From 72cefb773b66687ce62425d90b691f16d88aed6d Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 23 Sep 2026 14:20:02 +0000 Subject: [PATCH 01/26] session-types: legacy-rate-role-id-v1, the identity on the Id grammar, pinned in both languages --- packages/session-types/src/gameboy.ts | 46 ++- packages/session-types/tests/gameboy.test.ts | 21 ++ .../fixtures/gameboy-rate-roles.json | 332 ++++++++++++++++++ .../crates/fly-session-types/src/gameboy.rs | 54 +++ .../fly-session-types/tests/gameboy_legacy.rs | 41 +++ 5 files changed, 491 insertions(+), 3 deletions(-) create mode 100644 services/flysim/crates/fly-session-types/fixtures/gameboy-rate-roles.json diff --git a/packages/session-types/src/gameboy.ts b/packages/session-types/src/gameboy.ts index 261e708..ec44ba5 100644 --- a/packages/session-types/src/gameboy.ts +++ b/packages/session-types/src/gameboy.ts @@ -14,8 +14,8 @@ import { digestOf, fail } from './canonical'; import { readRational, readSchemaRef } from './common'; import { Reader, readArtifactRef, requireUnique, u64 } from './reader'; import type { ArtifactRef, Digest, Id, RationalNs, SchemaRef, TypedValue } from './scalar'; -import { isDigest } from './scalar'; -import { type AssetRef, readAssetRef } from './workers'; +import { isDigest, isId } from './scalar'; +import { type AssetRef, MAX_RATE_ROLES, readAssetRef } from './workers'; import { MAX_SLOTS, ROLLBACK_POLICY, SLOTS_CAPABILITY } from './extensions'; export const PROFILE_ID = 'gameboy-legacy-fafb-v783-v1'; @@ -93,7 +93,10 @@ export const PAYLOAD_SCHEMAS: readonly SchemaRef[] = [ /** The legacy profile document's AssetRef digest: SHA-256 of its canonical JSON. */ export const PROFILE_DIGEST = '41e5d1ac62ab23f1b2d7252d52faac08b269c85e6b4c9ed7a370c74032c60878'; -/** `ChannelName`: a decoder channel or rate-role name. Not an Id: legacy names carry '_'. */ +/** + * `ChannelName`: a decoder channel or rate-role name, `^[a-z][a-z0-9_]{0,63}$`. A subset of the + * `Id` grammar (which admits '_'); see `rateRoleId` below (amendment 2026-09-23). + */ export function isChannelName(value: unknown): value is string { return typeof value === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(value); } @@ -558,3 +561,40 @@ export function decoderConfigForm(config: DecoderConfigLike): unknown { export function decoderConfigDigest(config: DecoderConfigLike): Digest { return digestOf(decoderConfigForm(config)); } + +// Rate roles: legacy-rate-role-id-v1 (amendment 2026-09-23, AGENT-01) ---------------------- + +/** + * The mapping from a legacy rate-role name to `AgentGraph.rateRoles` / `rates[].roleId`. + * + * The contract left it open on the premise that `command_0`, `macro_go_item` and the rest are + * not `Id`s; they are, because the `Id` grammar `^[a-z0-9][a-z0-9._-]{0,63}$` admits '_'. So the + * mapping is the identity on the `Id` grammar and a name outside it has no roleId: the agent + * refuses such a dataset. `fly-session-types/src/gameboy.rs` is the twin and + * `fixtures/gameboy-rate-roles.json` holds both to it. + */ +export const RATE_ROLE_MAPPING = 'legacy-rate-role-id-v1'; + +/** The roleId of a legacy rate-role name: the name itself, when it is an Id. */ +export function rateRoleId(name: string): Id { + if (!isId(name)) { + fail(`${RATE_ROLE_MAPPING}: rate role ${JSON.stringify(name)} is not an Id and has no roleId`); + } + return name; +} + +/** The legacy rate-role name a roleId stands for: the inverse of `rateRoleId`. */ +export function rateRoleName(roleId: string): string { + if (!isId(roleId)) fail(`${RATE_ROLE_MAPPING}: ${JSON.stringify(roleId)} is not a roleId`); + return roleId; +} + +/** Maps a tracked-role list in order, holding it to `AgentGraph.rateRoles`' bounds. */ +export function rateRoleIds(names: readonly string[]): Id[] { + const ids = names.map(rateRoleId); + if (ids.length > MAX_RATE_ROLES) { + fail(`${RATE_ROLE_MAPPING}: ${ids.length} tracked rate roles; AgentGraph.rateRoles holds at most ${MAX_RATE_ROLES}`); + } + requireUnique(ids, 'rateRoles'); + return ids; +} diff --git a/packages/session-types/tests/gameboy.test.ts b/packages/session-types/tests/gameboy.test.ts index b92ebd9..a5cadea 100644 --- a/packages/session-types/tests/gameboy.test.ts +++ b/packages/session-types/tests/gameboy.test.ts @@ -174,3 +174,24 @@ test('the decoderConfigDigest vectors are what the TypeScript oracle preset comp assert.equal(example.decoderConfigDigest, cases[1]!.digest); assert.deepEqual(example.executor.macroChannels, cases[1]!.macroChannels); }); + +test('legacy-rate-role-id-v1 is the identity on the Id grammar and refuses the rest', () => { + const file = fixtures.load('gameboy-rate-roles.json') as Record; + assert.equal(file.mapping, gameboy.RATE_ROLE_MAPPING); + assert.ok(file.accepted.length > 0); + for (const { name, roleId } of file.accepted as { name: string; roleId: string }[]) { + assert.equal(gameboy.rateRoleId(name), roleId, name); + assert.equal(gameboy.rateRoleName(roleId), name, `${roleId} maps back`); + } + for (const { name } of file.refused as { name: string }[]) { + assert.throws(() => gameboy.rateRoleId(name), `${JSON.stringify(name)} has no roleId`); + assert.throws(() => gameboy.rateRoleName(name)); + } + const tracked = file.fafbTrackedRoles as string[]; + assert.deepEqual(gameboy.rateRoleIds(tracked), tracked); + for (const role of tracked.filter((r) => r.startsWith('macro_'))) { + assert.ok(gameboy.isChannelName(role)); + } + assert.throws(() => gameboy.rateRoleIds(Array.from({ length: 65 }, (_, i) => `role_${i}`))); + assert.throws(() => gameboy.rateRoleIds(['command_0', 'command_0'])); +}); diff --git a/services/flysim/crates/fly-session-types/fixtures/gameboy-rate-roles.json b/services/flysim/crates/fly-session-types/fixtures/gameboy-rate-roles.json new file mode 100644 index 0000000..b562ecb --- /dev/null +++ b/services/flysim/crates/fly-session-types/fixtures/gameboy-rate-roles.json @@ -0,0 +1,332 @@ +{ + "description": "legacy-rate-role-id-v1 (legacy-gameboy-v1 section 13, amendment 2026-09-23, AGENT-01): the roleId of a legacy rate-role name is the name itself when it matches the session Id grammar, and a name outside it has no roleId. fafbTrackedRoles is the rate-role list the kernel tracks on data/fafb-v783 in network order (AgentGraph.rateRoles order); fly-session's gated test recomputes it from the committed dataset. Both languages must map every accepted name to itself and back, and refuse every refused name.", + "mapping": "legacy-rate-role-id-v1", + "idPattern": "^[a-z0-9][a-z0-9._-]{0,63}$", + "fafbTrackedRoles": [ + "backward", + "command_0", + "command_1", + "command_2", + "command_3", + "command_4", + "command_5", + "command_6", + "command_7", + "forward", + "proboscis", + "reward_pam", + "steer_left", + "steer_right", + "macro_go_objective", + "macro_go_out", + "macro_go_warp", + "macro_go_route", + "macro_go_item", + "macro_go_npc", + "macro_go_frontier", + "macro_go_shop", + "macro_go_heal", + "macro_talk", + "macro_menu", + "macro_next", + "macro_yes", + "macro_no", + "macro_close", + "macro_confirm", + "macro_back", + "macro_move_1", + "macro_move_2", + "macro_move_3", + "macro_move_4", + "macro_switch", + "macro_item", + "macro_throw_ball", + "macro_run", + "macro_buy_potion", + "macro_buy_ball", + "macro_buy_antidote", + "macro_buy_repel", + "macro_heal", + "macro_leave" + ], + "accepted": [ + { + "name": "backward", + "roleId": "backward" + }, + { + "name": "command_0", + "roleId": "command_0" + }, + { + "name": "command_1", + "roleId": "command_1" + }, + { + "name": "command_2", + "roleId": "command_2" + }, + { + "name": "command_3", + "roleId": "command_3" + }, + { + "name": "command_4", + "roleId": "command_4" + }, + { + "name": "command_5", + "roleId": "command_5" + }, + { + "name": "command_6", + "roleId": "command_6" + }, + { + "name": "command_7", + "roleId": "command_7" + }, + { + "name": "forward", + "roleId": "forward" + }, + { + "name": "proboscis", + "roleId": "proboscis" + }, + { + "name": "reward_pam", + "roleId": "reward_pam" + }, + { + "name": "steer_left", + "roleId": "steer_left" + }, + { + "name": "steer_right", + "roleId": "steer_right" + }, + { + "name": "macro_go_objective", + "roleId": "macro_go_objective" + }, + { + "name": "macro_go_out", + "roleId": "macro_go_out" + }, + { + "name": "macro_go_warp", + "roleId": "macro_go_warp" + }, + { + "name": "macro_go_route", + "roleId": "macro_go_route" + }, + { + "name": "macro_go_item", + "roleId": "macro_go_item" + }, + { + "name": "macro_go_npc", + "roleId": "macro_go_npc" + }, + { + "name": "macro_go_frontier", + "roleId": "macro_go_frontier" + }, + { + "name": "macro_go_shop", + "roleId": "macro_go_shop" + }, + { + "name": "macro_go_heal", + "roleId": "macro_go_heal" + }, + { + "name": "macro_talk", + "roleId": "macro_talk" + }, + { + "name": "macro_menu", + "roleId": "macro_menu" + }, + { + "name": "macro_next", + "roleId": "macro_next" + }, + { + "name": "macro_yes", + "roleId": "macro_yes" + }, + { + "name": "macro_no", + "roleId": "macro_no" + }, + { + "name": "macro_close", + "roleId": "macro_close" + }, + { + "name": "macro_confirm", + "roleId": "macro_confirm" + }, + { + "name": "macro_back", + "roleId": "macro_back" + }, + { + "name": "macro_move_1", + "roleId": "macro_move_1" + }, + { + "name": "macro_move_2", + "roleId": "macro_move_2" + }, + { + "name": "macro_move_3", + "roleId": "macro_move_3" + }, + { + "name": "macro_move_4", + "roleId": "macro_move_4" + }, + { + "name": "macro_switch", + "roleId": "macro_switch" + }, + { + "name": "macro_item", + "roleId": "macro_item" + }, + { + "name": "macro_throw_ball", + "roleId": "macro_throw_ball" + }, + { + "name": "macro_run", + "roleId": "macro_run" + }, + { + "name": "macro_buy_potion", + "roleId": "macro_buy_potion" + }, + { + "name": "macro_buy_ball", + "roleId": "macro_buy_ball" + }, + { + "name": "macro_buy_antidote", + "roleId": "macro_buy_antidote" + }, + { + "name": "macro_buy_repel", + "roleId": "macro_buy_repel" + }, + { + "name": "macro_heal", + "roleId": "macro_heal" + }, + { + "name": "macro_leave", + "roleId": "macro_leave" + }, + { + "name": "up", + "roleId": "up" + }, + { + "name": "down", + "roleId": "down" + }, + { + "name": "left", + "roleId": "left" + }, + { + "name": "right", + "roleId": "right" + }, + { + "name": "a", + "roleId": "a" + }, + { + "name": "b", + "roleId": "b" + }, + { + "name": "start", + "roleId": "start" + }, + { + "name": "select", + "roleId": "select" + }, + { + "name": "kenyon", + "roleId": "kenyon" + }, + { + "name": "mbon", + "roleId": "mbon" + }, + { + "name": "visual_l1", + "roleId": "visual_l1" + }, + { + "name": "descending", + "roleId": "descending" + }, + { + "name": "motor", + "roleId": "motor" + }, + { + "name": "sensory", + "roleId": "sensory" + }, + { + "name": "7th.role-x", + "roleId": "7th.role-x" + }, + { + "name": "0", + "roleId": "0" + }, + { + "name": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "roleId": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr" + } + ], + "refused": [ + { + "name": "Command_0", + "why": "uppercase" + }, + { + "name": "_command", + "why": "leading underscore" + }, + { + "name": "-x", + "why": "leading hyphen" + }, + { + "name": "", + "why": "empty" + }, + { + "name": "steer left", + "why": "space" + }, + { + "name": "macro_é", + "why": "non-ASCII" + }, + { + "name": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "why": "65 characters" + } + ] +} diff --git a/services/flysim/crates/fly-session-types/src/gameboy.rs b/services/flysim/crates/fly-session-types/src/gameboy.rs index 29e88f8..c644612 100644 --- a/services/flysim/crates/fly-session-types/src/gameboy.rs +++ b/services/flysim/crates/fly-session-types/src/gameboy.rs @@ -413,6 +413,60 @@ pub fn extension_set_digest() -> String { canonical::digest_of(&extension_set()).expect("canonicalizable") } +// --------------------------------------------------------------------------------------------- +// Rate roles: `legacy-rate-role-id-v1` (amendment 2026-09-23, AGENT-01) + +/// The name of the mapping from a legacy rate-role name to `AgentGraph.rateRoles` / +/// `AgentTelemetry.rates[].roleId`. +/// +/// `legacy-gameboy-v1` section 13 left this to AGENT-01 on the premise that the legacy names +/// (`command_0`, `macro_go_item`, `steer_left`, ...) are not `Id`s. They are: the session `Id` +/// grammar is `^[a-z0-9][a-z0-9._-]{0,63}$` (`ipc-v1` section 1), which admits `_`, and every +/// role `data/fafb-v783` declares or the kernel tracks matches it. So the mapping is the identity +/// on the `Id` grammar, trivially reversible, and a name outside the grammar is not mapped at +/// all: the agent refuses to initialize on such a dataset rather than invent an encoding that +/// no consumer could read back. `fixtures/gameboy-rate-roles.json` pins it in both languages. +pub const RATE_ROLE_MAPPING: &str = "legacy-rate-role-id-v1"; + +/// The `roleId` a legacy rate-role name is published under: the name itself, when it is an +/// `Id`. Anything else is refused. +pub fn rate_role_id(name: &str) -> Result { + if is_id(name) { + Ok(name.to_owned()) + } else { + err(format!( + "{RATE_ROLE_MAPPING}: rate role {name:?} is not an Id (^[a-z0-9][a-z0-9._-]{{0,63}}$) and has no roleId" + )) + } +} + +/// The legacy rate-role name a `roleId` stands for: the inverse of [`rate_role_id`]. +pub fn rate_role_name(role_id: &str) -> Result { + if is_id(role_id) { + Ok(role_id.to_owned()) + } else { + err(format!("{RATE_ROLE_MAPPING}: {role_id:?} is not a roleId")) + } +} + +/// Maps a tracked-role list, in order, and holds it to `AgentGraph.rateRoles`' own bounds: +/// at most 64 (`MAX_RATE_ROLES`, the kernel's role bitmask) and unique. +pub fn rate_role_ids<'a>(names: impl IntoIterator) -> Result> { + let ids = names + .into_iter() + .map(rate_role_id) + .collect::>>()?; + if ids.len() > crate::workers::MAX_RATE_ROLES { + return err(format!( + "{RATE_ROLE_MAPPING}: {} tracked rate roles; AgentGraph.rateRoles holds at most {}", + ids.len(), + crate::workers::MAX_RATE_ROLES + )); + } + require_unique(ids.iter().map(String::as_str), "rateRoles")?; + Ok(ids) +} + // --------------------------------------------------------------------------------------------- // Scalars and helpers diff --git a/services/flysim/crates/fly-session-types/tests/gameboy_legacy.rs b/services/flysim/crates/fly-session-types/tests/gameboy_legacy.rs index c305f29..659fee7 100644 --- a/services/flysim/crates/fly-session-types/tests/gameboy_legacy.rs +++ b/services/flysim/crates/fly-session-types/tests/gameboy_legacy.rs @@ -348,3 +348,44 @@ fn the_extension_methods_check_their_scope() { assert_eq!(SLOTS_CAPABILITY, "gameboy-slots-v1"); assert_eq!(ROLLBACK_CAPABILITY, ROLLBACK_POLICY); } + +/// `legacy-rate-role-id-v1`: every accepted name is its own roleId and maps back; every refused +/// name has none. The TypeScript twin reads the same file. +#[test] +fn the_rate_role_mapping_is_the_identity_on_the_id_grammar_and_refuses_the_rest() { + let file = fixtures::load("gameboy-rate-roles.json").expect("gameboy-rate-roles.json"); + assert_eq!(file["mapping"].as_str(), Some(gameboy::RATE_ROLE_MAPPING)); + let accepted = file["accepted"].as_array().expect("accepted"); + assert!(!accepted.is_empty()); + for case in accepted { + let name = case["name"].as_str().expect("name"); + let role_id = case["roleId"].as_str().expect("roleId"); + assert_eq!(gameboy::rate_role_id(name).expect(name), role_id, "{name}"); + assert_eq!(gameboy::rate_role_name(role_id).expect(role_id), name, "{role_id} maps back"); + } + for case in file["refused"].as_array().expect("refused") { + let name = case["name"].as_str().expect("name"); + assert!(gameboy::rate_role_id(name).is_err(), "{name:?} must have no roleId"); + assert!(gameboy::rate_role_name(name).is_err(), "{name:?} is no roleId either"); + } + // The FAFB tracked list fits AgentGraph.rateRoles as it stands: <= 64, unique, in order. + let tracked: Vec<&str> = file["fafbTrackedRoles"] + .as_array() + .expect("fafbTrackedRoles") + .iter() + .map(|v| v.as_str().expect("a role name")) + .collect(); + let ids = gameboy::rate_role_ids(tracked.iter().copied()).expect("the FAFB roles map"); + assert_eq!(ids, tracked); + // Every decoder channel is a ChannelName, and every ChannelName is an Id, so a macro + // channel's role is its own roleId too. + for role in &tracked { + if role.starts_with("macro_") { + assert!(gameboy::is_channel_name(role)); + } + } + // The list bound and uniqueness are the contract's, not the mapping's convenience. + let many: Vec = (0..65).map(|i| format!("role_{i}")).collect(); + assert!(gameboy::rate_role_ids(many.iter().map(String::as_str)).is_err()); + assert!(gameboy::rate_role_ids(["command_0", "command_0"]).is_err()); +} From 9bdfb079e5aaa95aaa35eee510fce94dc50ebf3d Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 23 Sep 2026 14:45:25 +0000 Subject: [PATCH 02/26] fly-session: LegacyAgentWorker, the legacy Game Boy agent over the neural core Agent.Initialize checks the profile against the dataset fingerprint and warms up as the legacy fresh start does; Prepare applies sugar, ticks the 548625/32768 ms frame on the rational clock and decodes with gameboy-readout-context-v1; Commit installs the frame, stimulates, then reinforces once; Agent.Rollback is legacy-ratchet-rollback-v1's agent half; capture is agent_to_chunks in an envelope and a restore resets the readout transient as a fresh legacy process has it. --- services/flysim/Cargo.lock | 2 + services/flysim/crates/fly-session/Cargo.toml | 5 + .../crates/fly-session/src/legacy_agent.rs | 1796 +++++++++++++++++ services/flysim/crates/fly-session/src/lib.rs | 1 + .../flysim/crates/fly-session/src/worker.rs | 7 + 5 files changed, 1811 insertions(+) create mode 100644 services/flysim/crates/fly-session/src/legacy_agent.rs diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index 25f88d6..f0f4a3f 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -439,7 +439,9 @@ dependencies = [ name = "fly-session" version = "0.1.1" dependencies = [ + "flate2", "fly-session-types", + "flybrain-core", "flybus", "serde_json", "tempfile", diff --git a/services/flysim/crates/fly-session/Cargo.toml b/services/flysim/crates/fly-session/Cargo.toml index 25d9a76..9be8436 100644 --- a/services/flysim/crates/fly-session/Cargo.toml +++ b/services/flysim/crates/fly-session/Cargo.toml @@ -23,6 +23,11 @@ path = "src/bin/fly-session.rs" # Everything else this crate needs is std or Tokio. fly-session-types = { path = "../fly-session-types" } flybus = { path = "../flybus" } +# AGENT-01: the legacy agent worker is an adapter over the existing neural core (LIF kernel, +# plasticity, retina, fixed readout, checkpoint chunks). Pure Rust, no emulator. +flybrain-core = { path = "../flybrain-core" } +# The toy connectome fixture is written as gzipped `.binz` arrays, the dataset loader's format. +flate2 = { workspace = true } serde_json = { workspace = true } # `rt-multi-thread` is not only for the tests: a worker process and a dedicated-thread diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs new file mode 100644 index 0000000..a846993 --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -0,0 +1,1796 @@ +//! AGENT-01: the legacy agent worker, `gameboy-legacy-fafb-v783-v1` over the existing neural core. +//! +//! [`LegacyAgentWorker`] is a [`WorkerEndpoint`] with the agent role. It is a small adapter over +//! `flybrain-core`'s [`NeuralAgent`] primitives -- the LIF network, its plasticity, the retina and +//! the fixed Game Boy readout -- and it does **not** go through `NeuralAgent::tick`, because that +//! wrapper runs a whole legacy frame in one call and the session splits it in two: +//! +//! | Legacy `Sim::step_frame` | Here | +//! | --- | --- | +//! | drain commands: `stimulate(sugar)` | `Agent.Prepare`: `preStepStimulations`, in order | +//! | `network.step(ticks)`, 548625/32768 ms per frame | `Agent.Prepare`: the rational accumulator of `step-v1` section 5, whose ticks and remainders are the legacy f64 ones exactly (`legacy-gameboy-v1` section 3) | +//! | blocked rule, `decode_bound(rates, ms, boot, blocked, bound)` | `Agent.Prepare`, with `gameboy-readout-context-v1` | +//! | `set_visual_frame(frame)` | `Agent.Commit` step 1 | +//! | `stimulate(event.stimulation_ms)` per event | `Agent.Commit` step 2, `taskStimulations` in order | +//! | `reinforce(sum, ms)` if plasticity is enabled | `Agent.Commit` step 3, once | +//! | `location != last` restarts the blocked window | `Agent.Commit`, from `nextDecisionContext.location` | +//! | `recover_game`'s neural half | `Agent.Rollback` (`legacy-ratchet-rollback-v1`) | +//! | FLYSIM01 load, then a fresh process's transients | `State.StageRestore` + `ActivateRestore` (`legacy-transient-reset`) | +//! +//! The readout transient -- the held channel, the start of the blocked window and the last +//! location -- is private agent state (`legacy-gameboy-v1` section 5) and is never captured. +//! A fresh start and a restore both begin it exactly as a fresh legacy process does: no held +//! channel, no location, the window starting at brain time **0 ms**. So the first decode after a +//! restore passes the restored winner as `blocked` (section 14 and the port-contracts review, N1). +//! +//! Rate roles are published under `legacy-rate-role-id-v1` ([`gameboy::rate_role_id`]): the +//! identity on the `Id` grammar, which every legacy role name already satisfies. + +use std::collections::BTreeSet; +use std::path::PathBuf; +use std::sync::Arc; + +use fly_session_types::extensions::{ + AgentRollbackParams, AgentRollbackResult, METHOD_AGENT_ROLLBACK, ROLLBACK_CAPABILITY, +}; +use fly_session_types::gameboy::{self, ChannelsDecision, Location, ReadoutContext}; +use flybrain_core::agent::{AgentConfig as CoreAgentConfig, AgentState, NeuralAgent}; +use flybrain_core::dataset::{BrainDataset, MACRO_ROLE_PREFIX, load_brain_dataset_from_dir}; +use flybrain_core::decoder::gameboy::{gameboy_decoder_config_with_macros, to_button_mask}; +use flybrain_core::decoder::{DecoderConfig, ExclusiveGroup}; +use flybrain_core::envelope::{ + agent_from_chunks, agent_to_chunks, decode_envelope, encode_envelope, +}; +use flybrain_core::json::JsonValue; +use flybrain_core::lif::{LifConfig, SweepPlan, kernel_version}; +use serde_json::{Value, json}; + +use crate::clock::TickAccumulator; +// `crate::types` is this crate's facade over the shared `fly-session-types` crate. +use crate::types::*; +use crate::worker::{BoxFuture, HandlerCtx, HandlerReply, StatusCell, WorkerEndpoint}; + +// ------------------------------------------------------------------------------------------- +// Profiles + +/// The toy profile's id. A fixture profile for the committed toy connectome: every field is the +/// legacy profile's except the id, the dataset id and the fingerprint, and a profile never +/// reuses the legacy profile's id (`legacy-gameboy-v1` section 17). It is test identity, not a +/// production profile. +pub const TOY_PROFILE_ID: &str = "gameboy-legacy-toy-v1"; +/// The toy connectome's dataset id. +pub const TOY_DATASET_ID: &str = "legacy-toy"; +/// The schema-1 fingerprint of `fixtures/legacy-toy`, which the loader recomputes and the toy +/// golden test pins. +pub const TOY_FINGERPRINT: &str = "4014d84930520778281dba0000f97e07e36f200c045f9464f1fc860cb0d8efe6:\ +6a95a07f1598277333397b551c9b3a3d88b0c75a507123486810b83bc5deb88e:\ +6af524099ade9a45f6426eb2dc297306e8ecb2aa19fde7c5764fe8dda722d979:\ +f767d48ff556fceae996e2ac73c0d0871df71101db0af414a0ffcd0bfb678489:\ +525b5fe3910fd219ad7c989f977489fa98fe815a3eef95301626391a9ab126e6:\ +319fbbb4acc79b1711ce1dc9431df2b3c0be49ca04fdd703f1afa204bd3f6e5d:\ +49c2699978666f863cee2baf914167f00fa9a215ef4756536f8d6e64449ceb38"; + +/// The magic of the agent's capture payload: a `flybrain-core` checkpoint envelope whose +/// manifest and chunks are exactly `agent_to_chunks`, plus one `session` manifest member. +pub const PAYLOAD_MAGIC: &str = "FLYAGT01"; +/// The layout version of the `session` member. +pub const PAYLOAD_VERSION: u64 = 1; +/// The attachment a Commit reply carries the transition's spike bitset under. +pub const SPIKES_ATTACHMENT: &str = "telemetry.spikes"; +/// Bit `i` is neuron `i` in dataset order, little-endian within a byte, `ceil(neurons/8)` bytes: +/// the legacy feed's `spike_bitset` layout. +pub const SPIKES_CONTENT_TYPE: &str = "application/x-fly-spike-bitset"; +/// The one stimulus kind the profile supports. +pub const REWARD_PULSE: &str = gameboy::STIMULUS_REWARD_PULSE; + +/// Which profile document a worker is configured for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LegacyProfileKind { + /// `gameboy-legacy-fafb-v783-v1`, over `data/fafb-v783`. + Production, + /// [`TOY_PROFILE_ID`], over the committed toy connectome. + Toy, +} + +impl LegacyProfileKind { + pub fn label(&self) -> &'static str { + match self { + LegacyProfileKind::Production => "production", + LegacyProfileKind::Toy => "toy", + } + } + + pub fn parse(text: &str) -> Result { + match text { + "production" => Ok(LegacyProfileKind::Production), + "toy" => Ok(LegacyProfileKind::Toy), + other => Err(format!( + "unknown legacy profile {other:?}; production or toy" + )), + } + } + + pub fn profile(&self) -> LegacyAgentProfile { + match self { + LegacyProfileKind::Production => LegacyAgentProfile::production(), + LegacyProfileKind::Toy => LegacyAgentProfile::toy(), + } + } +} + +/// A profile document, its `AssetRef` and the dataset fingerprint it embeds. +#[derive(Clone, Debug)] +pub struct LegacyAgentProfile { + pub kind: LegacyProfileKind, + pub document: Value, + pub asset: AssetRef, + pub dataset_fingerprint: String, +} + +impl LegacyAgentProfile { + /// The one legacy profile of `legacy-gameboy-v1` section 2. + pub fn production() -> LegacyAgentProfile { + let document = DomainType::to_json(&gameboy::legacy_profile()); + LegacyAgentProfile { + kind: LegacyProfileKind::Production, + document, + asset: gameboy::profile_asset_ref(), + dataset_fingerprint: gameboy::FAFB_V783_FINGERPRINT.to_owned(), + } + } + + /// The toy fixture profile: the legacy document with the toy id, dataset and fingerprint. + pub fn toy() -> LegacyAgentProfile { + let mut document = DomainType::to_json(&gameboy::legacy_profile()); + document["profileId"] = Value::from(TOY_PROFILE_ID); + document["datasetId"] = Value::from(TOY_DATASET_ID); + document["datasetFingerprint"] = Value::from(TOY_FINGERPRINT); + let canonical = canonicalize(&document).expect("a profile document canonicalizes"); + LegacyAgentProfile { + kind: LegacyProfileKind::Toy, + asset: AssetRef { + id: TOY_PROFILE_ID.to_owned(), + digest: digest_of_bytes(canonical.as_bytes()), + byte_length: canonical.len() as u64, + format: gameboy::PROFILE_FORMAT.to_owned(), + }, + document, + dataset_fingerprint: TOY_FINGERPRINT.to_owned(), + } + } +} + +// ------------------------------------------------------------------------------------------- +// The decoder configuration digest + +fn group_form(group: Option<&ExclusiveGroup>) -> Value { + match group { + None => Value::Null, + Some(g) => json!({ + "channels": g.channels.iter() + .map(|(channel, role)| json!({"channel": channel, "role": role})) + .collect::>(), + "decisionMs": g.decision_ms, + "holdMs": g.hold_ms, + "hysteresis": g.hysteresis, + "fatigueGain": g.fatigue_gain, + "fatigueDecay": g.fatigue_decay, + "blockedFatigue": g.blocked_fatigue, + "blockedMs": g.blocked_ms, + }), + } +} + +/// The canonical form `gameboy-decoder-config-v1` of `legacy-gameboy-v1` section 12. +/// +/// `flysim`'s `legacy_profile_identity` test builds the same form and writes the shared vectors +/// in `fly-session-types/fixtures/gameboy-decoder-config.json`; this crate's tests hold this +/// function to those vectors, so the agent reports the digest its own decoder has. +pub fn decoder_config_form(config: &DecoderConfig) -> Value { + json!({ + "form": "gameboy-decoder-config-v1", + "exclusive": group_form(config.exclusive.as_ref()), + "macros": group_form(config.macros.as_ref()), + "pulses": config.pulses.iter().map(|p| json!({ + "channel": p.channel, + "role": p.role, + "holdMs": p.hold_ms, + "cooldownMs": p.cooldown_ms, + "threshold": p.threshold, + "boot": p.boot.map_or(Value::Null, |b| json!({"cooldownMs": b.cooldown_ms, "threshold": b.threshold})), + "throttleGroup": p.throttle_group.clone().map_or(Value::Null, Value::String), + })).collect::>(), + "clearLockoutMs": config.clear_lockout_ms, + }) +} + +/// `decoderConfigDigest`: the SHA-256 of the canonical form. +pub fn decoder_config_digest(config: &DecoderConfig) -> Digest { + digest_of(&decoder_config_form(config)).expect("a decoder form canonicalizes") +} + +// ------------------------------------------------------------------------------------------- +// Clock conversions + +/// The legacy f64 frame remainder (ms) as the exact `RationalNs` remainder. +/// +/// Every legacy remainder is a multiple of 2^-15 ms below one tick (`legacy-gameboy-v1` +/// section 3), so the conversion is exact; anything else is refused rather than rounded. +pub fn legacy_remainder_to_rational(ms: f64) -> Result { + let scaled = ms * 32_768.0; + if !scaled.is_finite() || scaled < 0.0 || scaled.fract() != 0.0 || scaled >= 32_768.0 { + return Err(format!( + "legacy remainder {ms} is not k/32768 ms below one tick" + )); + } + RationalNs::reduced(scaled as u128 * 1_000_000, 32_768).map_err(|e| e.0) +} + +/// The exact `RationalNs` remainder as the legacy f64 millisecond remainder. +pub fn rational_remainder_to_legacy(remainder: &RationalNs) -> Result { + let numerator = u128::from(remainder.numerator) * 32_768; + let denominator = u128::from(remainder.denominator) * 1_000_000; + if !numerator.is_multiple_of(denominator) { + return Err(format!( + "remainder {}/{} ns is not a multiple of 2^-15 ms", + remainder.numerator, remainder.denominator + )); + } + let k = numerator / denominator; + if k >= 32_768 { + return Err("a remainder must stay below one model tick".to_owned()); + } + Ok(k as f64 / 32_768.0) +} + +// ------------------------------------------------------------------------------------------- +// The readout transient + +/// The readout's private transient: the channel the direction group holds, the brain time at +/// which the blocked window last restarted, and the last location the task reported. +/// +/// `legacy-gameboy-v1` sections 5 and 14: never captured, and reset on Initialize and on every +/// restore to exactly what a fresh legacy process holds. +#[derive(Clone, Debug, PartialEq)] +pub struct ReadoutTransient { + pub held_channel: Option, + pub blocked_since_ms: f64, + pub location: Option, +} + +impl ReadoutTransient { + /// A fresh legacy process: no held channel, no location, the window starting at 0 ms. + pub fn legacy_reset() -> ReadoutTransient { + ReadoutTransient { + held_channel: None, + blocked_since_ms: 0.0, + location: None, + } + } +} + +/// The spike bitset of the legacy feed: neuron `i` fired at or after `since_ms`. +pub fn spike_bitset(last_spike_ms: &[f64], since_ms: f64, now_ms: f64) -> Vec { + let mut bytes = vec![0u8; last_spike_ms.len().div_ceil(8)]; + if now_ms <= since_ms { + return bytes; + } + for (index, last) in last_spike_ms.iter().enumerate() { + if *last >= since_ms { + bytes[index >> 3] |= 1 << (index & 7); + } + } + bytes +} + +// ------------------------------------------------------------------------------------------- +// Configuration + +/// One legacy agent worker's configuration. +#[derive(Clone, Debug)] +pub struct LegacyAgentConfig { + pub session_id: Id, + pub agent_id: Id, + pub incarnation_id: Id, + /// The launcher's thread allocation. `workerThreads > 1` parallelises the neuron sweep, + /// which `flybrain-core` guarantees does not change a result. + pub worker_threads: usize, + /// The dataset directory: `data/fafb-v783` for the production profile. + pub dataset_dir: PathBuf, + pub profile: LegacyProfileKind, + /// The composition's `executor.macroChannels`, in composition order; empty in raw mode. + pub macro_channels: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum AgentPhase { + Uninitialized, + Ready(u64), + Prepared(u64), + Failed, +} + +/// The decision context this worker holds for its next Prepare. +#[derive(Clone, Debug)] +struct HeldContext { + typed: TypedValue, + readout: ReadoutContext, + digest: Digest, +} + +/// A validated replacement state, invisible to the live session until it is activated. +struct StagedAgent { + token: Id, + checkpoint_id: Id, + scope: Scope, + agent: NeuralAgent, + dataset: Arc, + graph: AgentGraph, + accumulator: TickAccumulator, + context: HeldContext, + seed: i32, + reinforcements: u64, + committed_step: u64, +} + +/// The legacy agent worker endpoint. +pub struct LegacyAgentWorker { + config: LegacyAgentConfig, + profile: LegacyAgentProfile, + status: StatusCell, + phase: AgentPhase, + epoch: Option, + dataset: Option>, + graph: Option, + seed: i32, + agent: Option, + accumulator: Option, + transient: ReadoutTransient, + context: Option, + prepared: Option<(DomainRequestId, PreparedDecision)>, + /// The brain time before the in-flight transition's ticks: the spike window's start. + transition_start_ms: f64, + staged: Option, + activated: BTreeSet, + /// Every mutation this worker applied, reported as its progress counter. + mutations: u64, + /// Reinforcement calls applied since the fly's fresh start; captured. + reinforcements: u64, +} + +fn incompatible(message: impl std::fmt::Display) -> DomainError { + DomainError::before(ErrorCode::IncompatibleState, message) +} + +fn applied(code: ErrorCode, message: impl std::fmt::Display) -> DomainError { + DomainError::new(code, message, MutationCertainty::Applied) +} + +fn check_supported(stimulus: &Stimulus) -> DomainResult<()> { + stimulus.validate().map_err(DomainError::invalid)?; + if stimulus.kind_id != REWARD_PULSE { + return Err(DomainError::before( + ErrorCode::Unsupported, + format!( + "stimulus kind {} is not one this profile resolves; it supports {REWARD_PULSE}", + stimulus.kind_id + ), + )); + } + Ok(()) +} + +/// The dataset digest an `AgentGraph` attests: SHA-256 of the schema-1 fingerprint string. +pub fn dataset_digest(fingerprint: &str) -> Digest { + digest_of_bytes(fingerprint.as_bytes()) +} + +/// The index digest: the fingerprint (which covers the neuron order and every anatomical role) +/// plus the `macro_*` populations it deliberately does not cover, the profile's declared +/// `macro-roles-outside-fingerprint` exception. Two datasets that relabel the macro +/// populations differently have the same fingerprint and different index digests. +pub fn index_digest(dataset: &BrainDataset, fingerprint: &str) -> Digest { + let mut text = format!( + "fly-session/legacy-agent-index-v1\nfingerprint={fingerprint}\nneurons={}\n", + dataset.meta.neurons + ); + for (name, neurons) in &dataset.meta.roles { + if name.starts_with(MACRO_ROLE_PREFIX) { + let list: Vec = neurons.iter().map(u32::to_string).collect(); + text.push_str(&format!("role={name}:{}\n", list.join(","))); + } + } + digest_of_bytes(text.as_bytes()) +} + +/// The capture compatibility digest (`workers-v1` section 2) of a legacy agent. +pub fn compatibility_digest( + agent_id: &Id, + profile: &AssetRef, + graph: &AgentGraph, + seed: i32, +) -> Digest { + crate::agent::agent_compatibility_digest( + agent_id, + &profile.digest, + &graph.dataset_digest, + gameboy::KERNEL_VERSION, + gameboy::PLASTICITY_VERSION, + seed, + &graph.index_digest, + ) +} + +/// The telemetry of an agent at its current state. +/// +/// `learning` maps the legacy counters onto the contract's, which requires +/// `changed <= updates`: `updates` is the reinforcement calls this agent applied (one per +/// commit while the rule is enabled, zero sums included), and `changed` is the legacy +/// `plasticity.updates`, the reinforcements that moved at least one gain. The legacy +/// per-synapse count (`LearningStats.changed`, gains off 1.0) is not a counter of updates and +/// is not carried; it stays readable from the captured state. +pub fn telemetry_of(agent: &NeuralAgent, brain_ticks: u64, reinforcements: u64) -> AgentTelemetry { + let network = &agent.network; + let plasticity = &network.plasticity; + AgentTelemetry { + brain_ticks, + population_rate_hz: network.population_rate, + rates: network + .rates + .iter() + .map(|(name, hz)| RateSample { + role_id: name.clone(), + hz, + }) + .collect(), + learning: LearningTelemetry { + enabled: plasticity.enabled, + updates: reinforcements, + changed: plasticity.updates() as u64, + signal: plasticity.signal(), + }, + stimulus_remaining_ms: Some(network.reward_remaining()), + } +} + +/// `gameboy-channels-v1` from a decode's active set: the button mask in `GAMEBOY_BUTTONS` +/// order, and the first bound channel the decode holds, which is exactly the channel the legacy +/// macro layer's `asked` would start. +pub fn channels_decision(active: &[String], bound: &[String]) -> ChannelsDecision { + let mask = to_button_mask(active); + let mut buttons = [false; 8]; + for (bit, down) in buttons.iter_mut().enumerate() { + *down = mask & (1 << bit) != 0; + } + let macro_channel = bound + .iter() + .find(|channel| active.contains(channel)) + .cloned(); + ChannelsDecision { + buttons, + macro_channel, + } +} + +impl LegacyAgentWorker { + pub fn new(config: LegacyAgentConfig) -> LegacyAgentWorker { + LegacyAgentWorker { + profile: config.profile.profile(), + config, + status: StatusCell::new(), + phase: AgentPhase::Uninitialized, + epoch: None, + dataset: None, + graph: None, + seed: 0, + agent: None, + accumulator: None, + transient: ReadoutTransient::legacy_reset(), + context: None, + prepared: None, + transition_start_ms: 0.0, + staged: None, + activated: BTreeSet::new(), + mutations: 0, + reinforcements: 0, + } + } + + pub fn status(&self) -> StatusCell { + self.status.clone() + } + + /// The readout transient, for an in-process test. + pub fn transient(&self) -> &ReadoutTransient { + &self.transient + } + + /// The neural agent, for an in-process test. + pub fn agent(&self) -> Option<&NeuralAgent> { + self.agent.as_ref() + } + + fn bump(&mut self) { + self.mutations += 1; + self.status.advance_to(self.mutations); + } + + fn check_epoch(&self, scope: &Scope) -> DomainResult<()> { + if scope.session_id != self.config.session_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "this worker belongs to another session", + )); + } + match &self.epoch { + Some(epoch) if *epoch == scope.epoch => Ok(()), + Some(_) => Err(DomainError::before( + ErrorCode::StaleEpoch, + "this scope names an epoch this worker has left", + )), + None => Err(DomainError::before( + ErrorCode::InvalidPhase, + "this worker is uninitialized", + )), + } + } + + /// Reads and validates a decision context against the composition's macro channels. + fn read_context(&self, typed: &TypedValue) -> DomainResult { + typed.validate().map_err(DomainError::invalid)?; + let readout = ReadoutContext::from_typed(typed).map_err(|e| { + DomainError::before( + ErrorCode::IdentityMismatch, + format!( + "the decision context is not gameboy-readout-context-v1: {}", + e.0 + ), + ) + })?; + readout + .validate_against(&self.config.macro_channels) + .map_err(DomainError::invalid)?; + Ok(HeldContext { + typed: typed.clone(), + readout, + digest: typed.digest(), + }) + } + + /// Reads the one `lcd` view of a sensory input: 160 x 144 RGBA8, produced at the observed + /// boundary, from a live owned attachment. A missing view is an error, never zero input. + async fn read_lcd(&self, ctx: &HandlerCtx<'_>, input: &SensoryInput) -> DomainResult> { + input + .validate_for_profile(false) + .map_err(DomainError::invalid)?; + let [view] = input.views.as_slice() else { + return Err(DomainError::invalid(format!( + "this profile consumes exactly one view, {}; the input has {}", + gameboy::VIEW_ID, + input.views.len() + ))); + }; + if view.view_id != gameboy::VIEW_ID { + return Err(DomainError::invalid(format!( + "this profile consumes the view {}, not {}", + gameboy::VIEW_ID, + view.view_id + ))); + } + if view.produced_step != input.boundary { + return Err(DomainError::invalid( + "the lcd view has no render delay: it must be produced at the observed boundary", + )); + } + let expected = gameboy::VIEW_WIDTH * gameboy::VIEW_HEIGHT * 4; + let name = crate::media::view_attachment(&view.view_id); + let artifact = ctx.artifact(&name)?; + if artifact.reference() != &view.pixels { + return Err(DomainError::before( + ErrorCode::BufferInvalid, + format!("attachment {name} is not the artifact the payload names"), + )); + } + let bytes = artifact.read_all().await.map_err(|e| { + DomainError::before( + ErrorCode::BufferInvalid, + format!("view {} could not be read: {}", view.view_id, e.message), + ) + })?; + if bytes.len() as u64 != expected || view.pixels.byte_length != expected { + return Err(DomainError::before( + ErrorCode::BufferInvalid, + format!( + "the lcd view must be {expected} RGBA bytes, found {}", + bytes.len() + ), + )); + } + Ok(bytes) + } + + /// Loads the dataset once and checks it is the one the profile embeds. + fn dataset(&mut self) -> DomainResult> { + if let Some(dataset) = &self.dataset { + return Ok(dataset.clone()); + } + let dir = &self.config.dataset_dir; + let dataset = load_brain_dataset_from_dir(dir).map_err(|e| { + DomainError::before( + ErrorCode::IncompatibleState, + format!("the dataset at {} does not load: {e}", dir.display()), + ) + })?; + match dataset.fingerprint.as_deref() { + Some(fingerprint) if fingerprint == self.profile.dataset_fingerprint => {} + found => { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + format!( + "the dataset at {} is not the one {} embeds: fingerprint {} (expected {})", + dir.display(), + self.profile.asset.id, + found.unwrap_or("none"), + self.profile.dataset_fingerprint + ), + )); + } + } + let dataset = Arc::new(dataset); + self.dataset = Some(dataset.clone()); + Ok(dataset) + } + + /// Builds a network and readout over `dataset`, before any state is installed, and checks + /// every identity the profile pins: kernel and plasticity versions, frame size, rate roles. + fn build_agent( + &self, + dataset: Arc, + seed: i32, + ) -> DomainResult<(NeuralAgent, AgentGraph)> { + let lif = LifConfig { + seed, + ..LifConfig::default() + }; + let kernel = kernel_version(&lif); + if kernel != gameboy::KERNEL_VERSION { + return Err(incompatible(format!( + "seed {seed} is not this profile's: its kernel version would be {kernel}, and the \ + profile pins {} (the default seed, 22222)", + gameboy::KERNEL_VERSION + ))); + } + let channels: Vec<&str> = self + .config + .macro_channels + .iter() + .map(String::as_str) + .collect(); + let mut config = + CoreAgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels)); + config.lif = lif; + config.warmup_ms = gameboy::WARMUP_MS; + let mut agent = NeuralAgent::new(dataset.clone(), config) + .map_err(|e| incompatible(format!("the agent does not build: {e}")))?; + if agent.network.version != gameboy::KERNEL_VERSION + || agent.network.plasticity.version != gameboy::PLASTICITY_VERSION + { + return Err(incompatible(format!( + "the built network is {} / {}, not the profile's {} / {}", + agent.network.version, + agent.network.plasticity.version, + gameboy::KERNEL_VERSION, + gameboy::PLASTICITY_VERSION + ))); + } + if (u64::from(agent.frame.width), u64::from(agent.frame.height)) + != (gameboy::VIEW_WIDTH, gameboy::VIEW_HEIGHT) + { + return Err(incompatible( + "the retina is not the profile's 160 x 144 lcd", + )); + } + let names: Vec<&str> = agent.network.rates.keys().map(String::as_str).collect(); + let rate_roles = gameboy::rate_role_ids(names.iter().copied()).map_err(|e| { + incompatible(format!( + "the dataset's rate roles cannot be published: {}", + e.0 + )) + })?; + for channel in &self.config.macro_channels { + if !names.contains(&channel.as_str()) { + return Err(incompatible(format!( + "macro channel {channel} reads a rate role this dataset does not track" + ))); + } + } + if self.config.worker_threads > 1 { + let plan = SweepPlan::with_threads(self.config.worker_threads) + .map_err(|e| DomainError::invalid(format!("sweep plan: {e}")))?; + agent.set_sweep_plan(plan); + } + let fingerprint = self.profile.dataset_fingerprint.clone(); + let graph = AgentGraph { + dataset_digest: dataset_digest(&fingerprint), + index_digest: index_digest(&dataset, &fingerprint), + neuron_count: dataset.meta.neurons as u64, + rate_roles, + supported_stimuli: vec![REWARD_PULSE.to_owned()], + }; + Ok((agent, graph)) + } + + fn telemetry(&self) -> AgentTelemetry { + let agent = self.agent.as_ref().expect("initialized"); + let accumulator = self.accumulator.as_ref().expect("initialized"); + telemetry_of(agent, accumulator.brain_ticks(), self.reinforcements) + } + + // --------------------------------------------------------------------------------------- + // Agent.Initialize + + async fn initialize(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + if self.phase != AgentPhase::Uninitialized { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "Agent.Initialize is only allowed on an uninitialized agent; restore uses the \ + state interface", + )); + } + if scope.step != 0 { + return Err(DomainError::before( + ErrorCode::FutureStep, + "Agent.Initialize uses the new epoch at step 0", + )); + } + if scope.session_id != self.config.session_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "this worker belongs to another session", + )); + } + let params: AgentInitializeParams = ctx.params()?; + if params.agent_id != self.config.agent_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "Agent.Initialize names another agent", + )); + } + if params.worker_threads == 0 { + return Err(DomainError::invalid("workerThreads must be >= 1")); + } + if params.worker_threads > self.config.worker_threads as u64 { + return Err(DomainError::before( + ErrorCode::Busy, + format!( + "Agent.Initialize asks for {} worker threads; the launcher allocated {}", + params.worker_threads, self.config.worker_threads + ), + )); + } + // The profile identity: the document this worker is configured for, byte for byte. + if params.profile != self.profile.asset { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + format!( + "Agent.Initialize names profile {} ({}); this worker serves {} ({})", + params.profile.id, + params.profile.digest, + self.profile.asset.id, + self.profile.asset.digest + ), + )); + } + if params.initial_input.boundary != 0 { + return Err(DomainError::invalid( + "the initial input must observe boundary 0", + )); + } + let context = self.read_context(¶ms.initial_decision_context)?; + let frame = self.read_lcd(ctx, ¶ms.initial_input).await?; + // Everything above is validated; now the dataset and the model. The dataset is checked + // against the fingerprint the profile embeds before a network is built over it. + let dataset = self.dataset()?; + let (mut agent, graph) = self.build_agent(dataset, params.seed)?; + + // Warm-up with learning disabled, calibration on the settled rates, then the first + // frame -- `NeuralAgent::warmup`, which is what the legacy fresh start calls. + let mut accumulator = TickAccumulator::new(gameboy::tick_duration()) + .map_err(|e| applied(ErrorCode::Internal, e))?; + agent + .warmup(Some(&frame)) + .map_err(|e| applied(ErrorCode::BackendFailure, format!("warm-up: {e}")))?; + accumulator + .warm_up(gameboy::WARMUP_MS) + .map_err(|e| applied(ErrorCode::Internal, e))?; + if agent.network.ms != accumulator.brain_ticks() as f64 { + return Err(applied( + ErrorCode::Internal, + "the brain clock after warm-up is not the accumulator's tick count", + )); + } + + self.seed = params.seed; + self.agent = Some(agent); + self.graph = Some(graph.clone()); + self.accumulator = Some(accumulator); + // A fresh legacy process: the context's location is not adopted as the last location. + // The legacy loop only takes a location at the end of a frame, so frame one's commit + // is where the window first restarts on it. + self.transient = ReadoutTransient::legacy_reset(); + self.transition_start_ms = gameboy::WARMUP_MS as f64; + let digest = context.digest.clone(); + self.context = Some(context); + self.epoch = Some(scope.epoch.clone()); + self.phase = AgentPhase::Ready(0); + self.bump(); + self.status.set_state(WorkerState::Ready); + self.status.set_scope(Some(scope.clone())); + + let result = AgentInitializeResult { + agent_id: self.config.agent_id.clone(), + profile_digest: self.profile.asset.digest.clone(), + tick_duration: gameboy::tick_duration(), + warmup_ticks: gameboy::WARMUP_MS, + committed_step: 0, + decision_context_digest: digest, + telemetry: self.telemetry(), + graph, + }; + result + .validate() + .map_err(|e| applied(ErrorCode::Internal, e.0))?; + Ok(HandlerReply::from(&result)) + } + + // --------------------------------------------------------------------------------------- + // Agent.Prepare + + async fn prepare(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + self.check_epoch(&scope)?; + let AgentPhase::Ready(k) = self.phase.clone() else { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + format!( + "Agent.Prepare needs Ready(k); this worker is {:?}", + self.phase + ), + )); + }; + if scope.step != k { + return Err(DomainError::before( + if scope.step < k { + ErrorCode::StaleStep + } else { + ErrorCode::FutureStep + }, + "Agent.Prepare names a step other than this worker's committed boundary", + )); + } + let params: PrepareParams = ctx.params()?; + if params.agent_id != self.config.agent_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "Agent.Prepare names another agent", + )); + } + if params.profile_digest != self.profile.asset.digest { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "Agent.Prepare names another profile", + )); + } + let context = self.context.clone().expect("initialized"); + if params.decision_context_digest != context.digest { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "the cached decision context digest does not match", + )); + } + if params.interval != gameboy::step_duration() { + return Err(DomainError::invalid( + "this profile's interval is one Game Boy frame, 8572265625/512 ns", + )); + } + if params.pre_step_stimulations.len() > MAX_STIMULI { + return Err(DomainError::invalid("at most 64 pre-step stimulations")); + } + for stimulus in ¶ms.pre_step_stimulations { + check_supported(stimulus)?; + } + + self.status.set_state(WorkerState::Preparing); + // 1. Admitted pre-step stimulation (sugar), in command order: the legacy drain. + let agent = self.agent.as_mut().expect("initialized"); + for stimulus in ¶ms.pre_step_stimulations { + agent.network.stimulate(stimulus.duration_ms); + } + // 2. The frame's whole ticks. + let accumulator = self.accumulator.as_mut().expect("initialized"); + let ticks = accumulator + .advance(¶ms.interval) + .map_err(|e| applied(ErrorCode::Internal, e))?; + let brain_ticks = accumulator.brain_ticks(); + let remainder = accumulator.remainder(); + self.transition_start_ms = agent.network.ms; + agent.network.step(ticks); + if agent.network.ms != brain_ticks as f64 { + return Err(applied( + ErrorCode::Internal, + "the brain clock is not the accumulator's tick count", + )); + } + // 3. The fixed readout with the declared context, and the blocked-direction rule on + // the agent's own held channel, clock and location history (`docs/readout.md`). + let ms = agent.network.ms; + let rates = agent.network.rates.clone(); + let blocked_ms = agent.decoder.blocked_ms(); + let blocked = (blocked_ms > 0.0 && ms - self.transient.blocked_since_ms >= blocked_ms) + .then(|| agent.decoder.current()) + .flatten() + .map(str::to_string); + let bound = context.readout.bound.clone(); + // Raw mode has no macro group, and the legacy loop passes `None` there. + let mask_bound = (!self.config.macro_channels.is_empty()).then_some(bound.as_slice()); + let active = agent.decoder.decode_bound( + &rates, + ms, + context.readout.boot, + blocked.as_deref(), + mask_bound, + ); + // A new winner starts its own window. + let held = agent.decoder.current().map(str::to_string); + if held != self.transient.held_channel { + self.transient.held_channel = held; + self.transient.blocked_since_ms = ms; + } + let decision = channels_decision(&active, &bound); + decision + .validate_against(&context.readout) + .map_err(|e| applied(ErrorCode::Internal, e.0))?; + let prepared = PreparedDecision { + agent_id: self.config.agent_id.clone(), + ticks_advanced: ticks, + brain_ticks, + remainder, + decision: decision.to_typed(), + }; + self.prepared = Some((ctx.request.request_id.clone(), prepared.clone())); + self.phase = AgentPhase::Prepared(k); + self.bump(); + self.status.set_state(WorkerState::Prepared); + Ok(HandlerReply::from(&prepared)) + } + + // --------------------------------------------------------------------------------------- + // Agent.Commit + + async fn commit(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + self.check_epoch(&scope)?; + let AgentPhase::Prepared(k) = self.phase.clone() else { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + format!( + "Agent.Commit needs Prepared(k); this worker is {:?}", + self.phase + ), + )); + }; + if scope.step != k { + return Err(DomainError::before( + if scope.step < k { + ErrorCode::StaleStep + } else { + ErrorCode::FutureStep + }, + "Agent.Commit must carry the step of its transition, not the new boundary", + )); + } + let params: CommitParams = ctx.params()?; + params + .validate_against_scope(&scope) + .map_err(DomainError::invalid)?; + if params.agent_id != self.config.agent_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "Agent.Commit names another agent", + )); + } + let (prepared_request, _) = self.prepared.as_ref().expect("prepared"); + if params.prepared_request_id != *prepared_request { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "Agent.Commit does not match this worker's Prepare request", + )); + } + if params.rewards.len() > MAX_REWARDS || params.task_stimulations.len() > MAX_STIMULI { + return Err(DomainError::invalid( + "at most 64 rewards and 64 stimulations", + )); + } + for reward in ¶ms.rewards { + reward.validate().map_err(DomainError::invalid)?; + } + for stimulus in ¶ms.task_stimulations { + check_supported(stimulus)?; + } + let context = self.read_context(¶ms.next_decision_context)?; + // The complete request and its owned artifact are validated before anything applies. + let frame = self.read_lcd(ctx, ¶ms.next_input).await?; + + self.status.set_state(WorkerState::Committing); + let agent = self.agent.as_mut().expect("initialized"); + // 1. Install the next input: the frame the environment just produced. + let (width, height) = (agent.frame.width, agent.frame.height); + agent.network.set_visual_frame(&frame, width, height); + // 2. Task stimulation, in event order. + for stimulus in ¶ms.task_stimulations { + agent.network.stimulate(stimulus.duration_ms); + } + // 3. One reinforcement with the sum, in event order, at the current brain time. The + // legacy loop gates it on the rule being enabled and never skips a zero sum. + let ms = agent.network.ms; + let mut total = 0.0f64; + for reward in ¶ms.rewards { + total += reward.value; + } + if agent.network.plasticity.enabled { + agent.network.plasticity.reinforce(total, ms); + self.reinforcements += 1; + } + // The blocked window's other reset: the player moved. `None` is no information. + if let Some(location) = context.readout.location + && Some(location) != self.transient.location + { + self.transient.location = Some(location); + self.transient.blocked_since_ms = ms; + } + let spikes = spike_bitset(&agent.network.last_spike_ms, self.transition_start_ms, ms); + // 4. Retain the next context and acknowledge k+1. + let digest = context.digest.clone(); + self.context = Some(context); + self.prepared = None; + self.phase = AgentPhase::Ready(k + 1); + self.bump(); + let result = AgentCommitResult { + agent_id: self.config.agent_id.clone(), + committed_step: k + 1, + decision_context_digest: digest, + telemetry: self.telemetry(), + }; + let artifact = crate::media::seal_copy(ctx.client, SPIKES_CONTENT_TYPE.to_owned(), &spikes) + .await + .map_err(|e| applied(e.code, e.message))?; + self.status.set_state(WorkerState::Ready); + self.status + .set_scope(Some(scope_at(&scope.session_id, &scope.epoch, k + 1))); + Ok(HandlerReply::with_artifacts( + object(result.to_json()), + vec![(SPIKES_ATTACHMENT.to_owned(), artifact)], + )) + } + + // --------------------------------------------------------------------------------------- + // Agent.Rollback: legacy-ratchet-rollback-v1 + + async fn rollback(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + if scope.session_id != self.config.session_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "this worker belongs to another session", + )); + } + let params: AgentRollbackParams = ctx.params()?; + params + .validate_against_scope(&scope) + .map_err(DomainError::invalid)?; + if params.agent_id != self.config.agent_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "Agent.Rollback names another agent", + )); + } + match &self.epoch { + None => { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "this worker is uninitialized", + )); + } + Some(epoch) if *epoch == scope.epoch => { + return Err(DomainError::before( + ErrorCode::StaleEpoch, + "Agent.Rollback moves to a new epoch; this worker is already in it", + )); + } + Some(epoch) if *epoch != params.prior_epoch => { + return Err(DomainError::before( + ErrorCode::StaleEpoch, + format!( + "Agent.Rollback names prior epoch {}; this worker is in {epoch}", + params.prior_epoch + ), + )); + } + Some(_) => {} + } + let AgentPhase::Ready(k) = self.phase.clone() else { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + format!( + "Agent.Rollback needs Ready(k); this worker is {:?}", + self.phase + ), + )); + }; + if scope.step != k { + return Err(DomainError::before( + if scope.step < k { + ErrorCode::StaleStep + } else { + ErrorCode::FutureStep + }, + "Agent.Rollback is applied at this worker's committed boundary", + )); + } + let context = self.read_context(¶ms.decision_context)?; + let frame = self.read_lcd(ctx, ¶ms.input).await?; + + self.status.set_state(WorkerState::Restoring); + let agent = self.agent.as_mut().expect("initialized"); + let ms = agent.network.ms; + // The neural half of `recover_game`, in its order: decoder holds, eligibility, frame. + agent.decoder.clear_holds(ms); + agent.network.plasticity.clear_eligibility(ms); + let (width, height) = (agent.frame.width, agent.frame.height); + agent.network.set_visual_frame(&frame, width, height); + // `Sim::recover`: the location from the restored world, no held channel, the window + // restarting now. + self.transient = ReadoutTransient { + held_channel: None, + blocked_since_ms: ms, + location: context.readout.location, + }; + self.transition_start_ms = ms; + let digest = context.digest.clone(); + self.context = Some(context); + self.epoch = Some(scope.epoch.clone()); + self.prepared = None; + self.phase = AgentPhase::Ready(k); + self.bump(); + let result = AgentRollbackResult { + agent_id: self.config.agent_id.clone(), + committed_step: k, + decision_context_digest: digest, + telemetry: self.telemetry(), + }; + result + .validate_against_scope(&scope) + .map_err(|e| applied(ErrorCode::Internal, e.0))?; + self.status.set_state(WorkerState::Ready); + self.status.set_scope(Some(scope.clone())); + Ok(HandlerReply::new(object(result.to_json()))) + } + + // --------------------------------------------------------------------------------------- + // State.Capture / StageRestore / ActivateRestore + + /// The capture payload: `agent_to_chunks` in a checkpoint envelope, plus a `session` + /// manifest member with the accumulator, the context and the identities. The readout + /// transient is not in it (`legacy-transient-reset`). + fn payload(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult> { + let agent = self.agent.as_ref().expect("initialized"); + let accumulator = self.accumulator.as_ref().expect("initialized"); + let context = self.context.as_ref().expect("initialized"); + let mut state = agent.export_state(); + // The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`). + state.remainder = rational_remainder_to_legacy(&accumulator.remainder()) + .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?; + let chunks = agent_to_chunks(&state); + let channels: Vec<&str> = self + .config + .macro_channels + .iter() + .map(String::as_str) + .collect(); + let session = json!({ + "payloadVersion": PAYLOAD_VERSION, + "kind": "legacy-agent", + "agentId": self.config.agent_id, + "checkpointId": checkpoint_id, + "sourceScope": scope.to_json(), + "committedStep": k.to_string(), + "profile": self.profile.asset.to_json(), + "seed": self.seed, + "reinforcements": self.reinforcements.to_string(), + "kernelVersion": gameboy::KERNEL_VERSION, + "plasticityVersion": gameboy::PLASTICITY_VERSION, + "macroChannels": self.config.macro_channels, + "decoderConfigDigest": decoder_config_digest(&gameboy_decoder_config_with_macros(&channels)), + "accumulator": { + "tickDuration": accumulator.tick_duration().to_json(), + "remainder": accumulator.remainder().to_json(), + "executedTicks": accumulator.executed_ticks().to_string(), + "warmupOffset": accumulator.warmup_offset().to_string(), + }, + "context": context.typed.to_json(), + }); + let mut manifest = chunks.manifest; + let session = JsonValue::parse(&session.to_string()).map_err(|e| { + DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None) + })?; + manifest.set("session", session); + encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| { + DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None) + }) + } + + async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + self.check_epoch(&scope)?; + let AgentPhase::Ready(k) = self.phase.clone() else { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + format!( + "State.Capture needs a quiescent Ready(k); this worker is {:?}", + self.phase + ), + )); + }; + if scope.step != k { + return Err(DomainError::before( + if scope.step < k { + ErrorCode::StaleStep + } else { + ErrorCode::FutureStep + }, + "State.Capture names a boundary this worker is not at", + )); + } + let params: CaptureParams = ctx.params()?; + let previous = self.status.state(); + self.status.set_state(WorkerState::Capturing); + let bytes = self.payload(¶ms.checkpoint_id, &scope, k); + let bytes = match bytes { + Ok(bytes) => bytes, + Err(e) => { + self.status.set_state(previous); + return Err(e); + } + }; + let digest = digest_of_bytes(&bytes); + let artifact = crate::state::seal_payload(ctx.client, &bytes, &digest).await; + self.status.set_state(previous); + let artifact = artifact?; + let graph = self.graph.as_ref().expect("initialized"); + let result = CaptureResult { + checkpoint_id: params.checkpoint_id, + boundary: k, + compatibility_digest: compatibility_digest( + &self.config.agent_id, + &self.profile.asset, + graph, + self.seed, + ), + payload: artifact.reference().clone(), + }; + Ok(HandlerReply::with_artifacts( + object(result.to_json()), + vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)], + )) + } + + async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + if scope.session_id != self.config.session_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "this worker belongs to another session", + )); + } + match &self.phase { + AgentPhase::Uninitialized | AgentPhase::Ready(_) => {} + other => { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + format!( + "State.StageRestore needs an uninitialized replacement or a quiescent \ + worker; this worker is {other:?}" + ), + )); + } + } + if let Some(epoch) = &self.epoch + && *epoch == scope.epoch + { + return Err(DomainError::before( + ErrorCode::StaleEpoch, + "State.StageRestore proposes the epoch this worker is already running", + )); + } + let params: StageRestoreParams = ctx.params()?; + if params.source_scope.step != scope.step { + return Err(DomainError::invalid( + "State.StageRestore's scope step must be the source boundary", + )); + } + let artifact = ctx.artifact(crate::state::PAYLOAD_ATTACHMENT)?; + if artifact.reference() != ¶ms.payload { + return Err(DomainError::before( + ErrorCode::BufferInvalid, + "the staged payload attachment is not the artifact the request names", + )); + } + let bytes = artifact.read_all().await.map_err(|e| { + DomainError::before( + ErrorCode::BufferInvalid, + format!("the staged payload could not be read: {}", e.message), + ) + })?; + let declared = params + .payload + .digest + .clone() + .ok_or_else(|| incompatible("a checkpoint payload must carry a content digest"))?; + let actual = digest_of_bytes(&bytes); + if actual != declared || bytes.len() as u64 != params.payload.byte_length { + return Err(incompatible( + "the staged payload is not the content the request declares", + )); + } + let parts = decode_envelope(&bytes, PAYLOAD_MAGIC).map_err(|e| { + incompatible(format!( + "the staged payload is not a {PAYLOAD_MAGIC} envelope: {e}" + )) + })?; + let session = parts + .manifest + .get("session") + .ok_or_else(|| incompatible("the agent payload has no session member"))?; + let session: Value = serde_json::from_str(&session.stringify()) + .map_err(|e| incompatible(format!("the session member is not JSON: {e}")))?; + let text = |key: &str| -> DomainResult { + session + .get(key) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| incompatible(format!("the agent payload has no {key}"))) + }; + if session.get("payloadVersion").and_then(Value::as_u64) != Some(PAYLOAD_VERSION) { + return Err(incompatible("the agent payload is another payload version")); + } + if text("kind")? != "legacy-agent" { + return Err(incompatible("this payload is not a legacy agent's state")); + } + if text("agentId")? != self.config.agent_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "the staged payload belongs to another agent", + )); + } + if text("checkpointId")? != params.checkpoint_id { + return Err(incompatible( + "the staged payload belongs to another checkpoint", + )); + } + if text("kernelVersion")? != gameboy::KERNEL_VERSION + || text("plasticityVersion")? != gameboy::PLASTICITY_VERSION + { + return Err(incompatible( + "the staged payload was captured under another numerical model", + )); + } + let source_scope = Scope::from_json( + session + .get("sourceScope") + .ok_or_else(|| incompatible("the agent payload has no sourceScope"))?, + ) + .map_err(|e| incompatible(format!("the agent payload's sourceScope: {}", e.0)))?; + if source_scope != params.source_scope { + return Err(incompatible( + "the staged payload was captured at another source scope", + )); + } + let committed_step: u64 = text("committedStep")? + .parse() + .map_err(|_| incompatible("the agent payload's committedStep is not a U64"))?; + if committed_step != params.source_scope.step { + return Err(incompatible( + "the staged payload's committed step is not the source boundary", + )); + } + let profile = AssetRef::from_json( + session + .get("profile") + .ok_or_else(|| incompatible("the agent payload has no profile"))?, + ) + .map_err(|e| incompatible(format!("the agent payload's profile: {}", e.0)))?; + if profile != self.profile.asset { + return Err(incompatible(format!( + "the staged payload is profile {}; this worker serves {}", + profile.id, self.profile.asset.id + ))); + } + let seed = session + .get("seed") + .and_then(Value::as_i64) + .and_then(|v| i32::try_from(v).ok()) + .ok_or_else(|| incompatible("the agent payload has no seed"))?; + let reinforcements: u64 = text("reinforcements")? + .parse() + .map_err(|_| incompatible("the agent payload's reinforcements is not a U64"))?; + let accumulator_value = session + .get("accumulator") + .ok_or_else(|| incompatible("the agent payload has no accumulator"))?; + let rational = |key: &str| -> DomainResult { + RationalNs::from_json( + accumulator_value + .get(key) + .ok_or_else(|| incompatible(format!("the accumulator has no {key}")))?, + ) + .map_err(|e| incompatible(format!("the accumulator's {key}: {}", e.0))) + }; + let counter = |key: &str| -> DomainResult { + accumulator_value + .get(key) + .and_then(Value::as_str) + .ok_or_else(|| incompatible(format!("the accumulator has no {key}")))? + .parse::() + .map_err(|_| incompatible(format!("the accumulator's {key} is not a U64"))) + }; + let tick_duration = rational("tickDuration")?; + if tick_duration != gameboy::tick_duration() { + return Err(incompatible( + "the staged state was captured at another model tick", + )); + } + let accumulator = TickAccumulator::restored( + tick_duration, + rational("remainder")?, + counter("executedTicks")?, + counter("warmupOffset")?, + ) + .map_err(incompatible)?; + let context = self.read_context( + &TypedValue::from_json( + session + .get("context") + .ok_or_else(|| incompatible("the agent payload has no context"))?, + ) + .map_err(|e| incompatible(format!("the agent payload's context: {}", e.0)))?, + )?; + let state: AgentState = agent_from_chunks(&parts.manifest, &parts) + .map_err(|e| incompatible(format!("the agent state does not read: {e}")))?; + // The accumulator and the agent state describe one clock. + let legacy_remainder = + rational_remainder_to_legacy(&accumulator.remainder()).map_err(incompatible)?; + if state.remainder != legacy_remainder + || state.network.ms != accumulator.brain_ticks() as f64 + { + return Err(incompatible( + "the agent state's clock and the session accumulator disagree", + )); + } + if !state.warmed_up { + return Err(incompatible("the staged agent state was never warmed up")); + } + // A replacement fly: the dataset is loaded and checked here, not trusted. + let dataset = self.dataset()?; + let (mut agent, graph) = self.build_agent(dataset.clone(), seed)?; + let computed = + compatibility_digest(&self.config.agent_id, &self.profile.asset, &graph, seed); + if computed != params.compatibility_digest { + return Err(incompatible(format!( + "the staged state's compatibility {} is not the {computed} this worker is", + params.compatibility_digest + ))); + } + agent + .import_state(&state) + .map_err(|e| incompatible(format!("the agent state does not import: {e}")))?; + if let Some(staged) = &self.staged { + return Err(DomainError::before( + ErrorCode::Conflict, + format!( + "this worker already holds the staged restore {} for checkpoint {}", + staged.token, staged.checkpoint_id + ), + )); + } + let token = crate::agent::restore_token( + ¶ms.checkpoint_id, + &scope, + &actual, + &self.config.incarnation_id, + ); + if self.activated.contains(&token) { + return Err(DomainError::before( + ErrorCode::Conflict, + "this exact restore was already activated on this worker", + )); + } + self.staged = Some(StagedAgent { + token: token.clone(), + checkpoint_id: params.checkpoint_id.clone(), + scope: scope.clone(), + agent, + dataset, + graph, + accumulator, + context, + seed, + reinforcements, + committed_step, + }); + self.status.set_state(WorkerState::StagedRestore); + Ok(HandlerReply::from(&StageRestoreResult { + checkpoint_id: params.checkpoint_id, + restore_token: token, + })) + } + + async fn state_activate_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let params: ActivateRestoreParams = ctx.params()?; + if self.activated.contains(¶ms.restore_token) { + return Err(DomainError::before( + ErrorCode::Conflict, + "this restore token has already been activated", + )); + } + let Some(staged) = self.staged.take() else { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "this worker holds no staged restore", + )); + }; + if staged.token != params.restore_token { + let token = staged.token.clone(); + self.staged = Some(staged); + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + format!( + "this worker's staged restore is {token}, not {}", + params.restore_token + ), + )); + } + self.status.set_state(WorkerState::Restoring); + let StagedAgent { + token, + checkpoint_id, + scope, + agent, + dataset, + graph, + accumulator, + context, + seed, + reinforcements, + committed_step, + } = staged; + self.transition_start_ms = agent.network.ms; + self.agent = Some(agent); + self.dataset = Some(dataset); + self.graph = Some(graph); + self.accumulator = Some(accumulator); + self.context = Some(context); + self.seed = seed; + self.reinforcements = reinforcements; + // legacy-transient-reset: the readout transient starts as a fresh legacy process has + // it, while the decoder state (holds, winners, fatigue) was restored with the agent. + self.transient = ReadoutTransient::legacy_reset(); + self.epoch = Some(scope.epoch.clone()); + self.prepared = None; + self.phase = AgentPhase::Ready(committed_step); + self.activated.insert(token); + self.bump(); + self.status.set_state(WorkerState::Ready); + self.status.set_scope(Some(scope_at( + &scope.session_id, + &scope.epoch, + committed_step, + ))); + let result = ActivateRestoreResult { + committed_step, + checkpoint_id, + observation: None, + }; + result + .validate_for_role(Role::Agent) + .map_err(|e| DomainError::invalid(e.0))?; + Ok(HandlerReply::from(&result)) + } + + fn fail_on_applied( + &mut self, + outcome: DomainResult, + ) -> DomainResult { + if let Err(e) = &outcome + && e.mutation != MutationCertainty::None + { + self.phase = AgentPhase::Failed; + } + outcome + } +} + +impl WorkerEndpoint for LegacyAgentWorker { + fn worker_id(&self) -> Id { + self.config.agent_id.clone() + } + + fn incarnation_id(&self) -> Id { + self.config.incarnation_id.clone() + } + + fn session_id(&self) -> Id { + self.config.session_id.clone() + } + + fn role(&self) -> Role { + Role::Agent + } + + fn capabilities(&self) -> Vec { + vec![ + id("agent-step-v1"), + id("pixel-observation-v1"), + id(crate::state::CHECKPOINT_CAPABILITY), + id(ROLLBACK_CAPABILITY), + ] + } + + fn status_cell(&self) -> StatusCell { + self.status.clone() + } + + fn worker_threads(&self) -> u64 { + self.config.worker_threads as u64 + } + + fn methods(&self) -> Vec<&'static str> { + vec![ + "Agent.Initialize", + "Agent.Prepare", + "Agent.Commit", + METHOD_AGENT_ROLLBACK, + "State.Capture", + "State.StageRestore", + "State.ActivateRestore", + ] + } + + fn handle<'a>(&'a mut self, ctx: HandlerCtx<'a>) -> BoxFuture<'a, DomainResult> { + Box::pin(async move { + let outcome = match ctx.method { + "Agent.Initialize" => self.initialize(&ctx).await, + "Agent.Prepare" => self.prepare(&ctx).await, + "Agent.Commit" => self.commit(&ctx).await, + METHOD_AGENT_ROLLBACK => self.rollback(&ctx).await, + "State.Capture" => self.state_capture(&ctx).await, + "State.StageRestore" => self.state_stage_restore(&ctx).await, + "State.ActivateRestore" => self.state_activate_restore(&ctx).await, + other => Err(DomainError::before( + ErrorCode::Unsupported, + format!("{other} is not an agent method"), + )), + }; + self.fail_on_applied(outcome) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_legacy_remainder_converts_exactly_both_ways() { + let mut legacy = 0.0f64; + for _ in 0..100_000 { + legacy += flybrain_core::agent::GAMEBOY_MS_PER_FRAME; + legacy -= legacy.floor(); + let rational = legacy_remainder_to_rational(legacy).expect("exact"); + assert_eq!( + rational_remainder_to_legacy(&rational).expect("exact"), + legacy + ); + } + assert!( + legacy_remainder_to_rational(0.1).is_err(), + "0.1 ms is not k/32768" + ); + assert!( + legacy_remainder_to_rational(1.0).is_err(), + "a remainder is below one tick" + ); + } + + #[test] + fn the_spike_bitset_is_the_legacy_feed_layout() { + let last = [5.0, 9.0, 10.0, -1.0, 12.0, 0.0, 0.0, 0.0, 11.0]; + assert_eq!( + spike_bitset(&last, 10.0, 12.0), + vec![0b0001_0100, 0b0000_0001] + ); + assert_eq!( + spike_bitset(&last, 12.0, 12.0), + vec![0, 0], + "an empty window is empty" + ); + } + + #[test] + fn the_macro_in_a_decision_is_the_first_bound_channel_held() { + let active = vec![ + "up".to_owned(), + "macro_talk".to_owned(), + "macro_go_out".to_owned(), + ]; + let bound = vec!["macro_go_out".to_owned(), "macro_talk".to_owned()]; + let decision = channels_decision(&active, &bound); + assert_eq!(decision.macro_channel.as_deref(), Some("macro_go_out")); + assert_eq!(decision.mask(), 1); + assert_eq!(channels_decision(&active, &[]).macro_channel, None); + } + + #[test] + fn the_decoder_digest_reproduces_the_shared_vectors() { + let file = + fly_session_types::fixtures::load("gameboy-decoder-config.json").expect("vectors"); + for case in file["cases"].as_array().expect("cases") { + let channels: Vec<&str> = case["macroChannels"] + .as_array() + .expect("channels") + .iter() + .map(|c| c.as_str().expect("a channel")) + .collect(); + let config = gameboy_decoder_config_with_macros(&channels); + assert_eq!( + decoder_config_form(&config), + case["form"], + "{}", + case["name"] + ); + assert_eq!( + decoder_config_digest(&config), + case["digest"].as_str().expect("digest"), + "{}", + case["name"] + ); + } + } + + #[test] + fn the_production_profile_is_the_contract_constant_and_the_toy_one_is_not() { + let production = LegacyAgentProfile::production(); + assert_eq!(production.asset, gameboy::profile_asset_ref()); + let toy = LegacyAgentProfile::toy(); + assert_eq!(toy.asset.id, TOY_PROFILE_ID); + assert_ne!(toy.asset.digest, production.asset.digest); + assert_eq!( + digest_of(&toy.document).expect("digest"), + toy.asset.digest, + "the toy AssetRef is the digest of its own document" + ); + // Every pinned field other than the three it names is the legacy profile's. + for key in [ + "kernelVersion", + "plasticityVersion", + "tickDuration", + "warmupMs", + "view", + "supportedStimuli", + "readoutContextSchema", + "decisionSchema", + "legacyExceptions", + ] { + assert_eq!(toy.document[key], production.document[key], "{key}"); + } + } +} diff --git a/services/flysim/crates/fly-session/src/lib.rs b/services/flysim/crates/fly-session/src/lib.rs index 6849001..74a21c9 100644 --- a/services/flysim/crates/fly-session/src/lib.rs +++ b/services/flysim/crates/fly-session/src/lib.rs @@ -29,6 +29,7 @@ pub mod dedup; pub mod environment; pub mod harness; pub mod launcher; +pub mod legacy_agent; pub mod measure; pub mod media; pub mod metrics; diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index e361af3..4451900 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -606,6 +606,13 @@ async fn execute( fn classify_default(method: &str) -> Option { match method { "Agent.Prepare" | "Agent.Commit" | "Environment.Advance" => Some(OpClass::StepMutation), + // The extension methods of `workers-v1` section 7 are mutations under the step operation + // key (`legacy-gameboy-v1` section 11): `SaveSlot` at `(e, k)`, `RestoreSlot` and + // `Agent.Rollback` at the new epoch `(e', k)`. A lost reply replays from the same cache + // rather than rolling back twice. + "Agent.Rollback" | "Environment.SaveSlot" | "Environment.RestoreSlot" => { + Some(OpClass::StepMutation) + } // `ipc-v1` section 5 retains lifecycle *and capture* replies until // `Worker.Acknowledge`. The restore methods join them: their replies carry a // once-only token and, for an environment, the restored observation's artifact, and a From fbf7c1e486be18f0b05edeaf3489d172f92a33fc Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 23 Sep 2026 14:45:25 +0000 Subject: [PATCH 03/26] fly-session: the launcher starts a legacy agent in-process, on a thread or as a process --- services/flysim/crates/fly-session/src/cli.rs | 34 +++++- .../flysim/crates/fly-session/src/launcher.rs | 114 ++++++++++++++++++ 2 files changed, 147 insertions(+), 1 deletion(-) diff --git a/services/flysim/crates/fly-session/src/cli.rs b/services/flysim/crates/fly-session/src/cli.rs index dcb0df7..823f7d2 100644 --- a/services/flysim/crates/fly-session/src/cli.rs +++ b/services/flysim/crates/fly-session/src/cli.rs @@ -22,14 +22,16 @@ use std::process::ExitCode; use crate::agent::AgentFaults; use crate::environment::EnvironmentFaults; use crate::launcher::{ - AgentLaunch, EnvironmentLaunch, ExecutionMode, Started, flags, serve_one, + AgentLaunch, EnvironmentLaunch, ExecutionMode, LegacyAgentLaunch, Started, flags, serve_one, }; +use crate::legacy_agent::LegacyProfileKind; use crate::types::*; const USAGE: &str = "\ fly-session [options] agent serve one agent worker on a launcher-created endpoint + legacy-agent serve one legacy Game Boy agent worker (AGENT-01) on a launcher endpoint environment serve the environment worker on a launcher-created endpoint measure compare the execution modes and print the measurement table measure-row measure one row and print it as JSON (one child per row) @@ -47,6 +49,8 @@ Worker options (agent and environment): --warmup-ticks N [--prepare-delay-ms N] [--commit-delay-ms N] [--fail-commit-at-step N] [--fail-stage-restore 0|1] [--fail-activate-restore 0|1] + legacy-agent: --agent ID --port ID --dataset DIR --profile production|toy + --macro-channels c1,c2 (empty in raw mode) environment: --worker ID --ports p1,p2 --step-numerator N --step-denominator N [--advance-delay-ms N] [--omit-view-at-boundary N] [--fail-stage-restore 0|1] [--fail-activate-restore 0|1] @@ -75,6 +79,8 @@ pub fn main() -> ExitCode { let result = match command.as_str() { "agent" => Options::parse(&rest, &[flags::COMMON, flags::AGENT_ONLY]) .and_then(|o| serve(&command, &o)), + "legacy-agent" => Options::parse(&rest, &[flags::COMMON, flags::LEGACY_AGENT_ONLY]) + .and_then(|o| serve(&command, &o)), "environment" => Options::parse(&rest, &[flags::COMMON, flags::ENVIRONMENT_ONLY]) .and_then(|o| serve(&command, &o)), "measure" => Options::parse(&rest, &[flags::MEASURE]).and_then(|o| measure(&o)), @@ -220,6 +226,18 @@ fn serve(role: &str, options: &Options) -> Result<(), String> { client_id: client_id.clone(), service: service.clone(), }), + "legacy-agent" => Started::LegacyAgent(LegacyAgentLaunch { + session_id, + agent_id: options.id(flags::AGENT)?, + port_id: options.id(flags::PORT)?, + incarnation_id, + worker_threads: threads, + dataset_dir: options.path(flags::DATASET)?, + profile: LegacyProfileKind::parse(options.required(flags::PROFILE)?)?, + macro_channels: parse_channels(options.required(flags::MACRO_CHANNELS)?)?, + client_id: client_id.clone(), + service: service.clone(), + }), _ => Started::Environment(EnvironmentLaunch { session_id, worker_id: options.id(flags::WORKER)?, @@ -259,6 +277,20 @@ fn serve(role: &str, options: &Options) -> Result<(), String> { }) } +fn parse_channels(value: &str) -> Result, String> { + value + .split(',') + .filter(|part| !part.is_empty()) + .map(|part| { + if fly_session_types::gameboy::is_channel_name(part) { + Ok(part.to_owned()) + } else { + Err(format!("--macro-channels: {part:?} is not a channel name")) + } + }) + .collect() +} + fn parse_ports(value: &str) -> Result, String> { value .split(',') diff --git a/services/flysim/crates/fly-session/src/launcher.rs b/services/flysim/crates/fly-session/src/launcher.rs index 65827b6..b36119d 100644 --- a/services/flysim/crates/fly-session/src/launcher.rs +++ b/services/flysim/crates/fly-session/src/launcher.rs @@ -30,6 +30,7 @@ use flybus::{Client, ClientConfig, Router, ServiceConfig, Transport, UnixListene use crate::agent::{AgentConfig, AgentFaults, FakeAgentWorker}; use crate::environment::{CounterEnvironment, EnvironmentConfig, EnvironmentFaults}; +use crate::legacy_agent::{LegacyAgentConfig, LegacyAgentWorker, LegacyProfileKind}; use crate::rpc::WorkerRef; use crate::types::*; use crate::worker::{StatusCell, WorkerHandle, serve}; @@ -257,6 +258,26 @@ pub struct EnvironmentLaunch { pub service: String, } +/// What one legacy agent participant (AGENT-01) is started with. +/// +/// Everything crosses a process boundary as argv, like the synthetic agent's configuration: a +/// dataset directory, the profile it serves and the composition's macro channels. The seed, +/// the profile `AssetRef` and the first frame arrive in `Agent.Initialize`, not here. +#[derive(Clone, Debug)] +pub struct LegacyAgentLaunch { + pub session_id: Id, + pub agent_id: Id, + pub port_id: Id, + pub incarnation_id: Id, + pub worker_threads: usize, + pub dataset_dir: PathBuf, + pub profile: LegacyProfileKind, + /// `executor.macroChannels` in composition order; empty in raw mode. + pub macro_channels: Vec, + pub client_id: String, + pub service: String, +} + // ------------------------------------------------------------------------------------------- // A launched participant @@ -581,6 +602,38 @@ impl Launcher { } } + /// Starts one legacy agent (AGENT-01), in the launcher's configured mode, and identifies it. + pub async fn launch_legacy_agent( + &mut self, + spec: LegacyAgentLaunch, + ) -> Result { + let threads = self.budget.allocate(&spec.agent_id, spec.worker_threads)?; + let identity = WorkerIdentity { + session_id: spec.session_id.clone(), + client_id: spec.client_id.clone(), + service: spec.service.clone(), + worker_id: spec.agent_id.clone(), + incarnation_id: spec.incarnation_id.clone(), + role: Role::Agent, + port_id: Some(spec.port_id.clone()), + worker_threads: threads, + }; + let started = self + .start_participant(&identity, Started::LegacyAgent(spec.clone()), threads) + .await; + match started { + Ok(worker) => { + let identity = worker.identity.clone(); + self.workers.insert(spec.agent_id.clone(), worker); + Ok(identity) + } + Err(e) => { + self.budget.release(&spec.agent_id); + Err(e) + } + } + } + /// Starts the environment, in the launcher's configured mode, and identifies it. pub async fn launch_environment( &mut self, @@ -690,6 +743,12 @@ impl Launcher { let status = endpoint.status(); (serve(client, service, endpoint), status) } + Started::LegacyAgent(spec) => { + let endpoint = + LegacyAgentWorker::new(legacy_agent_config(spec, identity.worker_threads)); + let status = endpoint.status(); + (serve(client, service, endpoint), status) + } Started::Environment(spec) => { let endpoint = CounterEnvironment::new(environment_config(spec)); let status = endpoint.status(); @@ -1250,6 +1309,10 @@ pub(crate) mod flags { pub const OMIT_AUDIO_AT_BOUNDARY: &str = "omit-audio-at-boundary"; pub const OVERLAPPING_AUDIO_AT_BOUNDARY: &str = "overlapping-audio-at-boundary"; + pub const DATASET: &str = "dataset"; + pub const PROFILE: &str = "profile"; + pub const MACRO_CHANNELS: &str = "macro-channels"; + pub const MODE: &str = "mode"; pub const AGENTS: &str = "agents"; pub const STEPS: &str = "steps"; @@ -1281,6 +1344,8 @@ pub(crate) mod flags { FAIL_STAGE_RESTORE, FAIL_ACTIVATE_RESTORE, ]; + /// What only a legacy agent (AGENT-01) is given. + pub const LEGACY_AGENT_ONLY: &[&str] = &[AGENT, PORT, DATASET, PROFILE, MACRO_CHANNELS]; /// What only the environment is given, media options included. pub const ENVIRONMENT_ONLY: &[&str] = &[ WORKER, @@ -1313,6 +1378,7 @@ fn arg(name: &str, value: impl std::fmt::Display) -> (String, String) { #[derive(Clone, Debug)] pub(crate) enum Started { Agent(AgentLaunch), + LegacyAgent(LegacyAgentLaunch), Environment(EnvironmentLaunch), } @@ -1320,6 +1386,7 @@ impl Started { pub(crate) fn subcommand(&self) -> &'static str { match self { Started::Agent(_) => "agent", + Started::LegacyAgent(_) => "legacy-agent", Started::Environment(_) => "environment", } } @@ -1350,6 +1417,17 @@ impl Started { } args } + Started::LegacyAgent(spec) => vec![ + arg(flags::SESSION, &spec.session_id), + arg(flags::AGENT, &spec.agent_id), + arg(flags::PORT, &spec.port_id), + arg(flags::INCARNATION, &spec.incarnation_id), + arg(flags::DATASET, spec.dataset_dir.display()), + arg(flags::PROFILE, spec.profile.label()), + // An empty list is raw mode; the flag is always written so the parser never + // has to guess which one a missing flag meant. + arg(flags::MACRO_CHANNELS, spec.macro_channels.join(",")), + ], Started::Environment(spec) => { let mut args = vec![ arg(flags::SESSION, &spec.session_id), @@ -1405,6 +1483,18 @@ pub(crate) fn agent_config(spec: &AgentLaunch, worker_threads: usize) -> AgentCo } } +pub(crate) fn legacy_agent_config(spec: &LegacyAgentLaunch, worker_threads: usize) -> LegacyAgentConfig { + LegacyAgentConfig { + session_id: spec.session_id.clone(), + agent_id: spec.agent_id.clone(), + incarnation_id: spec.incarnation_id.clone(), + worker_threads, + dataset_dir: spec.dataset_dir.clone(), + profile: spec.profile, + macro_channels: spec.macro_channels.clone(), + } +} + pub(crate) fn environment_config(spec: &EnvironmentLaunch) -> EnvironmentConfig { EnvironmentConfig { session_id: spec.session_id.clone(), @@ -1441,6 +1531,11 @@ pub(crate) async fn serve_one( service, FakeAgentWorker::new(agent_config(spec, worker_threads)), ), + Started::LegacyAgent(spec) => serve( + client, + service, + LegacyAgentWorker::new(legacy_agent_config(spec, worker_threads)), + ), Started::Environment(spec) => { serve(client, service, CounterEnvironment::new(environment_config(spec))) } @@ -1528,6 +1623,21 @@ mod flag_tests { } } + fn legacy_agent_launch() -> LegacyAgentLaunch { + LegacyAgentLaunch { + session_id: id("demo"), + agent_id: id("fly-a"), + port_id: id("p1"), + incarnation_id: id("fly-a-inc-1"), + worker_threads: 1, + dataset_dir: PathBuf::from("/nonexistent/legacy-toy"), + profile: LegacyProfileKind::Toy, + macro_channels: vec!["macro_talk".to_owned()], + client_id: "worker-fly-a".to_owned(), + service: "agent.fly-a".to_owned(), + } + } + /// Both halves of the command line name the same constants, and this proves it for every /// argument a launch can produce: a flag the launcher writes that the parser does not /// accept would be a silently ignored option, which is what the parser now refuses. @@ -1539,6 +1649,10 @@ mod flag_tests { [flags::COMMON, flags::ENVIRONMENT_ONLY], ), (Started::Agent(agent_launch()), [flags::COMMON, flags::AGENT_ONLY]), + ( + Started::LegacyAgent(legacy_agent_launch()), + [flags::COMMON, flags::LEGACY_AGENT_ONLY], + ), ] { let arguments = started.arguments(); assert!(!arguments.is_empty()); From 214755f2b9401f29acbde33302dd6d027ec71219 Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 23 Sep 2026 14:45:25 +0000 Subject: [PATCH 04/26] fly-session: the AGENT-01 parity harness, a direct NeuralAgent reference and a toy connectome --- .../fixtures/legacy-toy/circuit-roles.json | 1 + .../fixtures/legacy-toy/indptr.binz | Bin 0 -> 5484 bytes .../fly-session/fixtures/legacy-toy/meta.json | 1 + .../fixtures/legacy-toy/targets.binz | Bin 0 -> 83424 bytes .../legacy-toy/visual-hemisphere.binz | Bin 0 -> 37 bytes .../fixtures/legacy-toy/visual-indices.binz | Bin 0 -> 1158 bytes .../fixtures/legacy-toy/visual-xy.binz | Bin 0 -> 1652 bytes .../fixtures/legacy-toy/weights.binz | Bin 0 -> 41843 bytes .../crates/fly-session/src/legacy_parity.rs | 1510 +++++++++++++++++ services/flysim/crates/fly-session/src/lib.rs | 1 + 10 files changed, 1513 insertions(+) create mode 100644 services/flysim/crates/fly-session/fixtures/legacy-toy/circuit-roles.json create mode 100644 services/flysim/crates/fly-session/fixtures/legacy-toy/indptr.binz create mode 100644 services/flysim/crates/fly-session/fixtures/legacy-toy/meta.json create mode 100644 services/flysim/crates/fly-session/fixtures/legacy-toy/targets.binz create mode 100644 services/flysim/crates/fly-session/fixtures/legacy-toy/visual-hemisphere.binz create mode 100644 services/flysim/crates/fly-session/fixtures/legacy-toy/visual-indices.binz create mode 100644 services/flysim/crates/fly-session/fixtures/legacy-toy/visual-xy.binz create mode 100644 services/flysim/crates/fly-session/fixtures/legacy-toy/weights.binz create mode 100644 services/flysim/crates/fly-session/src/legacy_parity.rs diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/circuit-roles.json b/services/flysim/crates/fly-session/fixtures/legacy-toy/circuit-roles.json new file mode 100644 index 0000000..8bac168 --- /dev/null +++ b/services/flysim/crates/fly-session/fixtures/legacy-toy/circuit-roles.json @@ -0,0 +1 @@ +{"neurons":4096,"roles":{"kenyon":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,893,894,895,896,897,898,899,900,901,902,903,904,905,906,907,908,909,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999,1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023],"mbon":[1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131,1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147,1148,1149,1150,1151,1152,1153,1154,1155,1156,1157,1158,1159,1160,1161,1162,1163,1164,1165,1166,1167,1168,1169,1170,1171,1172,1173,1174,1175,1176,1177,1178,1179,1180,1181,1182,1183,1184,1185,1186,1187,1188,1189,1190,1191,1192,1193,1194,1195,1196,1197,1198,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229,1230,1231,1232,1233,1234,1235,1236,1237,1238,1239,1240,1241,1242,1243,1244,1245,1246,1247,1248,1249,1250,1251,1252,1253,1254,1255,1256,1257,1258,1259,1260,1261,1262,1263,1264,1265,1266,1267,1268,1269,1270,1271,1272,1273,1274,1275,1276,1277,1278,1279],"macro_go_out":[1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115],"macro_talk":[1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131],"macro_menu":[1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147],"macro_next":[1148,1149,1150,1151,1152,1153,1154,1155,1156,1157,1158,1159,1160,1161,1162,1163]}} diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/indptr.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/indptr.binz new file mode 100644 index 0000000000000000000000000000000000000000..41935a31c6513dfa1fed037ea1c3ff9a119fa17f GIT binary patch literal 5484 zcmai%c{tSj9>*iapk%0!!dM2`$(D?582eh$Q5wdeoU*i_%#1Z-i?NO{)~MnjWJJt zjtp6yJtwTwp(j*Z_r?_K9oDHU!?*hzjV6OBltA0cKjO8kDJwo^yyTaUB76B3ojh#x zv4H=|7Dho!cFHD6A)TbtRhblaEwCc(#z6`H%rm8Di=SjwPIUvB{xvKA? zu!&YfU2K}$#xtXHmQzyr&74f8PyufWjdpBMg|@D z{}9%GC!A9I>@81~cWA#5i;tVZ0p@7~&6DCuZKca)>eZ=~WUGD(D$O!YWM0ix9G#fX z(0vj)m7{6FdBU+m+vrHnx>*^W(HpWh*q^HN#^iKxU8nZ(53B8GV{q_5A0rR6eA4H~ zq<~^_gj<)wLtoYEO8T8B2~uj%F;D-LXs3qR^Z-+V?R(o|PQvtxOh=wd4_9ZQqIK;) zzUOMs-W`5W82WbqulGgKY+Po0ro+KTaaX59Y4w9|_mw+n_X|Gy9NKr_rO7v^smU>x zR++7Aj@qh9DZ{v6sU%OXgGtOh^TKE<`}Ehy>8z=cUAks+`kR5j=Q6eA_ zKRP~7bAQsXkl-9kb)aIB6zR9Zlq*uNNd;D>P^|Mw>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J=ws^K2`OBj&czx_ zzDH2A4Eyw^r_*7(oU1R#I5V44wQ(r34mhu5o znpu3Syi~f4|5CY-vKfYTHq*S^Ub*40ZFeG%6de&Qf_>TyNcSy|$aADi8rMw+wB|Tj z7I=NXr<^1@OI~6*CI^j@yW+gHTfMClj(U?`Jnh>z^BwYm@+;br>9qLKd1{s%#qWX} z_{u0al5W2v=i(RB)pceo=L`(p{-|$CzPO*CR+Gm|CY4V5X?0_nIcV=L>_zV@`wfo6 zpG21+hmGHicAa(&)};&k+)i}+`!+K3!dOQAbctM1Igm@v|Fg#qqB(W8*vn-B*$v?Z zKDWh3$r;{@d?%Dx$Kk8 z>QmaVa=h^h=6mxX?;tN9zI};F=65^%#f|*gun|2^v@$zZ{tMj*+(*9$jjeOBGf1xR zXDT;bPYBN(yaq4KqlHU?G0~f*9WHYmO0C1O#HSRJ)?bM znd+SOeY>-D-RqRoi+OnEw7~;qi91)!IC{iagOksK=j)%L^Z!gE^C-NCH|F-@J7_KR zq02`$*TDzrv>qLWhtJp6XlwL1iw$iewqXeBNFA)K=|e_AU5M z=l^~Gn8n9M`>UTo{;d9FXRNac|4A3&ccgWHfAMR_bi!lu4Z=x3UY&QkgqAG4kVX$S zB?o-bZnOtHn%BT`9B;zKlguczrnu2H6KG2CS+8)RIsL$q<@)5x*ywmtdxloJycf%PPIX`(( z&1Ljo^gBAv=%akUW((Ms&rOb+?p7S+<-O!v>3riUJ!qJ@YS>8^r{|+tIXilb-Nh@6 zvJ>FT?36qr`;XEoxpQIfupt~ZefviWKQnLXRMed(qgRK~jkEah?b*7oou~gFpk4K= H0DuAj_U3kh literal 0 HcmV?d00001 diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-hemisphere.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-hemisphere.binz new file mode 100644 index 0000000000000000000000000000000000000000..4203e09853f0ebde169ddd72f4bd9cdf4ddf0eeb GIT binary patch literal 37 pcmb2|=3oE;rvGmbGV%f$O$Kk`Z?Tvpq^k(BXDoX5SAm&<0RXpD3X%W- literal 0 HcmV?d00001 diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-indices.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-indices.binz new file mode 100644 index 0000000000000000000000000000000000000000..1c50f0eab154e49d1a3967d1801a2bc0250a4701 GIT binary patch literal 1158 zcmb2|=3oE;rvJQ`otqRmm>4$P%DlZT7a3I-pAep8pW)!Z$Q9IaNMxbLQ4K#%ub{3= zQx@tx)$nK43hF!+vQX>l3P0Ygpzd2&7V3Rn;m<5}spFW*Ld~-oe%w))x~^?msQWg< zpWW(G=ed%F+IL_0@mF2yzV~IJ{@)kp8Q6?E4)P>w9F{o8;bzozu_saIvBY^6HKWdx zK8aeFXPo0nGwQy1CQvo_Bx;_HIL8&Xsq5;RMBUdB=h@6Qb)L;h)V_V= z9ADX{?z?Xi^?%pRZz<`s3{ zzVlG;`;PO>a-TYm+dR}fUvZ8*?o-$GJr8x?SDa_J`_y^9=ArieALsb%K6T&!^HBdk z2Zxxz2m61@0*#zb0ZoE)1X@%?7IHdA91@(z;i4imvC}DJk>Fg3BPwDWJDp=53C?Fx zQ4#F)bPAd@agN9m715QR&QX^p&f`f@5uSO{DQwfkxiU{w#CM)_j{7umK9k52fmThY zz^=eKLQ|HAEY)<5JQX;PD`bh#)Rj)5s{-drU0EWwb)|FctHAkeCQAf+Go6BGU7RDf zWr^t8Oy}rZ7w7SnED@gj(kXn`#kq1{mWc0t=^X#-;(SJ)6oF>RLji4ua|C-*L>5aP zjyPsGkJBebX!6WMA!iwYa8eB z=A;PEzIiBY+s3)FZ&Ji}-#i@mZR31qnI{76mWKlS3g-yVc_Omh@^Iw2!g<^=PlTrL zJQTXFaIW;7Ct}-o9*%uiIG^3-iC}-_q2PHR=ZNolBD%ivaP+;8^Z09?2+#j{D16_? nx$=LWi0}V-IR2lYz@7Th0H$dG9~$@o{#gIoMoFN7hk*eA&Grx^ literal 0 HcmV?d00001 diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-xy.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-xy.binz new file mode 100644 index 0000000000000000000000000000000000000000..feb31e69945887d4401f7315861f4f24d5815dbc GIT binary patch literal 1652 zcmb`Ge@GKy7{^yq1|y}Q%)||>tgspcv8dL8p%NkXM>4|n3@j_OvvMiTyHO$(Vk0Dz zB!~SV%4pz^&0OvrSY{$i1=rlxnWkIbc5}_$ZF}!-tv`Ywf^d5tc)ri)`-SJP_Z2s; z6a1>xk$g+XrR~LAhreDSr}otC+kY~nt9Vx{GMh1)lUrD3XiW%}=Co|uu={paYOP|N z9?Tx{Ig_p?qN@_SUc4-CsocW9J#}m{8Oj_{i*eYg0iuYVDKpb*7>L}ZYT9bF)+oEg zy6FO?4yF;QjSVnq8q!z=_iOEmOfPtkk|KKzrDW=X3#*1az^|d4XvB|rl|DAGpsI#u zos^zh)Keqvp6E0s(HAtHHdMb8obBX#%E37~?sc#_vjXmuIOJ44m`3M}ie&0AGXP9z zHPo-6qp`QwyP!9E-}&Wci=2u3#n}hJ9oQW>Mp+VKCP{D&K9j=Uf>#3b@=zgmAC6Jx zEWra<6C9fm5az+i*BIIEwnpdQkKuX%d>KQ)8KwbDpz}xjv<@j%#LO745eBh6k9h(v z64AH>T*gRHazquV1EEpvoW(~573?7_9lr|?$AD(7)8Z#X0rmza!`tDNBOl>g4uVHP zS47t=vq7!tZm%j2R1j{1%$i)}c`ma_4B_?cS}Xy-Nem)0(xtTEztGDNrQ7g(#0TV? z^ha8#$w>a**j((-;QvtKJHc+mhhmc+zy-7p#D?IN1#|_@>13ZxB2PEk?WN10ie63B zbL)xzPJ(|!37Kc$BU%L;5PS5aqE2HC)TgHMm`P(a9-xak9WzkNFNVSom!;p43F0Y! zT-D5Ha{1x5co+dGiA)i%@YAYp{yaApZi|B<0>Mw6cOJO_ literal 0 HcmV?d00001 diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/weights.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/weights.binz new file mode 100644 index 0000000000000000000000000000000000000000..c148f835e68d2f1997aa83f4837835c4e5968eae GIT binary patch literal 41843 zcmV()K;OR~iwFP!00002|3#gJb{t8wgok^2n3?(gpGIU!mShrx1(q$<&G@SJzsG02 zwmi^XU6l|S8CghF68Xe5(N3%ry+kAN#a+0G{bZ6TCNA7M5hre4lvvuU8i{mbWPfVf zYio&YqMMl8YjXVQpQ|UnxntL`f2rChbrLCiZO%S-V*i@5pH%GUZ*FCu^5X8@!2Tsp z4DI)UeQGZDQZuxsCmMIvR}HM zRpQ95cxK<$uunX7kFJzR+PiXzy8S(4S6Q=ne7KxlWo)03=U=M!O>eGZe|~k_#F$S? z*{jQTy?y(>G=FO)PF%s>zq6m_?OiQ{n8`?Fu>|4h6j=J5)%&O>%Q34Ol>{V_8r^AUpKdRcX$?E`)S2Kt!u9yCH}ac zy{=~e_QhrGUSFM7Cdu{A?eA&(b!VT|v~TIyJD2wVd%L$LJ0oYm5ABs%`*YF0f0KBy zJJDJe6VJ9zx`U?Oy;fek>A~sqX6!TVy_&tUZFjNbp3C+rTf3Kx{aZfq=|1dQ&fV1h zoUu=;*_s@}L%UY3$kcw{CidK?>)I7mZ7s6w^P=sAnZ5SW zc1_FPTekOJI6dW4`@Eg~YTIk8wz@s`QEb=KU=I%M9#*yn7k1Yb`*iK(zTMN<{=BmH zFYUDh?qgw}cw?)#uzyYQs+#?K)n0XI*R4I$v3LJ;S9V<$d)1{I*|*I(YnjAXTQA*H zhWpvrGnm^af3M2ZlQaigkope1pUE8fanXUbOX74$*SDv~z*W@I|*p8ijL&olLW$#kWt>(x+y=0#`uDcUaEvik=1?pJqfmZNK*HBD$A_3bL!_O6}1u48}h z+BNj-8MhP8cKn__H|@WjeV)E|YJa{p`=qBD*$(R1pO*Gcovg3+TJ4vLz5lDN>6z2h zpV?0aVO3?h*7k1^`#!S2{jnXj;gpo^b!of47h9)q_DL;!&(40PRk^oSn`2jW_H^Z4 zyX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vUt@Zt)C4BG#WHkcon1L&#=**d*W7I)`eokZ_6MwY%^d#)E zCjAFW~=Y%*_F5OHr3zI(;j4p!i|86w1Yrk6P4YIWre!OS$3 zXa}d~AAa|SIS?sy*9&ym``)^Ub;)5fez_?efO` DirectReference (NeuralAgent in Sim::step_frame order) ──> Vec +//! ──> AgentDriver (Agent.* RPCs to a launched worker) ──> Vec +//! └─ compare() ─┘ +//! ``` +//! +//! A [`ParityRecord`] carries only what both sides can observe of the agent: the ticks, the +//! brain clock and its exact remainder, the decision, the whole telemetry, the digest of the +//! transition's spike bitset and, at declared checkpoints, the digest of the full agent state +//! (`agent_to_chunks`). A state digest is exact equality of every membrane, trace, gain, rate, +//! RNG and decoder field. +//! +//! [`ReferenceSource`] is the seam for FND-01: a reader of `LegacyFrame`'s `FLY_TRACE` is a +//! second reference beside [`DirectReference`], producing the same records from the running +//! loop instead of from a transcription of it. Nothing here depends on it. +//! +//! [`toy`] is the committed toy connectome the goldens run on; the real dataset is optional. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use fly_session_types::extensions::{ + AgentRollbackParams, AgentRollbackResult, METHOD_AGENT_ROLLBACK, ROLLBACK_POLICY, +}; +use fly_session_types::gameboy::{self, ChannelsDecision, Location, ReadoutContext}; +use flybrain_core::agent::{AgentConfig as CoreAgentConfig, NeuralAgent}; +use flybrain_core::dataset::BrainDataset; +use flybrain_core::decoder::gameboy::{gameboy_decoder_config_with_macros, to_button_mask}; +use flybrain_core::envelope::{agent_from_chunks, agent_to_chunks, decode_envelope}; +use flybrain_core::rng::Xorshift32; +use flybus::{Client, Grants, Pattern, Policy, Router, RouterConfig}; +use serde_json::{Value, json}; + +use crate::launcher::{ + ExecutionMode, Launcher, LegacyAgentLaunch, SUPERVISOR_CLIENT, ThreadBudget, Via, +}; +use crate::legacy_agent::{ + LegacyAgentProfile, LegacyProfileKind, PAYLOAD_MAGIC, SPIKES_ATTACHMENT, channels_decision, + legacy_remainder_to_rational, spike_bitset, telemetry_of, +}; +use crate::rpc::{Serials, WorkerRef, call}; +use crate::types::*; + +/// The frame size: 160 x 144 RGBA8. +pub const FRAME_BYTES: usize = (gameboy::VIEW_WIDTH * gameboy::VIEW_HEIGHT * 4) as usize; +/// The legacy default seed. The profile's kernel version pins it (`lif-1ms-f64-v2` hashes the +/// seed into any other value), so it is the only seed this profile accepts. +pub const LEGACY_SEED: i32 = 22_222; + +// ------------------------------------------------------------------------------------------- +// The toy connectome + +pub mod toy { + //! The committed toy connectome, `fixtures/legacy-toy`: 4,096 neurons, sized as the + //! oracle's synthetic connectome is (`packages/brain/tools/golden.ts`) so that 300 noise + //! kicks leave the network sub-threshold and the connectome drives it, with the roles the + //! legacy readout and plasticity read -- `command_0..7`, `kenyon`, `mbon`, `reward_pam` -- + //! and four `macro_*` populations merged after the fingerprint, as FAFB's are. + + use std::io::Write as _; + use std::path::{Path, PathBuf}; + + use flate2::Compression; + use flate2::write::GzEncoder; + use flybrain_core::rng::Xorshift32; + use serde_json::{Map, Value, json}; + + /// The macro channels of the toy composition, in composition order. + pub const MACRO_CHANNELS: [&str; 4] = + ["macro_go_out", "macro_talk", "macro_menu", "macro_next"]; + pub const NEURONS: u32 = 4_096; + const EDGES_PER_NEURON: u32 = 10; + const SEED: i32 = 20_260_923; + + /// `services/flysim/crates/fly-session/fixtures/legacy-toy`. + pub fn dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/legacy-toy") + } + + fn range(from: u32, to: u32) -> Vec { + (from..to).collect() + } + + fn gz(bytes: &[u8]) -> Vec { + // flate2's default header has no name and a zero mtime, so the bytes are reproducible. + let mut encoder = GzEncoder::new(Vec::new(), Compression::best()); + encoder.write_all(bytes).expect("in memory"); + encoder.finish().expect("in memory") + } + + /// Every file of the toy dataset, by name, as it is committed. + pub fn files() -> Vec<(String, Vec)> { + let mut random = Xorshift32::new(SEED); + let kenyon = (0u32, 1_024u32); + let mbon = (1_024u32, 1_280u32); + let visual = range(1_600, 2_400); + + let mut roles = Map::new(); + for command in 0..8u32 { + roles.insert( + format!("command_{command}"), + json!(range(1_344 + command * 32, 1_376 + command * 32)), + ); + } + roles.insert("reward_pam".to_owned(), json!(range(1_280, 1_344))); + roles.insert("steer_left".to_owned(), json!(range(2_400, 2_432))); + roles.insert("steer_right".to_owned(), json!(range(2_432, 2_464))); + roles.insert("visual_l1".to_owned(), json!(visual)); + + let mut indptr = Vec::with_capacity(NEURONS as usize + 1); + let mut targets: Vec = Vec::new(); + let mut weights: Vec = Vec::new(); + for source in 0..NEURONS { + indptr.push(targets.len() as u32); + let is_kenyon = source >= kenyon.0 && source < kenyon.1; + for edge in 0..EDGES_PER_NEURON { + let forced = is_kenyon && edge < 4; + let target = if forced { + mbon.0 + (random.next_f64() * f64::from(mbon.1 - mbon.0)).floor() as u32 + } else { + (random.next_f64() * f64::from(NEURONS)).floor() as u32 + }; + let magnitude = 1 + (random.next_f64() * 40.0).floor() as i16; + targets.push(target); + weights.push(if !forced && random.next_f64() < 0.2 { + -magnitude + } else { + magnitude + }); + } + } + indptr.push(targets.len() as u32); + + let mut visual_xy = Vec::with_capacity(visual.len() * 2); + for column in 0..visual.len() { + visual_xy.push((column % 40) as f32 * 7.5); + visual_xy.push((column / 40) as f32 * 5.25); + } + let hemisphere: Vec = (0..visual.len()).map(|c| (c % 2) as u8).collect(); + + let meta = json!({ + "schemaVersion": 1, + "dataset": "legacy-toy", + "neurons": NEURONS, + "edges": targets.len(), + "roles": Value::Object(roles), + "visual": {"population": "toy-retina", "count": visual.len()}, + }); + let circuits = json!({ + "neurons": NEURONS, + "roles": { + "kenyon": range(kenyon.0, kenyon.1), + "mbon": range(mbon.0, mbon.1), + // Relabelled MBONs, outside the fingerprint, as the FAFB macro populations are. + "macro_go_out": range(1_100, 1_116), + "macro_talk": range(1_116, 1_132), + "macro_menu": range(1_132, 1_148), + "macro_next": range(1_148, 1_164), + }, + }); + let le32 = |values: &[u32]| { + values + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>() + }; + let text = |value: &Value| { + let mut s = serde_json::to_string(value).expect("json"); + s.push('\n'); + s.into_bytes() + }; + vec![ + ("meta.json".to_owned(), text(&meta)), + ("circuit-roles.json".to_owned(), text(&circuits)), + ("indptr.binz".to_owned(), gz(&le32(&indptr))), + ("targets.binz".to_owned(), gz(&le32(&targets))), + ( + "weights.binz".to_owned(), + gz(&weights + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>()), + ), + ("visual-indices.binz".to_owned(), gz(&le32(&visual))), + ("visual-hemisphere.binz".to_owned(), gz(&hemisphere)), + ( + "visual-xy.binz".to_owned(), + gz(&visual_xy + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>()), + ), + ] + } + + /// Writes the dataset into `dir`. + pub fn write(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + for (name, bytes) in files() { + std::fs::write(dir.join(name), bytes)?; + } + Ok(()) + } +} + +/// `/data/fafb-v783`, or `None` where the dataset is not checked out. +pub fn fafb_dir() -> Option { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../../data/fafb-v783"); + dir.join("meta.json").is_file().then_some(dir) +} + +// ------------------------------------------------------------------------------------------- +// Recorded inputs + +/// One reward event of the legacy adapter: a value for `reinforce` and a pulse for +/// `stimulate`. The task turns it into one `Reward` and one `reward-pulse` `Stimulus`. +#[derive(Clone, Debug, PartialEq)] +pub struct RewardEvent { + pub value: f64, + pub stimulation_ms: f64, +} + +/// One step of a recorded run. +#[derive(Clone, Debug, PartialEq)] +pub enum ScriptStep { + /// One transition: sugar admitted before it, the frame the environment produced, the + /// adapter's reward events, and the next decision context. + Frame { + sugar: Vec, + frame: usize, + rewards: Vec, + next_context: ReadoutContext, + }, + /// `legacy-ratchet-rollback-v1` at the boundary just reached: the slot's archived frame and + /// the context the executor's observation of the restored world produced. + Rollback { + frame: usize, + context: ReadoutContext, + }, + /// A group restore at the boundary just reached into a fresh agent + /// (`legacy-transient-reset`): a FLYSIM01-style load into a new process. + Restore, +} + +/// A recorded run: the macro channels, the frame pool, the first frame and context, and the +/// steps. The frames are the environment's output, so they are inputs here. +#[derive(Clone, Debug)] +pub struct LegacyScript { + pub name: String, + pub macro_channels: Vec, + pub frames: Arc>>, + pub initial_frame: usize, + pub initial_context: ReadoutContext, + pub steps: Vec, + /// Step indices after which the full agent state is compared. + pub checkpoints: BTreeSet, +} + +/// A deterministic pool of frames with distinct overall brightness, so the retina drive differs +/// from frame to frame and the connectome has something to respond to. +pub fn frame_pool(count: usize, seed: i32) -> Vec> { + let mut random = Xorshift32::new(seed); + (0..count) + .map(|index| { + let scale = (index + 1) as f64 / count as f64; + (0..FRAME_BYTES) + .map(|byte| { + if byte % 4 == 3 { + 255 + } else { + (random.next_f64() * 256.0 * scale).floor() as u8 + } + }) + .collect() + }) + .collect() +} + +fn context(boot: bool, bound: &[&str], location: Option<(u32, u32, u32)>) -> ReadoutContext { + ReadoutContext { + boot, + bound: bound.iter().map(|b| (*b).to_owned()).collect(), + location: location.map(|(area, x, y)| Location { area, x, y }), + } +} + +/// The macros-mode toy scenario: boot and play, a still location long enough for the blocked +/// rule, a battle (no location), sugar overlapping a pulse, reward events on a schedule with a +/// zero-value one, a rollback, a restore into a fresh worker and play after both. +pub fn toy_macros_script(frames: usize) -> LegacyScript { + let channels: Vec = toy::MACRO_CHANNELS + .iter() + .map(|c| (*c).to_owned()) + .collect(); + let bound_at = |k: usize| -> Vec<&'static str> { + match k { + 0..60 => vec![], + 60..130 => vec!["macro_go_out", "macro_talk"], + 130..200 => vec!["macro_talk", "macro_menu", "macro_next"], + _ => vec!["macro_go_out", "macro_menu"], + } + }; + let location_at = |k: usize| -> Option<(u32, u32, u32)> { + match k { + 0..20 => None, + 20..90 => Some((1, 5, 5)), + 90..96 => None, + _ => Some((1, 5 + (k / 30) as u32, 5)), + } + }; + let mut steps = Vec::new(); + for k in 1..=frames { + let sugar = match k { + 25 => vec![300.0], + 26 => vec![100.0], + 170 => vec![500.0, 40.0], + _ => vec![], + }; + let mut rewards = Vec::new(); + if k % 17 == 0 { + rewards.push(RewardEvent { + value: 0.4, + stimulation_ms: 120.0, + }); + } + if k == 50 { + rewards.push(RewardEvent { + value: 0.25, + stimulation_ms: 80.0, + }); + rewards.push(RewardEvent { + value: 0.5, + stimulation_ms: 200.0, + }); + } + if k == 77 { + rewards.push(RewardEvent { + value: 0.0, + stimulation_ms: 60.0, + }); + } + steps.push(ScriptStep::Frame { + sugar, + frame: (k * 3) % 8, + rewards, + next_context: context(k < 40, &bound_at(k), location_at(k)), + }); + if k == 120 { + steps.push(ScriptStep::Rollback { + frame: 5, + context: context(false, &bound_at(k), Some((2, 3, 4))), + }); + } + if k == 190 { + steps.push(ScriptStep::Restore); + } + } + let checkpoints: BTreeSet = steps + .iter() + .enumerate() + .filter(|(i, _)| i % 40 == 39) + .map(|(i, _)| i) + .chain([steps.len() - 1]) + .collect(); + LegacyScript { + name: "toy-macros".to_owned(), + macro_channels: channels, + frames: Arc::new(frame_pool(8, 4_242)), + initial_frame: 0, + initial_context: context(true, &[], None), + steps, + checkpoints, + } +} + +/// The raw-mode toy scenario: no macro group, a still location, rewards, a rollback. +pub fn toy_raw_script(frames: usize) -> LegacyScript { + let mut steps = Vec::new(); + for k in 1..=frames { + steps.push(ScriptStep::Frame { + sugar: if k == 10 { vec![250.0] } else { vec![] }, + frame: (k * 5) % 8, + rewards: if k % 13 == 0 { + vec![RewardEvent { + value: 0.3, + stimulation_ms: 120.0, + }] + } else { + vec![] + }, + next_context: context(k < 30, &[], if k > 5 { Some((7, 1, 1)) } else { None }), + }); + if k == 60 { + steps.push(ScriptStep::Rollback { + frame: 2, + context: context(false, &[], None), + }); + } + } + let last = steps.len() - 1; + LegacyScript { + name: "toy-raw".to_owned(), + macro_channels: Vec::new(), + frames: Arc::new(frame_pool(8, 99)), + initial_frame: 1, + initial_context: context(true, &[], None), + steps, + checkpoints: [29, last].into_iter().collect(), + } +} + +// ------------------------------------------------------------------------------------------- +// Records + +/// What both sides can observe of one step. +#[derive(Clone, Debug, PartialEq)] +pub struct ParityRecord { + /// 0 is Initialize; step `i` of the script is record `i + 1`. + pub index: usize, + pub kind: &'static str, + /// The committed boundary after the step. + pub boundary: u64, + pub ticks: u64, + pub brain_ticks: u64, + pub remainder: RationalNs, + pub decision: Option, + pub telemetry: Option, + /// SHA-256 of the transition's spike bitset. + pub spikes: Option, + /// SHA-256 of the full agent state, at a checkpoint. + pub state: Option, +} + +impl ParityRecord { + pub fn to_json(&self) -> Value { + json!({ + "index": self.index, + "kind": self.kind, + "boundary": self.boundary.to_string(), + "ticks": self.ticks.to_string(), + "brainTicks": self.brain_ticks.to_string(), + "remainder": self.remainder.to_json(), + "decision": self.decision.as_ref().map_or(Value::Null, DomainType::to_json), + "telemetry": self.telemetry.as_ref().map_or(Value::Null, |t| t.to_json()), + "spikes": self.spikes, + "state": self.state, + }) + } + + pub fn digest(&self) -> Digest { + digest_of(&self.to_json()).expect("a record canonicalizes") + } + + /// One readable line for a golden file: the fields a reviewer reads, then the digest of + /// the whole record. + pub fn row(&self) -> String { + let (mask, macro_channel) = match &self.decision { + Some(d) => ( + format!("{:02x}", d.mask()), + d.macro_channel.clone().unwrap_or_else(|| "-".to_owned()), + ), + None => ("--".to_owned(), "-".to_owned()), + }; + let pulse = self + .telemetry + .as_ref() + .and_then(|t| t.stimulus_remaining_ms) + .map_or("-".to_owned(), |ms| format!("{ms}")); + format!( + "{} {} b{} t{} bt{} m{} {} p{} {}{}", + self.index, + self.kind, + self.boundary, + self.ticks, + self.brain_ticks, + mask, + macro_channel, + pulse, + &self.digest()[..16], + if self.state.is_some() { " state" } else { "" } + ) + } +} + +/// The digest of a full agent state: every chunk and the manifest `agent_to_chunks` writes. +pub fn state_digest(state: &flybrain_core::agent::AgentState) -> Digest { + let chunks = agent_to_chunks(state); + let mut bytes = chunks.manifest.stringify().into_bytes(); + for (name, chunk) in &chunks.chunks { + bytes.extend_from_slice(name.as_bytes()); + bytes.extend_from_slice(&(chunk.len() as u64).to_le_bytes()); + bytes.extend_from_slice(chunk); + } + digest_of_bytes(&bytes) +} + +/// The state digest of a worker's capture payload. +pub fn payload_state_digest(payload: &[u8]) -> Result { + let parts = decode_envelope(payload, PAYLOAD_MAGIC).map_err(|e| e.to_string())?; + let state = agent_from_chunks(&parts.manifest, &parts).map_err(|e| e.to_string())?; + Ok(state_digest(&state)) +} + +/// The first record at which two runs differ, described. +pub fn compare(left: &[ParityRecord], right: &[ParityRecord]) -> Result<(), String> { + for (a, b) in left.iter().zip(right) { + if a != b { + let mut fields = Vec::new(); + let (ja, jb) = (a.to_json(), b.to_json()); + for key in [ + "kind", + "boundary", + "ticks", + "brainTicks", + "remainder", + "decision", + "telemetry", + "spikes", + "state", + ] { + if ja[key] != jb[key] { + fields.push(format!("{key}: {} != {}", ja[key], jb[key])); + } + } + return Err(format!( + "record {} ({}) differs: {}", + a.index, + a.kind, + fields.join("; ") + )); + } + } + if left.len() != right.len() { + return Err(format!("{} records against {}", left.len(), right.len())); + } + Ok(()) +} + +/// A source of reference records for a script. +/// +/// [`DirectReference`] is one. FND-01's `LegacyFrame` trace (`FLY_TRACE`) is meant to be the +/// other: it would produce the same records from the running legacy loop, and at that point the +/// transcription in [`DirectReference`] is itself checked against the service. +pub trait ReferenceSource { + fn records(&mut self, script: &LegacyScript) -> Result, String>; +} + +// ------------------------------------------------------------------------------------------- +// The direct reference: NeuralAgent in `Sim::step_frame` order + +/// `NeuralAgent` driven the way `flysim::simloop::Sim` drives it, transcribed line by line from +/// `fresh_start`, `step_frame`, `recover` and `try_restore`, with the emulator, adapter and +/// macro layer replaced by the script's recorded outputs. +pub struct DirectReference { + dataset: Arc, + agent: NeuralAgent, + macro_channels: Vec, + // `Sim`'s own fields. + remainder: f64, + location: Option, + held_channel: Option, + blocked_since_ms: f64, + frame_buffer: Vec, + /// What the adapter and the macro layer would report after the last frame. + boot: bool, + bound: Vec, + /// Reinforcement calls, for `learning.updates`. + reinforcements: u64, +} + +impl DirectReference { + fn build(dataset: Arc, macro_channels: &[String]) -> Result { + let channels: Vec<&str> = macro_channels.iter().map(String::as_str).collect(); + let mut config = + CoreAgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels)); + config.warmup_ms = gameboy::WARMUP_MS; + NeuralAgent::new(dataset, config).map_err(|e| e.to_string()) + } + + /// `Sim::boot` with no checkpoint: `fresh_start` warms up on the setup frame. + pub fn fresh( + dataset: Arc, + script: &LegacyScript, + ) -> Result<(DirectReference, ParityRecord), String> { + let mut agent = DirectReference::build(dataset.clone(), &script.macro_channels)?; + let frame = script.frames[script.initial_frame].clone(); + agent.warmup(Some(&frame)).map_err(|e| e.to_string())?; + let reference = DirectReference { + dataset, + agent, + macro_channels: script.macro_channels.clone(), + remainder: 0.0, + location: None, + held_channel: None, + blocked_since_ms: 0.0, + frame_buffer: frame, + boot: script.initial_context.boot, + bound: script.initial_context.bound.clone(), + reinforcements: 0, + }; + let record = reference.record(0, "initialize", 0, gameboy::WARMUP_MS, None, None); + Ok((reference, record)) + } + + fn record( + &self, + index: usize, + kind: &'static str, + boundary: u64, + ticks: u64, + decision: Option, + spikes: Option, + ) -> ParityRecord { + ParityRecord { + index, + kind, + boundary, + ticks, + brain_ticks: self.agent.network.ms as u64, + remainder: legacy_remainder_to_rational(self.remainder).expect("a legacy remainder"), + decision, + telemetry: Some(telemetry_of( + &self.agent, + self.agent.network.ms as u64, + self.reinforcements, + )), + spikes, + state: None, + } + } + + /// The full state as `Sim::checkpoint` exports it: the loop owns the remainder. + pub fn state_digest(&self) -> Digest { + let mut state = self.agent.export_state(); + state.remainder = self.remainder; + state_digest(&state) + } + + /// `drain_commands` (sugar) and then `Sim::step_frame`'s agent half. + fn frame( + &mut self, + sugar: &[f64], + frame: &[u8], + rewards: &[RewardEvent], + next: &ReadoutContext, + ) -> (u64, ChannelsDecision, Digest) { + // Commands: `self.agent.network.stimulate(duration)`. + for duration in sugar { + self.agent.network.stimulate(*duration); + } + // 2. Step the brain. + self.remainder += self.agent.ms_per_frame; + let steps = self.remainder.floor(); + self.remainder -= steps; + let since = self.agent.network.ms; + self.agent.network.step(steps as u64); + // 3. Decode. + let boot = self.boot; + let ms = self.agent.network.ms; + let rates = self.agent.network.rates.clone(); + let blocked_ms = self.agent.decoder.blocked_ms(); + let blocked = (blocked_ms > 0.0 && ms - self.blocked_since_ms >= blocked_ms) + .then(|| self.agent.decoder.current()) + .flatten() + .map(str::to_string); + let bound = (!self.macro_channels.is_empty()).then(|| self.bound.clone()); + let active = + self.agent + .decoder + .decode_bound(&rates, ms, boot, blocked.as_deref(), bound.as_deref()); + let held = self.agent.decoder.current().map(str::to_string); + if held != self.held_channel { + self.held_channel = held; + self.blocked_since_ms = ms; + } + let mask = to_button_mask(&active); + let decision = channels_decision(&active, &self.bound); + debug_assert_eq!(u32::from(decision.mask()), mask); + // 5. Run a frame (recorded), 6. set the visual frame from it. + self.frame_buffer.copy_from_slice(frame); + let (width, height) = (self.agent.frame.width, self.agent.frame.height); + self.agent + .network + .set_visual_frame(&self.frame_buffer, width, height); + // 7. Sample rewards (recorded), 8. stimulate once per event, 9. reinforce with the sum. + let ms = self.agent.network.ms; + let mut total = 0.0; + for event in rewards { + self.agent.network.stimulate(event.stimulation_ms); + total += event.value; + } + if self.agent.network.plasticity.enabled { + self.agent.network.plasticity.reinforce(total, ms); + self.reinforcements += 1; + } + // `observe` (recorded as the next context's bound) and the cooldown's other reset. + self.boot = next.boot; + self.bound = next.bound.clone(); + let location = next.location; + if location.is_some() && location != self.location { + self.location = location; + self.blocked_since_ms = ms; + } + let spikes = digest_of_bytes(&spike_bitset(&self.agent.network.last_spike_ms, since, ms)); + (steps as u64, decision, spikes) + } + + /// `Sim::recover`: `recover_game`'s neural half, then the loop's own transients. + fn rollback(&mut self, frame: &[u8], context: &ReadoutContext) { + let ms = self.agent.network.ms; + self.agent.decoder.clear_holds(ms); + let ms = self.agent.network.ms; + self.agent.network.plasticity.clear_eligibility(ms); + let (width, height) = (self.agent.frame.width, self.agent.frame.height); + self.agent.network.set_visual_frame(frame, width, height); + self.frame_buffer.copy_from_slice(frame); + self.location = context.location; + self.held_channel = None; + self.blocked_since_ms = self.agent.network.ms; + self.boot = context.boot; + self.bound = context.bound.clone(); + } + + /// A service restart onto the last checkpoint: `Sim::boot`'s fresh fields, then + /// `try_restore`'s agent half. The executor observes the restored world before the first + /// frame, which is the context this reference already holds. + fn restore(&mut self) -> Result<(), String> { + let mut state = self.agent.export_state(); + state.remainder = self.remainder; + let mut agent = DirectReference::build(self.dataset.clone(), &self.macro_channels)?; + agent.import_state(&state).map_err(|e| e.to_string())?; + self.agent = agent; + self.remainder = state.remainder; + let (width, height) = (self.agent.frame.width, self.agent.frame.height); + self.agent + .network + .set_visual_frame(&self.frame_buffer, width, height); + self.location = None; + self.held_channel = None; + self.blocked_since_ms = 0.0; + Ok(()) + } +} + +/// [`ReferenceSource`] over a dataset directory. +pub struct DirectSource { + pub dataset: Arc, +} + +impl ReferenceSource for DirectSource { + fn records(&mut self, script: &LegacyScript) -> Result, String> { + let (mut reference, first) = DirectReference::fresh(self.dataset.clone(), script)?; + let mut records = vec![first]; + let mut boundary = 0u64; + for (index, step) in script.steps.iter().enumerate() { + let mut record = match step { + ScriptStep::Frame { + sugar, + frame, + rewards, + next_context, + } => { + let (ticks, decision, spikes) = + reference.frame(sugar, &script.frames[*frame], rewards, next_context); + boundary += 1; + reference.record( + index + 1, + "frame", + boundary, + ticks, + Some(decision), + Some(spikes), + ) + } + ScriptStep::Rollback { frame, context } => { + reference.rollback(&script.frames[*frame], context); + reference.record(index + 1, "rollback", boundary, 0, None, None) + } + ScriptStep::Restore => { + reference.restore()?; + let mut record = + reference.record(index + 1, "restore", boundary, 0, None, None); + // An ActivateRestore reply carries no telemetry; the record says so. + record.telemetry = None; + record.state = Some(reference.state_digest()); + record + } + }; + if script.checkpoints.contains(&index) { + record.state = Some(reference.state_digest()); + } + records.push(record); + } + Ok(records) + } +} + +// ------------------------------------------------------------------------------------------- +// The worker side: a launched LegacyAgentWorker driven over the bus + +const DRIVER_CLIENT: &str = "coordinator"; +const MAX_GENERATIONS: u32 = 8; + +fn agent_service(agent_id: &Id) -> String { + format!("agent.{agent_id}") +} + +fn agent_client(agent_id: &Id, generation: u32) -> String { + if generation <= 1 { + format!("worker-{agent_id}") + } else { + format!("worker-{agent_id}-r{generation}") + } +} + +fn grants(f: impl FnOnce(&mut Grants)) -> Grants { + let mut g = Grants::default(); + f(&mut g); + g +} + +/// One legacy agent the rig launches. +#[derive(Clone, Debug)] +pub struct RigAgent { + pub agent_id: Id, + pub port_id: Id, + pub dataset_dir: PathBuf, + pub profile: LegacyProfileKind, + pub macro_channels: Vec, + pub worker_threads: usize, +} + +/// A router, a launcher in one execution mode and the legacy agents it started: the smallest +/// composition that runs `LegacyAgentWorker` under `fly-session`'s own supervisor. The +/// coordinator's part is played by [`AgentDriver`]s on one bus client. +pub struct LegacyRig { + pub launcher: Launcher, + pub client: Client, + pub session_id: Id, + pub mode: ExecutionMode, + agents: BTreeMap, +} + +impl LegacyRig { + pub async fn start( + root: &Path, + mode: ExecutionMode, + agents: &[RigAgent], + ) -> Result { + let session_id = id("legacy"); + let store_root = root.join("store"); + let sockets = root.join("sockets"); + std::fs::create_dir_all(&sockets).map_err(|e| format!("sockets: {e}"))?; + let mut policy = Policy::closed() + .client( + DRIVER_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("agent.")]), + ) + .client( + SUPERVISOR_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("agent.")]), + ); + for agent in agents { + let service = agent_service(&agent.agent_id); + for generation in 1..=MAX_GENERATIONS { + policy = policy.client( + &agent_client(&agent.agent_id, generation), + grants(|g| g.register = vec![Pattern::exact(&service)]), + ); + } + } + let mut config = RouterConfig::new(&store_root); + config.policy = policy; + let router = Router::new(config).map_err(|e| format!("router: {e}"))?; + let total = 1 + agents.iter().map(|a| a.worker_threads).sum::(); + let budget = ThreadBudget::new(total, 1).map_err(|e| e.message)?; + let launcher = Launcher::start(router, mode, Via::Unix, &store_root, &sockets, budget) + .await + .map_err(|e| format!("launcher: {}", e.message))?; + let client = launcher + .connect(DRIVER_CLIENT) + .await + .map_err(|e| format!("connect: {}", e.message))?; + let mut rig = LegacyRig { + launcher, + client, + session_id, + mode, + agents: BTreeMap::new(), + }; + for agent in agents { + rig.agents + .insert(agent.agent_id.clone(), (agent.clone(), 0)); + rig.launch(&agent.agent_id).await?; + } + Ok(rig) + } + + async fn launch(&mut self, agent_id: &Id) -> Result { + let (agent, generation) = self.agents.get_mut(agent_id).ok_or("unknown agent")?; + *generation += 1; + let spec = LegacyAgentLaunch { + session_id: self.session_id.clone(), + agent_id: agent.agent_id.clone(), + port_id: agent.port_id.clone(), + incarnation_id: parse_id(&format!("{}-inc-{generation}", agent.agent_id))?, + worker_threads: agent.worker_threads, + dataset_dir: agent.dataset_dir.clone(), + profile: agent.profile, + macro_channels: agent.macro_channels.clone(), + client_id: agent_client(&agent.agent_id, *generation), + service: agent_service(&agent.agent_id), + }; + self.launcher + .launch_legacy_agent(spec) + .await + .map_err(|e| e.message)?; + Ok(self.worker_ref(agent_id)) + } + + pub fn worker_ref(&self, agent_id: &Id) -> WorkerRef { + self.launcher + .worker(agent_id) + .expect("launched") + .worker_ref() + } + + /// Stops an agent's worker and starts its replacement: a new process in process mode, with + /// a new incarnation and a new client identity, uninitialized. + pub async fn replace(&mut self, agent_id: &Id) -> Result { + self.launcher.reap(agent_id, &id("replaced")).await; + self.launch(agent_id).await + } + + pub async fn stop(mut self) { + self.launcher.reap_all(&id("done")).await; + } + + /// A driver for one agent, playing the coordinator's part. + pub fn driver(&self, agent_id: &Id, script: &LegacyScript) -> AgentDriver { + let (agent, _) = &self.agents[agent_id]; + AgentDriver { + client: self.client.clone(), + target: self.worker_ref(agent_id), + session_id: self.session_id.clone(), + agent_id: agent_id.clone(), + profile: agent.profile.profile(), + epoch_serial: 1, + boundary: 0, + serials: Serials::default(), + context: script.initial_context.to_typed(), + frames: script.frames.clone(), + captures: 0, + remainder: RationalNs::ZERO, + } + } +} + +fn domain(e: DomainError) -> String { + format!("{:?}: {}", e.code, e.message) +} + +/// The coordinator's side of one agent: scopes, request serials, frame artifacts and the +/// context it last sent. +pub struct AgentDriver { + client: Client, + target: WorkerRef, + session_id: Id, + agent_id: Id, + profile: LegacyAgentProfile, + epoch_serial: u32, + boundary: u64, + serials: Serials, + context: TypedValue, + frames: Arc>>, + captures: u64, + /// The remainder the last Prepare reported: a rollback keeps it. + remainder: RationalNs, +} + +/// A captured payload, held for a restore. +pub struct Captured { + pub result: CaptureResult, + pub artifact: flybus::Artifact, + pub bytes: Vec, + pub scope: Scope, +} + +impl AgentDriver { + fn epoch(&self) -> Id { + id(&format!("e{}", self.epoch_serial)) + } + + fn scope(&self) -> Scope { + scope_at(&self.session_id, &self.epoch(), self.boundary) + } + + async fn frame_input( + &self, + frame: usize, + boundary: u64, + ) -> Result<(SensoryInput, flybus::Artifact), String> { + let artifact = crate::media::seal_copy( + &self.client, + crate::media::FRAME_CONTENT_TYPE.to_owned(), + &self.frames[frame], + ) + .await + .map_err(domain)?; + let input = SensoryInput { + boundary, + views: vec![ViewRef { + view_id: gameboy::VIEW_ID.to_owned(), + produced_step: boundary, + pixels: artifact.reference().clone(), + }], + structured: None, + }; + Ok((input, artifact)) + } + + async fn call( + &mut self, + method: &str, + scope: Option, + params: Value, + attachments: &[(&str, &flybus::Artifact)], + want: &[&str], + ) -> Result { + let request_id = self.serials.next(&self.target.service); + let want: Vec = want.iter().map(|w| (*w).to_owned()).collect(); + let reply = call( + &self.client, + &self.target, + method, + scope, + object(params), + attachments, + request_id, + &want, + ) + .await + .map_err(|e| format!("{method}: {}", domain(e)))?; + reply + .result() + .map_err(|e| format!("{method}: {}", domain(e)))?; + Ok(reply) + } + + /// One call with any params, its domain outcome returned as it stands: for tests that + /// need the worker to refuse something. + pub async fn call_raw( + &mut self, + method: &str, + scope: Option, + params: Value, + attachments: &[(&str, &flybus::Artifact)], + ) -> Result { + let request_id = self.serials.next(&self.target.service); + call( + &self.client, + &self.target, + method, + scope, + object(params), + attachments, + request_id, + &[], + ) + .await + } + + /// The same request again, same id and body: a domain retry. + pub async fn retry_raw( + &mut self, + request_id: DomainRequestId, + method: &str, + scope: Option, + params: Value, + ) -> Result { + call( + &self.client, + &self.target, + method, + scope, + object(params), + &[], + request_id, + &[], + ) + .await + } + + /// A sealed frame from the script's pool, as a sensory input observing `boundary`. + pub async fn input( + &self, + frame: usize, + boundary: u64, + ) -> Result<(SensoryInput, flybus::Artifact), String> { + self.frame_input(frame, boundary).await + } + + /// The scope of the committed boundary this driver is at. + pub fn current_scope(&self) -> Scope { + self.scope() + } + + /// Moves the driver to the next epoch without telling the worker, to address it wrongly. + pub fn bump_epoch(&mut self) { + self.epoch_serial += 1; + } + + pub fn context(&self) -> &TypedValue { + &self.context + } + + pub fn profile(&self) -> &AssetRef { + &self.profile.asset + } + + async fn acknowledge(&mut self, request_id: DomainRequestId) -> Result<(), String> { + let params = AcknowledgeParams { + request_ids: vec![request_id], + }; + self.call("Worker.Acknowledge", None, params.to_json(), &[], &[]) + .await + .map(|_| ()) + } + + pub async fn initialize(&mut self, initial_frame: usize) -> Result { + let (input, artifact) = self.frame_input(initial_frame, 0).await?; + let params = AgentInitializeParams { + agent_id: self.agent_id.clone(), + profile: self.profile.asset.clone(), + seed: LEGACY_SEED, + initial_input: input, + initial_decision_context: self.context.clone(), + worker_threads: 1, + }; + let reply = self + .call( + "Agent.Initialize", + Some(self.scope()), + params.to_json(), + &[("view.lcd", &artifact)], + &[], + ) + .await?; + let result: AgentInitializeResult = reply.parse().map_err(domain)?; + if result + .telemetry + .rates + .iter() + .map(|r| r.role_id.as_str()) + .ne(result.graph.rate_roles.iter().map(String::as_str)) + { + return Err("telemetry rates are not in AgentGraph.rateRoles order".to_owned()); + } + self.acknowledge(reply.request_id).await?; + Ok(ParityRecord { + index: 0, + kind: "initialize", + boundary: 0, + ticks: result.warmup_ticks, + brain_ticks: result.telemetry.brain_ticks, + remainder: RationalNs::ZERO, + decision: None, + telemetry: Some(result.telemetry), + spikes: None, + state: None, + }) + } + + /// Prepare then Commit: one transition. + pub async fn frame( + &mut self, + index: usize, + sugar: &[f64], + frame: usize, + rewards: &[RewardEvent], + next_context: &ReadoutContext, + ) -> Result { + let k = self.boundary; + let prepare = PrepareParams { + agent_id: self.agent_id.clone(), + profile_digest: self.profile.asset.digest.clone(), + interval: gameboy::step_duration(), + decision_context_digest: self.context.digest(), + pre_step_stimulations: sugar + .iter() + .enumerate() + .map(|(n, ms)| Stimulus { + id: id(&format!("sugar-{k}-{n}")), + kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(), + duration_ms: *ms, + }) + .collect(), + }; + let reply = self + .call( + "Agent.Prepare", + Some(self.scope()), + prepare.to_json(), + &[], + &[], + ) + .await?; + let prepared: PreparedDecision = reply.parse().map_err(domain)?; + let decision = ChannelsDecision::from_typed(&prepared.decision).map_err(|e| e.0)?; + + let (input, artifact) = self.frame_input(frame, k + 1).await?; + let next = next_context.to_typed(); + let commit = CommitParams { + agent_id: self.agent_id.clone(), + prepared_request_id: reply.request_id.clone(), + next_input: input, + next_decision_context: next.clone(), + rewards: rewards + .iter() + .enumerate() + .map(|(n, e)| Reward { + event_id: id(&format!("ev-{k}-{n}")), + rule_id: id("toy"), + value: e.value, + }) + .collect(), + task_stimulations: rewards + .iter() + .enumerate() + .map(|(n, e)| Stimulus { + id: id(&format!("ev-{k}-{n}")), + kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(), + duration_ms: e.stimulation_ms, + }) + .collect(), + }; + let reply = self + .call( + "Agent.Commit", + Some(self.scope()), + commit.to_json(), + &[("view.lcd", &artifact)], + &[SPIKES_ATTACHMENT], + ) + .await?; + let result: AgentCommitResult = reply.parse().map_err(domain)?; + if result.committed_step != k + 1 || result.decision_context_digest != next.digest() { + return Err(format!( + "Agent.Commit acknowledged {} with another context", + result.committed_step + )); + } + let spikes = match reply.artifacts.get(SPIKES_ATTACHMENT) { + Some(artifact) => digest_of_bytes(&artifact.read_all().await.map_err(|e| e.message)?), + None => return Err("Agent.Commit carried no spike bitset".to_owned()), + }; + self.context = next; + self.boundary = k + 1; + self.remainder = prepared.remainder; + Ok(ParityRecord { + index, + kind: "frame", + boundary: k + 1, + ticks: prepared.ticks_advanced, + brain_ticks: prepared.brain_ticks, + remainder: prepared.remainder, + decision: Some(decision), + telemetry: Some(result.telemetry), + spikes: Some(spikes), + state: None, + }) + } + + /// `legacy-ratchet-rollback-v1`'s agent half, under a new epoch at the same boundary. + pub async fn rollback( + &mut self, + index: usize, + frame: usize, + context: &ReadoutContext, + ) -> Result { + let prior = self.epoch(); + self.epoch_serial += 1; + let (input, artifact) = self.frame_input(frame, self.boundary).await?; + let typed = context.to_typed(); + let params = AgentRollbackParams { + agent_id: self.agent_id.clone(), + prior_epoch: prior, + policy: ROLLBACK_POLICY.to_owned(), + input, + decision_context: typed.clone(), + }; + let reply = self + .call( + METHOD_AGENT_ROLLBACK, + Some(self.scope()), + params.to_json(), + &[("view.lcd", &artifact)], + &[], + ) + .await?; + let result: AgentRollbackResult = reply.parse().map_err(domain)?; + result + .validate_against_scope(&self.scope()) + .map_err(|e| e.0)?; + self.context = typed; + Ok(ParityRecord { + index, + kind: "rollback", + boundary: self.boundary, + ticks: 0, + brain_ticks: result.telemetry.brain_ticks, + remainder: self.remainder, + decision: None, + telemetry: Some(result.telemetry), + spikes: None, + state: None, + }) + } + + /// `State.Capture` at the committed boundary. + pub async fn capture(&mut self) -> Result { + self.captures += 1; + let scope = self.scope(); + let params = CaptureParams { + checkpoint_id: id(&format!("cp-{}", self.captures)), + }; + let reply = self + .call( + "State.Capture", + Some(scope.clone()), + params.to_json(), + &[], + &[crate::state::PAYLOAD_ATTACHMENT], + ) + .await?; + let result: CaptureResult = reply.parse().map_err(domain)?; + let artifact = reply + .artifacts + .get(crate::state::PAYLOAD_ATTACHMENT) + .cloned() + .ok_or("State.Capture carried no payload")?; + let bytes = artifact.read_all().await.map_err(|e| e.message)?; + self.acknowledge(reply.request_id).await?; + Ok(Captured { + result, + artifact, + bytes, + scope, + }) + } + + /// A group restore into `target`, a fresh replacement worker, under a new epoch. + pub async fn restore_into( + &mut self, + target: WorkerRef, + captured: &Captured, + ) -> Result<(), String> { + self.target = target; + self.epoch_serial += 1; + let params = StageRestoreParams { + checkpoint_id: captured.result.checkpoint_id.clone(), + source_scope: captured.scope.clone(), + compatibility_digest: captured.result.compatibility_digest.clone(), + payload: captured.artifact.reference().clone(), + }; + let reply = self + .call( + "State.StageRestore", + Some(self.scope()), + params.to_json(), + &[(crate::state::PAYLOAD_ATTACHMENT, &captured.artifact)], + &[], + ) + .await?; + let staged: StageRestoreResult = reply.parse().map_err(domain)?; + self.acknowledge(reply.request_id).await?; + let params = ActivateRestoreParams { + restore_token: staged.restore_token, + }; + let reply = self + .call("State.ActivateRestore", None, params.to_json(), &[], &[]) + .await?; + let activated: ActivateRestoreResult = reply.parse().map_err(domain)?; + if activated.committed_step != self.boundary { + return Err("State.ActivateRestore landed on another boundary".to_owned()); + } + self.acknowledge(reply.request_id).await + } +} + +/// Runs a script against the rig's agent, recording what the coordinator observes. +pub async fn run_on_worker( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, +) -> Result, String> { + let mut driver = rig.driver(agent_id, script); + let mut records = vec![driver.initialize(script.initial_frame).await?]; + for (index, step) in script.steps.iter().enumerate() { + let mut record = match step { + ScriptStep::Frame { + sugar, + frame, + rewards, + next_context, + } => { + driver + .frame(index + 1, sugar, *frame, rewards, next_context) + .await? + } + ScriptStep::Rollback { frame, context } => { + driver.rollback(index + 1, *frame, context).await? + } + ScriptStep::Restore => { + let captured = driver.capture().await?; + let target = rig.replace(agent_id).await?; + driver.restore_into(target, &captured).await?; + // The replacement's own capture: a restore is exact for everything captured. + let after = driver.capture().await?; + ParityRecord { + index: index + 1, + kind: "restore", + boundary: driver.boundary, + ticks: 0, + brain_ticks: captured_brain_ticks(&after.bytes)?, + remainder: captured_remainder(&after.bytes)?, + decision: None, + telemetry: None, + spikes: None, + state: Some(payload_state_digest(&after.bytes)?), + } + } + }; + if script.checkpoints.contains(&index) { + let captured = driver.capture().await?; + record.state = Some(payload_state_digest(&captured.bytes)?); + } + records.push(record); + } + Ok(records) +} + +fn captured_session(payload: &[u8]) -> Result { + let parts = decode_envelope(payload, PAYLOAD_MAGIC).map_err(|e| e.to_string())?; + let session = parts.manifest.get("session").ok_or("no session member")?; + serde_json::from_str(&session.stringify()).map_err(|e| e.to_string()) +} + +fn captured_brain_ticks(payload: &[u8]) -> Result { + captured_session(payload)?["accumulator"]["executedTicks"] + .as_str() + .and_then(|s| s.parse().ok()) + .ok_or_else(|| "no executedTicks".to_owned()) +} + +fn captured_remainder(payload: &[u8]) -> Result { + RationalNs::from_json(&captured_session(payload)?["accumulator"]["remainder"]).map_err(|e| e.0) +} + +/// The rows and the overall digest of a record sequence, as a golden file holds them. +pub fn golden_json(script: &LegacyScript, records: &[ParityRecord]) -> Value { + let all: Vec = records.iter().map(ParityRecord::to_json).collect(); + json!({ + "scenario": script.name, + "macroChannels": script.macro_channels, + "records": records.len(), + "digest": digest_of(&Value::Array(all)).expect("records canonicalize"), + "rows": records.iter().map(ParityRecord::row).collect::>(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_frame_pool_and_scripts_are_deterministic() { + assert_eq!(frame_pool(3, 7), frame_pool(3, 7)); + assert_ne!(frame_pool(3, 7)[0], frame_pool(3, 7)[1]); + let script = toy_macros_script(260); + assert_eq!( + script + .steps + .iter() + .filter(|s| matches!(s, ScriptStep::Rollback { .. })) + .count(), + 1 + ); + assert_eq!( + script + .steps + .iter() + .filter(|s| matches!(s, ScriptStep::Restore)) + .count(), + 1 + ); + for step in &script.steps { + if let ScriptStep::Frame { next_context, .. } = step { + next_context + .validate_against(&script.macro_channels) + .expect("a valid context"); + } + } + } +} diff --git a/services/flysim/crates/fly-session/src/lib.rs b/services/flysim/crates/fly-session/src/lib.rs index 74a21c9..fcb005e 100644 --- a/services/flysim/crates/fly-session/src/lib.rs +++ b/services/flysim/crates/fly-session/src/lib.rs @@ -30,6 +30,7 @@ pub mod environment; pub mod harness; pub mod launcher; pub mod legacy_agent; +pub mod legacy_parity; pub mod measure; pub mod media; pub mod metrics; From bd57b73b72daa8d026779c7a14c979b0edbadc68 Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 23 Sep 2026 14:45:25 +0000 Subject: [PATCH 05/26] tests: legacy agent goldens in every execution mode, two flies, and the refusals --- .../fixtures/toy-macros.golden.json | 276 ++++++++ .../fly-session/fixtures/toy-raw.golden.json | 90 +++ .../crates/fly-session/tests/legacy_agent.rs | 587 ++++++++++++++++++ 3 files changed, 953 insertions(+) create mode 100644 services/flysim/crates/fly-session/fixtures/toy-macros.golden.json create mode 100644 services/flysim/crates/fly-session/fixtures/toy-raw.golden.json create mode 100644 services/flysim/crates/fly-session/tests/legacy_agent.rs diff --git a/services/flysim/crates/fly-session/fixtures/toy-macros.golden.json b/services/flysim/crates/fly-session/fixtures/toy-macros.golden.json new file mode 100644 index 0000000..e71c761 --- /dev/null +++ b/services/flysim/crates/fly-session/fixtures/toy-macros.golden.json @@ -0,0 +1,276 @@ +{ + "scenario": "toy-macros", + "macroChannels": [ + "macro_go_out", + "macro_talk", + "macro_menu", + "macro_next" + ], + "records": 263, + "digest": "bae9357bb565266fdefba66004f792aa52a44e283fa73853e0c4f3de50790f86", + "rows": [ + "0 initialize b0 t2500 bt2500 m-- - p0 d676a54ce95aef0e", + "1 frame b1 t16 bt2516 m61 - p0 42a0dfdbf7fe8f55", + "2 frame b2 t17 bt2533 m61 - p0 bc0b415d8f485283", + "3 frame b3 t17 bt2550 m71 - p0 b953d63ad5548f84", + "4 frame b4 t16 bt2566 m71 - p0 5c6d3fef3c75b7e0", + "5 frame b5 t17 bt2583 m31 - p0 81b637fc70c20259", + "6 frame b6 t17 bt2600 m31 - p0 94e77ebf0653ed58", + "7 frame b7 t17 bt2617 m11 - p0 e9dc82d6837e1251", + "8 frame b8 t16 bt2633 m11 - p0 0997f4d5d11c3b28", + "9 frame b9 t17 bt2650 m01 - p0 ba71c1d68725ebd8", + "10 frame b10 t17 bt2667 m01 - p0 eb276406234e10c3", + "11 frame b11 t17 bt2684 m01 - p0 f51fa31f018683e7", + "12 frame b12 t16 bt2700 m01 - p0 91bfe963a2c0b0a4", + "13 frame b13 t17 bt2717 m01 - p0 6cb4d3b49ec11d37", + "14 frame b14 t17 bt2734 m01 - p0 7fb10c988bdfaafa", + "15 frame b15 t17 bt2751 m01 - p0 0277076d6c3855b1", + "16 frame b16 t16 bt2767 m01 - p0 f6b44b410581a903", + "17 frame b17 t17 bt2784 m01 - p120 5d5605f21806a2e8", + "18 frame b18 t17 bt2801 m01 - p103 e19f8f734ab1f79b", + "19 frame b19 t17 bt2818 m01 - p86 08c3045b0edda21d", + "20 frame b20 t16 bt2834 m01 - p70 70183eb4539388c6", + "21 frame b21 t17 bt2851 m01 - p53 ee10901597a34ff7", + "22 frame b22 t17 bt2868 m01 - p36 083b83cf159f8210", + "23 frame b23 t17 bt2885 m01 - p19 8e145a0fbe7439c6", + "24 frame b24 t16 bt2901 m01 - p3 b78dce0e1c9a4943", + "25 frame b25 t17 bt2918 m01 - p283 dfb93db9b8f19e8d", + "26 frame b26 t17 bt2935 m01 - p266 0c06868a06292d58", + "27 frame b27 t17 bt2952 m01 - p249 db4407e92950062d", + "28 frame b28 t16 bt2968 m01 - p233 c1eb8900546ebae6", + "29 frame b29 t17 bt2985 m01 - p216 0713b6bacce29e09", + "30 frame b30 t17 bt3002 m21 - p199 9e9fdbd1da35dddf", + "31 frame b31 t17 bt3019 m21 - p182 a67b8a9886ed6406", + "32 frame b32 t16 bt3035 m31 - p166 5de0bb3548fa8221", + "33 frame b33 t17 bt3052 m31 - p149 e443c6858ccfeefd", + "34 frame b34 t17 bt3069 m31 - p132 aad26ee01fcd8305", + "35 frame b35 t16 bt3085 m31 - p116 cbccd5cba4cf7428", + "36 frame b36 t17 bt3102 m11 - p99 2cb0a9bb493b3125", + "37 frame b37 t17 bt3119 m11 - p82 2c7d70fcdcfe1837", + "38 frame b38 t17 bt3136 m01 - p65 fbf14295f4fe432d", + "39 frame b39 t16 bt3152 m01 - p49 451f9f5b82706d20", + "40 frame b40 t17 bt3169 m01 - p32 683611e4e6578d1a state", + "41 frame b41 t17 bt3186 m01 - p15 83171b3ea9a7ea1e", + "42 frame b42 t17 bt3203 m01 - p0 05132a48c701a11b", + "43 frame b43 t16 bt3219 m01 - p0 32f1b389f783cfea", + "44 frame b44 t17 bt3236 m01 - p0 4399da53e142a8f7", + "45 frame b45 t17 bt3253 m01 - p0 83549f68a27e4a9f", + "46 frame b46 t17 bt3270 m01 - p0 8694cd49107aed69", + "47 frame b47 t16 bt3286 m01 - p0 b25ba2454528cca3", + "48 frame b48 t17 bt3303 m01 - p0 2623228af9f21266", + "49 frame b49 t17 bt3320 m02 - p0 6c82e578ef54c4c6", + "50 frame b50 t17 bt3337 m02 - p200 fa26f4f2b6e85a66", + "51 frame b51 t16 bt3353 m02 - p184 a6519d51e6a73409", + "52 frame b52 t17 bt3370 m02 - p167 804482d83c7ab25c", + "53 frame b53 t17 bt3387 m02 - p150 470afd9213bc9c69", + "54 frame b54 t17 bt3404 m02 - p133 672eb341bbee0c13", + "55 frame b55 t16 bt3420 m02 - p117 c6fdf33189fdb90a", + "56 frame b56 t17 bt3437 m02 - p100 a8b9177d330a06e1", + "57 frame b57 t17 bt3454 m02 - p83 0a96ab3adaf4ad87", + "58 frame b58 t17 bt3471 m02 - p66 89a10bb29ad693b6", + "59 frame b59 t16 bt3487 m22 - p50 d21f628e694c9a30", + "60 frame b60 t17 bt3504 m22 - p33 1a90f7e1f39f8a9d", + "61 frame b61 t17 bt3521 m32 macro_go_out p16 6b4e16812d8e4f98", + "62 frame b62 t17 bt3538 m32 macro_go_out p0 6617f27084cbb4c4", + "63 frame b63 t16 bt3554 m32 macro_go_out p0 352dde16702d22e1", + "64 frame b64 t17 bt3571 m32 macro_go_out p0 f91ec167d9a58161", + "65 frame b65 t17 bt3588 m12 macro_go_out p0 e2bbebc4ae5bb7c4", + "66 frame b66 t17 bt3605 m12 macro_go_out p0 71c1ebb6dfd44c1d", + "67 frame b67 t16 bt3621 m02 macro_go_out p0 6eb754b6d554ba64", + "68 frame b68 t17 bt3638 m02 macro_go_out p120 df0f4262f12a1cf7", + "69 frame b69 t17 bt3655 m02 macro_go_out p103 86c885bef55e8a76", + "70 frame b70 t16 bt3671 m02 macro_go_out p87 2de699b76b49ab85", + "71 frame b71 t17 bt3688 m02 macro_go_out p70 c73ebc28ca5f17ef", + "72 frame b72 t17 bt3705 m02 macro_go_out p53 5183a17558475ba4", + "73 frame b73 t17 bt3722 m02 macro_go_out p36 89a85c2d5f3a00dc", + "74 frame b74 t16 bt3738 m02 macro_go_out p20 504f6dca39cd12b9", + "75 frame b75 t17 bt3755 m02 macro_go_out p3 a23856ba2da98a74", + "76 frame b76 t17 bt3772 m02 macro_go_out p0 ff33e61ab59ca37e", + "77 frame b77 t17 bt3789 m02 macro_go_out p60 2e8876d54628e0da", + "78 frame b78 t16 bt3805 m02 macro_go_out p44 dbeca8ee685d0192", + "79 frame b79 t17 bt3822 m02 macro_go_out p27 3e2b6d875dba48c8", + "80 frame b80 t17 bt3839 m02 macro_go_out p10 31db168c0f6eef32 state", + "81 frame b81 t17 bt3856 m02 macro_go_out p0 af13492eb695dca6", + "82 frame b82 t16 bt3872 m02 macro_go_out p0 f9dca4bdd2edc20f", + "83 frame b83 t17 bt3889 m02 macro_go_out p0 19e59572d5922d09", + "84 frame b84 t17 bt3906 m02 macro_go_out p0 75e97690028f994d", + "85 frame b85 t17 bt3923 m02 macro_go_out p120 c68320e6515dd1d5", + "86 frame b86 t16 bt3939 m02 macro_go_out p104 89f1b529935223dc", + "87 frame b87 t17 bt3956 m02 macro_go_out p87 14bc1a0bbc7c9f48", + "88 frame b88 t17 bt3973 m22 macro_go_out p70 a04f92a4392e353c", + "89 frame b89 t17 bt3990 m22 macro_go_out p53 7ebb5b12ec25c397", + "90 frame b90 t16 bt4006 m32 macro_go_out p37 27ac565dda76999b", + "91 frame b91 t17 bt4023 m32 macro_go_out p20 61796a4ab7529877", + "92 frame b92 t17 bt4040 m32 macro_go_out p3 1f3dbcc2c303ff24", + "93 frame b93 t17 bt4057 m32 macro_go_out p0 84de4dd82b9054d6", + "94 frame b94 t16 bt4073 m12 macro_go_out p0 4ad0f5fe4ec4e4e8", + "95 frame b95 t17 bt4090 m12 macro_go_out p0 f3c60e6d7467e642", + "96 frame b96 t17 bt4107 m02 macro_go_out p0 f152704b374b54d2", + "97 frame b97 t17 bt4124 m08 macro_go_out p0 db6caba8900aa0f8", + "98 frame b98 t16 bt4140 m08 macro_go_out p0 750ec56c0611e86d", + "99 frame b99 t17 bt4157 m08 macro_go_out p0 20ed8618ae84ea7b", + "100 frame b100 t17 bt4174 m08 macro_go_out p0 9f3c88a1d3080276", + "101 frame b101 t17 bt4191 m08 macro_go_out p0 37f0f8de463d1ea4", + "102 frame b102 t16 bt4207 m08 macro_go_out p120 c637dc590b738a73", + "103 frame b103 t17 bt4224 m08 macro_go_out p103 acd289090f10e216", + "104 frame b104 t17 bt4241 m08 macro_go_out p86 27ff70ebeb16accd", + "105 frame b105 t16 bt4257 m08 macro_go_out p70 f6391347be381599", + "106 frame b106 t17 bt4274 m08 macro_go_out p53 dce3a6ea9772cad6", + "107 frame b107 t17 bt4291 m08 macro_go_out p36 e0c159d74b32179e", + "108 frame b108 t17 bt4308 m08 macro_go_out p19 59f328f318d4159c", + "109 frame b109 t16 bt4324 m08 macro_go_out p3 8183d6905016268b", + "110 frame b110 t17 bt4341 m08 macro_go_out p0 2e4f1cae9730fd38", + "111 frame b111 t17 bt4358 m08 macro_go_out p0 93374d1d064911e7", + "112 frame b112 t17 bt4375 m08 macro_go_out p0 3970042f6f7aeada", + "113 frame b113 t16 bt4391 m08 macro_go_out p0 453c35f7fe1df367", + "114 frame b114 t17 bt4408 m08 macro_go_out p0 84122d1a4bb5d5e4", + "115 frame b115 t17 bt4425 m08 macro_go_out p0 01155fce277003d9", + "116 frame b116 t17 bt4442 m08 macro_go_out p0 b7b1aa630e0d7422", + "117 frame b117 t16 bt4458 m28 macro_go_out p0 36283b05d8e8d580", + "118 frame b118 t17 bt4475 m28 macro_go_out p0 717afeaef5a9d808", + "119 frame b119 t17 bt4492 m38 macro_go_out p120 e3e15c15455f12ef", + "120 frame b120 t17 bt4509 m38 macro_go_out p103 25384a06ed1ab907 state", + "121 rollback b120 t0 bt4509 m-- - p103 f04a32eda0fc7403", + "122 frame b121 t16 bt4525 m08 macro_go_out p87 d07e3db7b97d3c37", + "123 frame b122 t17 bt4542 m08 macro_go_out p70 de23a79c7027df50", + "124 frame b123 t17 bt4559 m08 macro_go_out p53 f9e8c1261be94efb", + "125 frame b124 t17 bt4576 m08 macro_go_out p36 d0f1d3a30b26834b", + "126 frame b125 t16 bt4592 m08 macro_go_out p20 07a54c7f905d51b7", + "127 frame b126 t17 bt4609 m08 macro_go_out p3 4f86202774d47232", + "128 frame b127 t17 bt4626 m08 macro_go_out p0 f81252ea7dfd5cd6", + "129 frame b128 t17 bt4643 m08 macro_go_out p0 c655922ec21d8af7", + "130 frame b129 t16 bt4659 m08 macro_go_out p0 00113d916da36b19", + "131 frame b130 t17 bt4676 m08 macro_go_out p0 b29c32b34131610a", + "132 frame b131 t17 bt4693 m08 - p0 03c2ac6516de6340", + "133 frame b132 t17 bt4710 m08 - p0 0f317ebc1c7b2dfd", + "134 frame b133 t16 bt4726 m08 - p0 82c898d80cef5165", + "135 frame b134 t17 bt4743 m08 - p0 e1f447fe884f0035", + "136 frame b135 t17 bt4760 m08 - p0 03cce25fe0406708", + "137 frame b136 t17 bt4777 m08 - p120 30ab44aeb9ac184a", + "138 frame b137 t16 bt4793 m08 - p104 ecaf6653c64f1604", + "139 frame b138 t17 bt4810 m08 - p87 b660e701b0879c98", + "140 frame b139 t17 bt4827 m08 - p70 5371979c169470f3", + "141 frame b140 t16 bt4843 m08 - p54 5445a7a361444935", + "142 frame b141 t17 bt4860 m08 - p37 057f91929f6d91b4", + "143 frame b142 t17 bt4877 m08 - p20 46c238c00d482155", + "144 frame b143 t17 bt4894 m08 - p3 f0584e9063d8fc90", + "145 frame b144 t16 bt4910 m08 - p0 0b4ddd703fcf5a54", + "146 frame b145 t17 bt4927 m08 - p0 dbd0b0a86b336bfa", + "147 frame b146 t17 bt4944 m08 - p0 2e8c45f2c2c49320", + "148 frame b147 t17 bt4961 m08 - p0 63d766cee52d420c", + "149 frame b148 t16 bt4977 m08 - p0 ce85563509e81dd3", + "150 frame b149 t17 bt4994 m38 - p0 5a5ed80dd7cdd643", + "151 frame b150 t17 bt5011 m38 - p0 2c2fe0f7265f9558", + "152 frame b151 t17 bt5028 m38 - p0 a3b63cdb6fd5cdb4", + "153 frame b152 t16 bt5044 m38 - p0 3f61ef5c3aa330bb", + "154 frame b153 t17 bt5061 m38 - p120 25a4fe291121ee26", + "155 frame b154 t17 bt5078 m38 - p103 543b851caad059e1", + "156 frame b155 t17 bt5095 m08 - p86 65aa23cddd7cb9e4", + "157 frame b156 t16 bt5111 m08 - p70 51ea9900cc7266c5", + "158 frame b157 t17 bt5128 m08 - p53 5e11712fb96da006", + "159 frame b158 t17 bt5145 m08 - p36 7051c00f84b30f6b", + "160 frame b159 t17 bt5162 m08 - p19 a68b2bc24c5348ab state", + "161 frame b160 t16 bt5178 m08 - p3 0ae35caf8548b14c", + "162 frame b161 t17 bt5195 m08 - p0 1d1a3536795012c9", + "163 frame b162 t17 bt5212 m08 - p0 fdd488a6cd816ee8", + "164 frame b163 t17 bt5229 m08 - p0 847aaf2c8540f821", + "165 frame b164 t16 bt5245 m08 - p0 4d0cf08f6ad85698", + "166 frame b165 t17 bt5262 m08 - p0 fd181536e34fc9d2", + "167 frame b166 t17 bt5279 m08 - p0 4e92f250e74a306a", + "168 frame b167 t17 bt5296 m08 - p0 35d5376db498ad57", + "169 frame b168 t16 bt5312 m08 - p0 c7584d3a45a5e773", + "170 frame b169 t17 bt5329 m04 macro_talk p0 b095f08524a7fb63", + "171 frame b170 t17 bt5346 m04 macro_talk p483 0ad3bf47cf3a9a9d", + "172 frame b171 t17 bt5363 m04 macro_talk p466 38257a6752c8e9ce", + "173 frame b172 t16 bt5379 m04 macro_talk p450 b09ba9a0d5ea49f3", + "174 frame b173 t17 bt5396 m04 macro_talk p433 1ac57d8b95f38072", + "175 frame b174 t17 bt5413 m04 macro_talk p416 123bc0e305bc3745", + "176 frame b175 t16 bt5429 m04 macro_talk p400 5305ecb6f1b5e620", + "177 frame b176 t17 bt5446 m04 macro_talk p383 e495eb473a3a2803", + "178 frame b177 t17 bt5463 m04 macro_talk p366 7e018a67f3b3eb57", + "179 frame b178 t17 bt5480 m34 macro_talk p349 bcd058f091970946", + "180 frame b179 t16 bt5496 m34 macro_talk p333 25b9e2c4cd50a5fa", + "181 frame b180 t17 bt5513 m34 macro_talk p316 1512b0fb16669893", + "182 frame b181 t17 bt5530 m34 macro_talk p299 3e808e0829436112", + "183 frame b182 t17 bt5547 m34 macro_talk p282 94e9a537eaf6f5d0", + "184 frame b183 t16 bt5563 m34 macro_talk p266 bd54d070787ccd2a", + "185 frame b184 t17 bt5580 m04 macro_talk p249 1c1cd476fca4e267", + "186 frame b185 t17 bt5597 m04 macro_talk p232 9907b3274367cbf5", + "187 frame b186 t17 bt5614 m04 macro_talk p215 38e5f8b325bb16b1", + "188 frame b187 t16 bt5630 m04 macro_talk p199 fb3d645fdde535a1", + "189 frame b188 t17 bt5647 m04 macro_talk p182 7d641ad4221b0747", + "190 frame b189 t17 bt5664 m04 macro_talk p165 8856a5a3a7ea0bd0", + "191 frame b190 t17 bt5681 m04 macro_talk p148 8729465d0c93729d", + "192 restore b190 t0 bt5681 m-- - p- 3750266f1bed5a99 state", + "193 frame b191 t16 bt5697 m04 macro_talk p132 45792c108b658d08", + "194 frame b192 t17 bt5714 m04 macro_talk p115 2e86ee32ef98edcb", + "195 frame b193 t17 bt5731 m04 macro_talk p98 70133bde0d47d8ac", + "196 frame b194 t17 bt5748 m04 macro_talk p81 14aee6172d1e8f12", + "197 frame b195 t16 bt5764 m04 macro_talk p65 760f253d0b98cffc", + "198 frame b196 t17 bt5781 m04 macro_talk p48 dc2fcd053a28f245", + "199 frame b197 t17 bt5798 m04 macro_talk p31 1838d2ac9c5a10b1", + "200 frame b198 t17 bt5815 m04 macro_talk p14 723b794e9dfb5c47 state", + "201 frame b199 t16 bt5831 m04 macro_talk p0 51ddb25342248c72", + "202 frame b200 t17 bt5848 m04 macro_talk p0 3f4b549fcfd40302", + "203 frame b201 t17 bt5865 m04 - p0 1ab673841a089025", + "204 frame b202 t17 bt5882 m04 - p0 9146ba27774f5937", + "205 frame b203 t16 bt5898 m04 - p0 d1c891868e0c48b4", + "206 frame b204 t17 bt5915 m04 - p120 1aa382cede74d36a", + "207 frame b205 t17 bt5932 m04 - p103 692f94397750c3b6", + "208 frame b206 t16 bt5948 m04 - p87 5d9ac6f1fa771385", + "209 frame b207 t17 bt5965 m34 - p70 0e96c0743aec05c7", + "210 frame b208 t17 bt5982 m34 - p53 d91b236ebe272fa3", + "211 frame b209 t17 bt5999 m34 - p36 4ad5374d47cdcdae", + "212 frame b210 t16 bt6015 m34 - p20 b37529a0105ba2c0", + "213 frame b211 t17 bt6032 m34 - p3 504d9d86dae0cb35", + "214 frame b212 t17 bt6049 m34 - p0 886a90e8c0b58461", + "215 frame b213 t17 bt6066 m04 - p0 9cc25421d7118f7f", + "216 frame b214 t16 bt6082 m04 - p0 b44009171671ff67", + "217 frame b215 t17 bt6099 m04 - p0 20c0af1b486dcce7", + "218 frame b216 t17 bt6116 m04 - p0 5f62d7ce7aaf7cba", + "219 frame b217 t17 bt6133 m02 macro_menu p0 3479097cfe92a45e", + "220 frame b218 t16 bt6149 m02 macro_menu p0 58da0f5bf3e746bc", + "221 frame b219 t17 bt6166 m02 macro_menu p0 c727e2ee2f68ab43", + "222 frame b220 t17 bt6183 m02 macro_menu p0 3cd2936775dfaa42", + "223 frame b221 t17 bt6200 m02 macro_menu p120 1618166702443d2a", + "224 frame b222 t16 bt6216 m02 macro_menu p104 cac3e979b5094f7e", + "225 frame b223 t17 bt6233 m02 macro_menu p87 6bc80216cd9307d0", + "226 frame b224 t17 bt6250 m02 macro_menu p70 158808c3270826e2", + "227 frame b225 t17 bt6267 m02 macro_menu p53 e864eee9eaed3100", + "228 frame b226 t16 bt6283 m02 macro_menu p37 2f4831892562df6c", + "229 frame b227 t17 bt6300 m02 macro_menu p20 f94333f42fb868e5", + "230 frame b228 t17 bt6317 m02 macro_menu p3 62b950c98af5ea1e", + "231 frame b229 t17 bt6334 m02 macro_menu p0 3995bffa513087f5", + "232 frame b230 t16 bt6350 m02 macro_menu p0 83ed01c9a19409db", + "233 frame b231 t17 bt6367 m02 macro_menu p0 7cad1b56d3abcd86", + "234 frame b232 t17 bt6384 m02 macro_menu p0 1e4f6b123bf7b16b", + "235 frame b233 t17 bt6401 m02 macro_menu p0 961794680cc8d12e", + "236 frame b234 t16 bt6417 m02 macro_menu p0 4452a80712b7eef8", + "237 frame b235 t17 bt6434 m02 macro_menu p0 5dde31f090f929dd", + "238 frame b236 t17 bt6451 m32 macro_menu p0 10016921e0075703", + "239 frame b237 t17 bt6468 m32 macro_menu p0 3c71e55a03bcff56", + "240 frame b238 t16 bt6484 m32 macro_menu p120 65651f499c0f50a0 state", + "241 frame b239 t17 bt6501 m32 macro_menu p103 d2d653c50d3d61ab", + "242 frame b240 t17 bt6518 m72 macro_menu p86 e0eb01fdec42ae6b", + "243 frame b241 t16 bt6534 m72 macro_menu p70 819891d76b93ffb3", + "244 frame b242 t17 bt6551 m42 macro_menu p53 48e684dbcaa34252", + "245 frame b243 t17 bt6568 m42 macro_menu p36 6b5f7974c612b7a3", + "246 frame b244 t17 bt6585 m02 macro_menu p19 66184ee2c6b219d1", + "247 frame b245 t16 bt6601 m02 macro_menu p3 d2b0395a6f2d92ed", + "248 frame b246 t17 bt6618 m02 macro_menu p0 202c87574e9d0ebc", + "249 frame b247 t17 bt6635 m02 macro_menu p0 c021f470cca581d9", + "250 frame b248 t17 bt6652 m02 macro_menu p0 590e9ba836d9b1c8", + "251 frame b249 t16 bt6668 m02 macro_menu p0 5da2d0bac5889de6", + "252 frame b250 t17 bt6685 m02 macro_menu p0 b294d92e2460443b", + "253 frame b251 t17 bt6702 m02 macro_menu p0 6af20af6bb0d75c8", + "254 frame b252 t17 bt6719 m02 macro_menu p0 ee5b8463e04ddfaa", + "255 frame b253 t16 bt6735 m02 macro_menu p0 33ad8e7c4a740c20", + "256 frame b254 t17 bt6752 m02 macro_menu p0 2c8afafa80388840", + "257 frame b255 t17 bt6769 m02 macro_menu p120 e78d398f5e177908", + "258 frame b256 t17 bt6786 m02 macro_menu p103 a2bad8c1a35197c9", + "259 frame b257 t16 bt6802 m02 macro_menu p87 476decc6c7fdb03c", + "260 frame b258 t17 bt6819 m02 macro_menu p70 fb61281ced140083", + "261 frame b259 t17 bt6836 m02 macro_menu p53 eb14e0e8da15899c", + "262 frame b260 t17 bt6853 m02 macro_menu p36 92132643c2593be7 state" + ] +} diff --git a/services/flysim/crates/fly-session/fixtures/toy-raw.golden.json b/services/flysim/crates/fly-session/fixtures/toy-raw.golden.json new file mode 100644 index 0000000..b8c4ade --- /dev/null +++ b/services/flysim/crates/fly-session/fixtures/toy-raw.golden.json @@ -0,0 +1,90 @@ +{ + "scenario": "toy-raw", + "macroChannels": [], + "records": 82, + "digest": "b732f959c51784f833c8ce413f896845dd706d9f2b8a87871fc3fdf4b305bcfe", + "rows": [ + "0 initialize b0 t2500 bt2500 m-- - p0 d676a54ce95aef0e", + "1 frame b1 t16 bt2516 m61 - p0 4faf42ac1ad6bcb9", + "2 frame b2 t17 bt2533 m71 - p0 8486caa267aec201", + "3 frame b3 t17 bt2550 m71 - p0 b0d966a6997b1c97", + "4 frame b4 t16 bt2566 m71 - p0 64327c9a3acaab25", + "5 frame b5 t17 bt2583 m31 - p0 3798452f3ebb8d14", + "6 frame b6 t17 bt2600 m31 - p0 179c8090e3478edf", + "7 frame b7 t17 bt2617 m11 - p0 764ac5a70eaa61d5", + "8 frame b8 t16 bt2633 m01 - p0 4eebfeadc843551c", + "9 frame b9 t17 bt2650 m01 - p0 3a4d8b850a579039", + "10 frame b10 t17 bt2667 m01 - p233 2e0f5a9335fabcc1", + "11 frame b11 t17 bt2684 m01 - p216 463c0780050cad58", + "12 frame b12 t16 bt2700 m01 - p200 3cd1021570919827", + "13 frame b13 t17 bt2717 m01 - p183 1d94880645b962aa", + "14 frame b14 t17 bt2734 m01 - p166 46fe4904b3422551", + "15 frame b15 t17 bt2751 m01 - p149 fce03793e22fb350", + "16 frame b16 t16 bt2767 m01 - p133 e31bc8f885260567", + "17 frame b17 t17 bt2784 m01 - p116 fa18c9ba0836e754", + "18 frame b18 t17 bt2801 m01 - p99 1599f79d81c26afb", + "19 frame b19 t17 bt2818 m01 - p82 118a390d17e1bd1c", + "20 frame b20 t16 bt2834 m01 - p66 9ec9aa11d1798516", + "21 frame b21 t17 bt2851 m01 - p49 b204db618f624d2c", + "22 frame b22 t17 bt2868 m01 - p32 a23457482b2939ef", + "23 frame b23 t17 bt2885 m01 - p15 a8c14ddada3e932e", + "24 frame b24 t16 bt2901 m01 - p0 ba33d0462ebddaf1", + "25 frame b25 t17 bt2918 m01 - p0 67cc2d1bd2b9bb9b", + "26 frame b26 t17 bt2935 m01 - p120 14a2110ff7cab560", + "27 frame b27 t17 bt2952 m01 - p103 05a3fedc4ee71492", + "28 frame b28 t16 bt2968 m01 - p87 5f56e91792a8cde7", + "29 frame b29 t17 bt2985 m01 - p70 8c4a2900dd3c57a9", + "30 frame b30 t17 bt3002 m21 - p53 0a10535b52bfd50f state", + "31 frame b31 t17 bt3019 m31 - p36 719b19d5d7d38811", + "32 frame b32 t16 bt3035 m31 - p20 016145fcf339c081", + "33 frame b33 t17 bt3052 m31 - p3 3aaf41e08109ca4b", + "34 frame b34 t17 bt3069 m31 - p0 a8234c793afb94c9", + "35 frame b35 t16 bt3085 m31 - p0 58327823fc61314a", + "36 frame b36 t17 bt3102 m11 - p0 bcf2610c93f2ccbc", + "37 frame b37 t17 bt3119 m01 - p0 e1595a5774be4e17", + "38 frame b38 t17 bt3136 m01 - p0 16b1e96a6229a022", + "39 frame b39 t16 bt3152 m01 - p120 4a36e5436f44c5f5", + "40 frame b40 t17 bt3169 m01 - p103 1f3d420fa5f95980", + "41 frame b41 t17 bt3186 m01 - p86 b548ce6125948fa3", + "42 frame b42 t17 bt3203 m01 - p69 7750b42e6bad3b0e", + "43 frame b43 t16 bt3219 m01 - p53 05a53fc43e61453b", + "44 frame b44 t17 bt3236 m01 - p36 8a69135634af3790", + "45 frame b45 t17 bt3253 m01 - p19 eb08c832eae97b32", + "46 frame b46 t17 bt3270 m01 - p2 e6be429be207a75a", + "47 frame b47 t16 bt3286 m01 - p0 563592a0452cb518", + "48 frame b48 t17 bt3303 m01 - p0 ed298d7a151a5576", + "49 frame b49 t17 bt3320 m02 - p0 345c64ffddd498d7", + "50 frame b50 t17 bt3337 m02 - p0 f6b66191b92e78a6", + "51 frame b51 t16 bt3353 m02 - p0 5636f8375e2bd7af", + "52 frame b52 t17 bt3370 m02 - p120 a8379efb27af6c0b", + "53 frame b53 t17 bt3387 m02 - p103 a3ea7fd0062ef0f7", + "54 frame b54 t17 bt3404 m02 - p86 409e243195a1f031", + "55 frame b55 t16 bt3420 m02 - p70 18e41167f8ee76b5", + "56 frame b56 t17 bt3437 m02 - p53 2452a659ce895028", + "57 frame b57 t17 bt3454 m02 - p36 aea6a3b31521a657", + "58 frame b58 t17 bt3471 m02 - p19 abb6c797c4179f73", + "59 frame b59 t16 bt3487 m22 - p3 7f8278ec59a44a45", + "60 frame b60 t17 bt3504 m32 - p0 79f6fa3a61d3852c", + "61 rollback b60 t0 bt3504 m-- - p0 3a769108c95f6734", + "62 frame b61 t17 bt3521 m01 - p0 2d9f2dc819137ea8", + "63 frame b62 t17 bt3538 m01 - p0 4351b16cfffe379d", + "64 frame b63 t16 bt3554 m01 - p0 39286c3fcd1e0dfb", + "65 frame b64 t17 bt3571 m01 - p0 3c935521f3e6f9c1", + "66 frame b65 t17 bt3588 m01 - p120 fde92192bd9c3827", + "67 frame b66 t17 bt3605 m01 - p103 fe7a4a2e4bc2caea", + "68 frame b67 t16 bt3621 m01 - p87 a1e2ee1ff05cf73c", + "69 frame b68 t17 bt3638 m01 - p70 d676cc814f51c4e5", + "70 frame b69 t17 bt3655 m01 - p53 57e50efd3f7c7ece", + "71 frame b70 t16 bt3671 m01 - p37 2d286c3b9c9bdad5", + "72 frame b71 t17 bt3688 m01 - p20 3bdaad14aeafd436", + "73 frame b72 t17 bt3705 m01 - p3 d24ecab576a63abd", + "74 frame b73 t17 bt3722 m01 - p0 92344f9026ff8e6a", + "75 frame b74 t16 bt3738 m01 - p0 67296ab770e3083a", + "76 frame b75 t17 bt3755 m01 - p0 07a568151228ddd8", + "77 frame b76 t17 bt3772 m01 - p0 62d33c55f40ef71f", + "78 frame b77 t17 bt3789 m01 - p0 506824f70aec7fd2", + "79 frame b78 t16 bt3805 m01 - p120 b594e6a96e31d900", + "80 frame b79 t17 bt3822 m01 - p103 b11dd400cc4d2499", + "81 frame b80 t17 bt3839 m01 - p86 edab6faae36ee227 state" + ] +} diff --git a/services/flysim/crates/fly-session/tests/legacy_agent.rs b/services/flysim/crates/fly-session/tests/legacy_agent.rs new file mode 100644 index 0000000..54265ee --- /dev/null +++ b/services/flysim/crates/fly-session/tests/legacy_agent.rs @@ -0,0 +1,587 @@ +//! AGENT-01: the legacy agent worker against the neural core driven directly, on the committed +//! toy connectome, under the launcher in every execution mode. +//! +//! `FLY_UPDATE_FIXTURES=1` rewrites the toy dataset and the goldens; otherwise the committed +//! files must be exactly what this build computes. + +use std::sync::Arc; + +use fly_session::ExecutionMode; +use fly_session::legacy_agent::{LegacyProfileKind, TOY_FINGERPRINT}; +use fly_session::legacy_parity::{ + self, DirectSource, LegacyRig, LegacyScript, ParityRecord, ReferenceSource, RigAgent, toy, +}; +use fly_session::types::id; +use flybrain_core::dataset::load_brain_dataset_from_dir; +use serde_json::Value; + +fn updating() -> bool { + std::env::var_os("FLY_UPDATE_FIXTURES").is_some() +} + +fn toy_agent(agent_id: &str, script: &LegacyScript) -> RigAgent { + RigAgent { + agent_id: id(agent_id), + port_id: id("p1"), + dataset_dir: toy::dir(), + profile: LegacyProfileKind::Toy, + macro_channels: script.macro_channels.clone(), + worker_threads: 1, + } +} + +fn reference(script: &LegacyScript) -> Vec { + let dataset = Arc::new(load_brain_dataset_from_dir(toy::dir()).expect("the toy dataset loads")); + DirectSource { dataset } + .records(script) + .expect("the reference runs") +} + +async fn on_worker(mode: ExecutionMode, script: &LegacyScript) -> Vec { + let root = tempfile::tempdir().expect("a temporary directory"); + let mut rig = LegacyRig::start(root.path(), mode, &[toy_agent("fly-a", script)]) + .await + .expect("the rig starts"); + let records = legacy_parity::run_on_worker(&mut rig, &id("fly-a"), script) + .await + .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + rig.stop().await; + records +} + +fn golden(script: &LegacyScript, records: &[ParityRecord]) { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join(format!("{}.golden.json", script.name)); + let mut text = + serde_json::to_string_pretty(&legacy_parity::golden_json(script, records)).expect("json"); + text.push('\n'); + if updating() { + std::fs::write(&path, &text).expect("write the golden"); + } + let found = std::fs::read_to_string(&path).expect("the committed golden"); + if found != text { + let want: Value = serde_json::from_str(&found).expect("golden json"); + let got: Value = serde_json::from_str(&text).expect("json"); + let rows = |v: &Value| -> Vec { + v["rows"] + .as_array() + .map(|a| { + a.iter() + .map(|r| r.as_str().unwrap_or("").to_owned()) + .collect() + }) + .unwrap_or_default() + }; + let first = rows(&want) + .into_iter() + .zip(rows(&got)) + .find(|(a, b)| a != b); + panic!( + "{} is stale (first differing row: {first:?}); rerun with FLY_UPDATE_FIXTURES=1", + path.display() + ); + } +} + +#[test] +fn the_committed_toy_dataset_is_what_the_generator_writes() { + let dir = toy::dir(); + if updating() { + toy::write(&dir).expect("write the toy dataset"); + } + for (name, bytes) in toy::files() { + let found = std::fs::read(dir.join(&name)).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!( + found, bytes, + "{name} is stale; rerun with FLY_UPDATE_FIXTURES=1" + ); + } + let dataset = load_brain_dataset_from_dir(&dir).expect("the toy dataset loads"); + assert_eq!( + dataset.fingerprint.as_deref(), + Some(TOY_FINGERPRINT), + "the toy profile embeds it" + ); +} + +/// The macros-mode scenario, in all three execution modes, against the direct reference and +/// the committed golden. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_macros_scenario_matches_the_reference_in_every_mode() { + let script = legacy_parity::toy_macros_script(260); + let want = reference(&script); + golden(&script, &want); + for mode in ExecutionMode::all() { + let got = on_worker(mode, &script).await; + legacy_parity::compare(&want, &got).unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + } +} + +/// Raw mode: no macro group, `bound` never masks, the decision never names a macro. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_raw_scenario_matches_the_reference_in_every_mode() { + let script = legacy_parity::toy_raw_script(80); + let want = reference(&script); + golden(&script, &want); + assert!(want.iter().all(|r| { + r.decision + .as_ref() + .is_none_or(|d| d.macro_channel.is_none()) + })); + for mode in ExecutionMode::all() { + let got = on_worker(mode, &script).await; + legacy_parity::compare(&want, &got).unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + } +} + +/// A second fly's script: the same shape, other frames and no rewards, so any gain, trace, RNG +/// or hold shared between the two would show in one of them. +fn quiet_twin(script: &LegacyScript) -> LegacyScript { + let mut twin = script.clone(); + twin.name = format!("{}-twin", script.name); + for step in &mut twin.steps { + if let legacy_parity::ScriptStep::Frame { + frame, + rewards, + sugar, + .. + } = step + { + *frame = (*frame + 3) % 8; + rewards.clear(); + sugar.clear(); + } + } + twin +} + +async fn step_one( + driver: &mut legacy_parity::AgentDriver, + index: usize, + step: &legacy_parity::ScriptStep, +) -> ParityRecord { + match step { + legacy_parity::ScriptStep::Frame { + sugar, + frame, + rewards, + next_context, + } => driver + .frame(index + 1, sugar, *frame, rewards, next_context) + .await + .expect("a frame"), + legacy_parity::ScriptStep::Rollback { frame, context } => driver + .rollback(index + 1, *frame, context) + .await + .expect("a rollback"), + legacy_parity::ScriptStep::Restore => unreachable!("the pair scripts do not restore"), + } +} + +/// Two flies in one composition, dispatched concurrently and then in reversed order, one of +/// them sweeping on two threads: each is exactly its own solo reference. No gains, RNG, holds +/// or pulse cross between agents, and neither dispatch order nor worker count moves a result. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn two_agents_share_nothing_whatever_the_dispatch_order_or_thread_count() { + let a_script = legacy_parity::toy_raw_script(60); + let b_script = quiet_twin(&a_script); + let a_want = reference(&a_script); + let b_want = reference(&b_script); + assert_ne!(a_want, b_want); + for (mode, reversed) in [ + (ExecutionMode::Thread, false), + (ExecutionMode::Process, true), + ] { + let root = tempfile::tempdir().expect("a temporary directory"); + let mut a_agent = toy_agent("fly-a", &a_script); + a_agent.worker_threads = 2; + let mut b_agent = toy_agent("fly-b", &b_script); + b_agent.port_id = id("p2"); + let rig = LegacyRig::start(root.path(), mode, &[a_agent, b_agent]) + .await + .expect("the rig starts"); + let mut a = rig.driver(&id("fly-a"), &a_script); + let mut b = rig.driver(&id("fly-b"), &b_script); + let mut a_got = vec![a.initialize(a_script.initial_frame).await.expect("a")]; + let mut b_got = vec![b.initialize(b_script.initial_frame).await.expect("b")]; + for index in 0..a_script.steps.len() { + let (ra, rb) = if reversed { + let rb = step_one(&mut b, index, &b_script.steps[index]).await; + let ra = step_one(&mut a, index, &a_script.steps[index]).await; + (ra, rb) + } else { + tokio::join!( + step_one(&mut a, index, &a_script.steps[index]), + step_one(&mut b, index, &b_script.steps[index]) + ) + }; + a_got.push(ra); + b_got.push(rb); + } + // Checkpoints are compared on the solo runs; here the per-step records are. + let strip = |records: &[ParityRecord]| -> Vec { + records + .iter() + .cloned() + .map(|mut r| { + r.state = None; + r + }) + .collect() + }; + legacy_parity::compare(&strip(&a_want), &a_got) + .unwrap_or_else(|e| panic!("{} fly-a: {e}", mode.label())); + legacy_parity::compare(&strip(&b_want), &b_got) + .unwrap_or_else(|e| panic!("{} fly-b: {e}", mode.label())); + rig.stop().await; + } +} + +mod refusals { + use super::*; + use fly_session::legacy_agent::LegacyAgentProfile; + use fly_session::types::*; + use fly_session_types::extensions::{ + AgentRollbackParams, ROLLBACK_CAPABILITY, ROLLBACK_POLICY, + }; + + fn code(reply: Result) -> ErrorCode { + match reply { + Err(e) => e.code, + Ok(reply) => match reply.result() { + Err(e) => e.code, + Ok(v) => panic!("expected a refusal, got {v}"), + }, + } + } + + async fn rig_with(root: &std::path::Path, agent: RigAgent) -> LegacyRig { + LegacyRig::start(root, ExecutionMode::InProcess, &[agent]) + .await + .expect("the rig starts") + } + + fn init_params( + driver: &legacy_parity::AgentDriver, + input: SensoryInput, + profile: AssetRef, + seed: i32, + ) -> serde_json::Value { + AgentInitializeParams { + agent_id: id("fly-a"), + profile, + seed, + initial_input: input, + initial_decision_context: driver.context().clone(), + worker_threads: 1, + } + .to_json() + } + + /// Initialize refuses another profile, a dataset that is not the profile's, a seed the + /// kernel version does not allow, and a context naming a channel the composition lacks. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn initialize_checks_the_profile_the_dataset_the_seed_and_the_context() { + let script = legacy_parity::toy_macros_script(4); + let root = tempfile::tempdir().expect("tmp"); + let rig = rig_with(root.path(), toy_agent("fly-a", &script)).await; + let mut driver = rig.driver(&id("fly-a"), &script); + let scope = driver.current_scope(); + let (input, frame) = driver.input(0, 0).await.expect("a frame"); + let production = LegacyAgentProfile::production().asset; + let params = init_params( + &driver, + input.clone(), + production, + legacy_parity::LEGACY_SEED, + ); + assert_eq!( + code( + driver + .call_raw( + "Agent.Initialize", + Some(scope.clone()), + params, + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::IdentityMismatch, + "another profile" + ); + let toy_profile = driver.profile().clone(); + let params = init_params(&driver, input.clone(), toy_profile.clone(), 7); + assert_eq!( + code( + driver + .call_raw( + "Agent.Initialize", + Some(scope.clone()), + params, + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::IncompatibleState, + "seed 7 would be another kernel version" + ); + let mut params = init_params( + &driver, + input.clone(), + toy_profile.clone(), + legacy_parity::LEGACY_SEED, + ); + let bad = fly_session_types::gameboy::ReadoutContext { + boot: true, + bound: vec!["macro_heal".to_owned()], + location: None, + }; + params["initialDecisionContext"] = bad.to_typed().to_json(); + assert_eq!( + code( + driver + .call_raw( + "Agent.Initialize", + Some(scope.clone()), + params, + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::InvalidArgument, + "a bound channel outside the composition" + ); + // Every refusal above was made before a model existed: the worker still initializes. + driver + .initialize(0) + .await + .expect("the worker is still uninitialized and accepts a good request"); + rig.stop().await; + + // A worker configured for the production profile, pointed at the toy connectome. + let root = tempfile::tempdir().expect("tmp"); + let mut agent = toy_agent("fly-a", &script); + agent.profile = LegacyProfileKind::Production; + let rig = rig_with(root.path(), agent).await; + let mut driver = rig.driver(&id("fly-a"), &script); + let (input, frame) = driver.input(0, 0).await.expect("a frame"); + let params = init_params( + &driver, + input, + LegacyAgentProfile::production().asset, + legacy_parity::LEGACY_SEED, + ); + let scope = driver.current_scope(); + assert_eq!( + code( + driver + .call_raw( + "Agent.Initialize", + Some(scope), + params, + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::IdentityMismatch, + "the toy connectome is not the dataset the production profile embeds" + ); + rig.stop().await; + } + + /// Prepare refuses another cadence and an undeclared stimulus kind; a retried Prepare + /// replays its decision without ticking again; Rollback refuses the wrong epochs and a + /// prepared agent; StageRestore refuses another fly's compatibility. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn step_rollback_and_restore_refuse_what_they_must() { + let script = legacy_parity::toy_macros_script(4); + let root = tempfile::tempdir().expect("tmp"); + let rig = rig_with(root.path(), toy_agent("fly-a", &script)).await; + let mut driver = rig.driver(&id("fly-a"), &script); + let hello = HelloParams { + session_id: id("legacy"), + expected_worker_id: id("fly-a"), + role: Role::Agent, + supported_majors: vec![1], + }; + let hello: HelloResult = driver + .call_raw("Worker.Hello", None, hello.to_json(), &[]) + .await + .expect("hello") + .parse() + .expect("a hello result"); + assert!( + hello.capabilities.iter().any(|c| c == ROLLBACK_CAPABILITY), + "{:?}", + hello.capabilities + ); + driver.initialize(0).await.expect("initialize"); + let scope = driver.current_scope(); + let prepare = |interval: RationalNs, kind: &str| PrepareParams { + agent_id: id("fly-a"), + profile_digest: driver.profile().digest.clone(), + interval, + decision_context_digest: driver.context().digest(), + pre_step_stimulations: vec![Stimulus { + id: id("s1"), + kind_id: kind.to_owned(), + duration_ms: 50.0, + }], + }; + let sixty = hz(60).expect("60 Hz"); + let frame_interval = fly_session_types::gameboy::step_duration(); + let bad_cadence = prepare(sixty, "reward-pulse").to_json(); + let bad_kind = prepare(frame_interval, "arena.milestone").to_json(); + let good = prepare(frame_interval, "reward-pulse").to_json(); + assert_eq!( + code( + driver + .call_raw("Agent.Prepare", Some(scope.clone()), bad_cadence, &[]) + .await + ), + ErrorCode::InvalidArgument + ); + assert_eq!( + code( + driver + .call_raw("Agent.Prepare", Some(scope.clone()), bad_kind, &[]) + .await + ), + ErrorCode::Unsupported + ); + let first = driver + .call_raw("Agent.Prepare", Some(scope.clone()), good.clone(), &[]) + .await + .expect("prepare"); + let prepared: PreparedDecision = first.parse().expect("a decision"); + let again = driver + .retry_raw( + first.request_id.clone(), + "Agent.Prepare", + Some(scope.clone()), + good, + ) + .await + .expect("a replay"); + let replayed: PreparedDecision = again.parse().expect("the same decision"); + assert_eq!( + prepared, replayed, + "a duplicate Prepare returns the same decision" + ); + + // Rollback while Prepared. + let (input, frame) = driver.input(2, 0).await.expect("a frame"); + let rollback = |prior: &str| AgentRollbackParams { + agent_id: id("fly-a"), + prior_epoch: id(prior), + policy: ROLLBACK_POLICY.to_owned(), + input: input.clone(), + decision_context: driver.context().clone(), + }; + let next_epoch = scope_at("legacy", "e2", 0); + assert_eq!( + code( + driver + .call_raw( + "Agent.Rollback", + Some(next_epoch.clone()), + rollback("e1").to_json(), + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::InvalidPhase, + "a prepared agent is mid-transition" + ); + rig.stop().await; + + let root = tempfile::tempdir().expect("tmp"); + let mut rig = rig_with(root.path(), toy_agent("fly-a", &script)).await; + let mut driver = rig.driver(&id("fly-a"), &script); + driver.initialize(0).await.expect("initialize"); + let (input, frame) = driver.input(2, 0).await.expect("a frame"); + let context = driver.context().clone(); + let params = |prior: &str| { + AgentRollbackParams { + agent_id: id("fly-a"), + prior_epoch: id(prior), + policy: ROLLBACK_POLICY.to_owned(), + input: input.clone(), + decision_context: context.clone(), + } + .to_json() + }; + assert_eq!( + code( + driver + .call_raw( + "Agent.Rollback", + Some(scope_at("legacy", "e3", 0)), + params("e2"), + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::StaleEpoch, + "the prior epoch is not the one this worker is in" + ); + assert_eq!( + code( + driver + .call_raw( + "Agent.Rollback", + Some(scope_at("legacy", "e1", 0)), + params("e0"), + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::StaleEpoch, + "a rollback moves to a new epoch" + ); + let first = driver + .call_raw( + "Agent.Rollback", + Some(scope_at("legacy", "e2", 0)), + params("e1"), + &[("view.lcd", &frame)], + ) + .await + .expect("a rollback"); + first.result().expect("applied"); + let replay = driver + .retry_raw( + first.request_id.clone(), + "Agent.Rollback", + Some(scope_at("legacy", "e2", 0)), + params("e1"), + ) + .await + .expect("a replay of the same rollback"); + assert_eq!( + replay.result().expect("replayed"), + first.result().expect("applied"), + "a lost reply replays, it does not roll back twice" + ); + + // A capture restored with someone else's compatibility is refused before staging. + driver.bump_epoch(); + let captured = driver.capture().await.expect("capture"); + let target = rig.replace(&id("fly-a")).await.expect("a replacement"); + let mut forged = captured.result.clone(); + forged.compatibility_digest = digest_of_bytes(b"another fly"); + let forged = legacy_parity::Captured { + result: forged, + artifact: captured.artifact.clone(), + bytes: captured.bytes.clone(), + scope: captured.scope.clone(), + }; + let refused = driver + .restore_into(target, &forged) + .await + .expect_err("another fly's compatibility"); + assert!(refused.contains("IncompatibleState"), "{refused}"); + rig.stop().await; + } +} From 625bcb640345edb862280c6de9cdc1dc7f42732f Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 23 Sep 2026 14:53:33 +0000 Subject: [PATCH 06/26] tests: the toy rollback lands in a world that stands still past a blocked window --- .../crates/fly-session/fixtures/toy-macros.golden.json | 10 +++++----- .../flysim/crates/fly-session/src/legacy_parity.rs | 5 ++++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/services/flysim/crates/fly-session/fixtures/toy-macros.golden.json b/services/flysim/crates/fly-session/fixtures/toy-macros.golden.json index e71c761..ddb6a66 100644 --- a/services/flysim/crates/fly-session/fixtures/toy-macros.golden.json +++ b/services/flysim/crates/fly-session/fixtures/toy-macros.golden.json @@ -7,7 +7,7 @@ "macro_next" ], "records": 263, - "digest": "bae9357bb565266fdefba66004f792aa52a44e283fa73853e0c4f3de50790f86", + "digest": "5139fb8a99c6503ac2315f5a5ed754a6054e6eb8068acdd2b649931ccd40a02f", "rows": [ "0 initialize b0 t2500 bt2500 m-- - p0 d676a54ce95aef0e", "1 frame b1 t16 bt2516 m61 - p0 42a0dfdbf7fe8f55", @@ -201,7 +201,7 @@ "189 frame b188 t17 bt5647 m04 macro_talk p182 7d641ad4221b0747", "190 frame b189 t17 bt5664 m04 macro_talk p165 8856a5a3a7ea0bd0", "191 frame b190 t17 bt5681 m04 macro_talk p148 8729465d0c93729d", - "192 restore b190 t0 bt5681 m-- - p- 3750266f1bed5a99 state", + "192 restore b190 t0 bt5681 m-- - p- 8f949318d4bb63eb state", "193 frame b191 t16 bt5697 m04 macro_talk p132 45792c108b658d08", "194 frame b192 t17 bt5714 m04 macro_talk p115 2e86ee32ef98edcb", "195 frame b193 t17 bt5731 m04 macro_talk p98 70133bde0d47d8ac", @@ -209,7 +209,7 @@ "197 frame b195 t16 bt5764 m04 macro_talk p65 760f253d0b98cffc", "198 frame b196 t17 bt5781 m04 macro_talk p48 dc2fcd053a28f245", "199 frame b197 t17 bt5798 m04 macro_talk p31 1838d2ac9c5a10b1", - "200 frame b198 t17 bt5815 m04 macro_talk p14 723b794e9dfb5c47 state", + "200 frame b198 t17 bt5815 m04 macro_talk p14 c92a4879ba2b7755 state", "201 frame b199 t16 bt5831 m04 macro_talk p0 51ddb25342248c72", "202 frame b200 t17 bt5848 m04 macro_talk p0 3f4b549fcfd40302", "203 frame b201 t17 bt5865 m04 - p0 1ab673841a089025", @@ -249,7 +249,7 @@ "237 frame b235 t17 bt6434 m02 macro_menu p0 5dde31f090f929dd", "238 frame b236 t17 bt6451 m32 macro_menu p0 10016921e0075703", "239 frame b237 t17 bt6468 m32 macro_menu p0 3c71e55a03bcff56", - "240 frame b238 t16 bt6484 m32 macro_menu p120 65651f499c0f50a0 state", + "240 frame b238 t16 bt6484 m32 macro_menu p120 94bd075f6fa74a82 state", "241 frame b239 t17 bt6501 m32 macro_menu p103 d2d653c50d3d61ab", "242 frame b240 t17 bt6518 m72 macro_menu p86 e0eb01fdec42ae6b", "243 frame b241 t16 bt6534 m72 macro_menu p70 819891d76b93ffb3", @@ -271,6 +271,6 @@ "259 frame b257 t16 bt6802 m02 macro_menu p87 476decc6c7fdb03c", "260 frame b258 t17 bt6819 m02 macro_menu p70 fb61281ced140083", "261 frame b259 t17 bt6836 m02 macro_menu p53 eb14e0e8da15899c", - "262 frame b260 t17 bt6853 m02 macro_menu p36 92132643c2593be7 state" + "262 frame b260 t17 bt6853 m02 macro_menu p36 14a5132bd706cea1 state" ] } diff --git a/services/flysim/crates/fly-session/src/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs index 557e9d2..14953d4 100644 --- a/services/flysim/crates/fly-session/src/legacy_parity.rs +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -291,7 +291,8 @@ fn context(boot: bool, bound: &[&str], location: Option<(u32, u32, u32)>) -> Rea /// The macros-mode toy scenario: boot and play, a still location long enough for the blocked /// rule, a battle (no location), sugar overlapping a pulse, reward events on a schedule with a -/// zero-value one, a rollback, a restore into a fresh worker and play after both. +/// zero-value one, a rollback into a world that then stands still past a blocked window, a +/// restore into a fresh worker and play after both. pub fn toy_macros_script(frames: usize) -> LegacyScript { let channels: Vec = toy::MACRO_CHANNELS .iter() @@ -310,6 +311,8 @@ pub fn toy_macros_script(frames: usize) -> LegacyScript { 0..20 => None, 20..90 => Some((1, 5, 5)), 90..96 => None, + // The rollback's restored world, standing still past one blocked window. + 121..185 => Some((2, 3, 4)), _ => Some((1, 5 + (k / 30) as u32, 5)), } }; From 8f058a402b1e333933f7d5869cccafb92e7d995d Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 23 Sep 2026 15:01:43 +0000 Subject: [PATCH 07/26] tests: the gated FAFB run, recorded inputs through the worker against NeuralAgent driven directly --- .../crates/fly-session/tests/legacy_agent.rs | 136 ++++++++++++++++++ 1 file changed, 136 insertions(+) diff --git a/services/flysim/crates/fly-session/tests/legacy_agent.rs b/services/flysim/crates/fly-session/tests/legacy_agent.rs index 54265ee..285c1c6 100644 --- a/services/flysim/crates/fly-session/tests/legacy_agent.rs +++ b/services/flysim/crates/fly-session/tests/legacy_agent.rs @@ -585,3 +585,139 @@ mod refusals { rig.stop().await; } } + +/// The real dataset, an explicit job: `FLY_AGENT01_FAFB=1` with `data/fafb-v783` checked out. +/// Release mode is the sensible way to run it. +mod fafb { + use super::*; + use fly_session::legacy_parity::{RewardEvent, ScriptStep, fafb_dir, frame_pool}; + use fly_session_types::gameboy::{Location, ReadoutContext}; + + fn enabled() -> Option { + if std::env::var_os("FLY_AGENT01_FAFB").is_none() { + eprintln!("skipping: FLY_AGENT01_FAFB is not set"); + return None; + } + let dir = fafb_dir(); + if dir.is_none() { + eprintln!("skipping: data/fafb-v783 is not present in this checkout"); + } + dir + } + + fn pokered_channels() -> Vec { + let file = fly_session_types::fixtures::load("gameboy-decoder-config.json").expect("vectors"); + file["cases"][1]["macroChannels"] + .as_array() + .expect("the Pokemon Red macro group") + .iter() + .map(|c| c.as_str().expect("a channel").to_owned()) + .collect() + } + + /// The live macros-mode composition's shape on the real connectome, with recorded inputs. + fn script(frames: usize) -> LegacyScript { + let channels = pokered_channels(); + let bound = |k: usize| -> Vec { + let take: &[usize] = match k { + 0..20 => &[], + 20..50 => &[0, 1, 9], + _ => &[1, 4, 5, 6], + }; + take.iter().map(|i| channels[*i].clone()).collect() + }; + let mut steps = Vec::new(); + for k in 1..=frames { + steps.push(ScriptStep::Frame { + sugar: if k == 12 { vec![400.0] } else { vec![] }, + frame: k % 6, + rewards: if k % 11 == 0 { + vec![RewardEvent { value: 0.5, stimulation_ms: 120.0 }] + } else { + vec![] + }, + next_context: ReadoutContext { + boot: k < 10, + bound: bound(k), + location: (k > 5).then_some(Location { area: 12, x: 3 + (k / 40) as u32, y: 7 }), + }, + }); + if k == 60 { + steps.push(ScriptStep::Rollback { + frame: 2, + context: ReadoutContext { boot: false, bound: bound(k), location: None }, + }); + } + if k == 75 { + steps.push(ScriptStep::Restore); + } + } + let last = steps.len() - 1; + LegacyScript { + name: "fafb-macros".to_owned(), + macro_channels: channels, + frames: Arc::new(frame_pool(6, 783)), + initial_frame: 0, + initial_context: ReadoutContext { boot: true, bound: vec![], location: None }, + steps, + checkpoints: [30, last].into_iter().collect(), + } + } + + /// The tracked rate roles on the committed dataset are the fixture's list, and each is + /// published as itself (`legacy-rate-role-id-v1`). + #[test] + fn the_fafb_rate_roles_are_the_fixture_list() { + let Some(dir) = enabled() else { return }; + let dataset = Arc::new(load_brain_dataset_from_dir(&dir).expect("the dataset loads")); + let config = flybrain_core::agent::AgentConfig::with_decoder( + flybrain_core::decoder::gameboy::gameboy_decoder_config(), + ); + let agent = flybrain_core::agent::NeuralAgent::new(dataset, config).expect("the agent"); + let tracked: Vec = agent.network.rates.keys().cloned().collect(); + let file = fly_session_types::fixtures::load("gameboy-rate-roles.json").expect("fixture"); + let want: Vec = file["fafbTrackedRoles"] + .as_array() + .expect("list") + .iter() + .map(|v| v.as_str().expect("a name").to_owned()) + .collect(); + assert_eq!(tracked, want); + } + + /// Recorded inputs through the worker (in-process and as a process) against `NeuralAgent` + /// driven directly, on `gameboy-legacy-fafb-v783-v1` itself. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_fafb_scenario_matches_the_direct_reference() { + let Some(dir) = enabled() else { return }; + let script = script(90); + let started = std::time::Instant::now(); + let dataset = Arc::new(load_brain_dataset_from_dir(&dir).expect("the dataset loads")); + let want = DirectSource { dataset }.records(&script).expect("the reference runs"); + eprintln!("reference: {} records in {:?}", want.len(), started.elapsed()); + let summary = legacy_parity::golden_json(&script, &want); + eprintln!("reference digest {}", summary["digest"]); + for mode in [ExecutionMode::InProcess, ExecutionMode::Process] { + let started = std::time::Instant::now(); + let root = tempfile::tempdir().expect("tmp"); + let agent = RigAgent { + agent_id: id("fly-a"), + port_id: id("p1"), + dataset_dir: dir.clone(), + profile: LegacyProfileKind::Production, + macro_channels: script.macro_channels.clone(), + worker_threads: 1, + }; + let mut rig = LegacyRig::start(root.path(), mode, &[agent]).await.expect("the rig"); + let got = legacy_parity::run_on_worker(&mut rig, &id("fly-a"), &script) + .await + .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + rig.stop().await; + legacy_parity::compare(&want, &got).unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + eprintln!("{}: {} records identical in {:?}", mode.label(), got.len(), started.elapsed()); + } + for row in summary["rows"].as_array().expect("rows").iter().step_by(10) { + eprintln!(" {}", row.as_str().expect("a row")); + } + } +} From ae503aa7a0962472630016067d1ce7ac7506e233 Mon Sep 17 00:00:00 2001 From: acamilo Date: Wed, 23 Sep 2026 15:02:18 +0000 Subject: [PATCH 08/26] docs: legacy-gameboy-v1 amendments, the rate-role mapping and what the legacy agent reports --- .../session-framework/implementation.md | 11 +++ .../session-framework/legacy-gameboy-v1.md | 70 ++++++++++++++++++- 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index a11fa4c..8c00be1 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -176,6 +176,17 @@ window and last location as private readout state; report `stimulusRemainingMs`; legacy rate-role names (`command_0`, `macro_*`, which are not `Id`s) to `AgentGraph.rateRoles`, which that contract leaves open. +**2026-09-23 (AGENT-01 built, `feat/agent-legacy-worker`).** `LegacyAgentWorker` +(`fly-session/src/legacy_agent.rs`) serves the legacy profile under the launcher in all three +execution modes (`legacy-agent` subcommand). Its parity harness (`legacy_parity.rs`) drives +`NeuralAgent` directly in `Sim::step_frame` order from recorded inputs. On the committed toy +connectome, the worker's records match that reference exactly in every mode, including a +rollback and a restore, and are pinned as goldens. A gated FAFB run +(`FLY_AGENT01_FAFB=1`) shows the same on `gameboy-legacy-fafb-v783-v1`. The rate-role mapping +turned out to be the identity: the legacy names are already `Id`s. It is recorded in +[legacy-gameboy-v1](legacy-gameboy-v1.md) section 13, with the other agent-adapter choices. The +harness's `ReferenceSource` is the seam for FND-01's `FLY_TRACE`. + **Implement:** adapter over existing LIF, plasticity, retina and fixed readout primitives; reference-first composition/goldens; independently seeded agent state and shared immutable data. Avoid using the old whole-frame `tick` wrapper if it changes the specified phase ordering. diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 163934e..8061213 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -125,7 +125,8 @@ interface GameboyReadoutContext { ``` `ChannelName` is `^[a-z][a-z0-9_]{0,63}$`. Decoder channel and rate-role names carry `_`, so -they are not `Id`s. The context is what the task hands the decoder with each Prepare (the +they are not `Id`s (corrected 2026-09-23, AGENT-01: they are; see the section 13 amendment). +The context is what the task hands the decoder with each Prepare (the `initialDecisionContext`, then every `nextDecisionContext`). `bound` is an ordered subset of the composition's `macroChannels`. @@ -351,6 +352,73 @@ stale files. valid `Id`s, while `AgentGraph.rateRoles` and `AgentTelemetry.rates[].roleId` are `Id`s. The mapping belongs to the agent adapter. This contract does not choose it. +**Amendment, 2026-09-23 (AGENT-01): the rate-role mapping `legacy-rate-role-id-v1`.** The +premise above is wrong. The session `Id` grammar is `^[a-z0-9][a-z0-9._-]{0,63}$` +([session RPC](ipc-v1.md) section 1, `flybus::wire::is_id`, `isId` in `@flybrain/session-types`), +and it admits `_`. Every role `data/fafb-v783` declares, including the 31 `macro_*` populations +merged after the fingerprint, and every role the kernel tracks, is already an `Id`; so is every +`ChannelName`, whose grammar is a subset. The mapping is therefore the identity: + +- a legacy rate-role name `n` is published as `roleId = n` when `n` is an `Id`, and a `roleId` + names the rate role of the same spelling. The mapping is reversible by construction; +- a name that is not an `Id` has no `roleId`. The agent refuses to initialize over a dataset + that tracks one (`INCOMPATIBLE_STATE`), rather than invent an encoding no consumer could read + back. No shipped dataset has one; +- the published list keeps the kernel's tracked-role order and its bounds: at most 64 + (`MAX_RATE_ROLES`, the kernel's role bitmask) and unique. On `fafb-v783` it is 45 roles. + +`gameboy::rate_role_id`, `rate_role_name` and `rate_role_ids` in `fly-session-types`, and +`rateRoleId`, `rateRoleName` and `rateRoleIds` in `@flybrain/session-types`, implement it. +`fixtures/gameboy-rate-roles.json` holds both languages to the same accepted and refused names and +records the FAFB tracked list, which `fly-session`'s gated FAFB test recomputes from the +committed dataset. The mapping changes no schema, digest or fixture digest. + +**Amendment, 2026-09-23 (AGENT-01): what the legacy agent reports and captures.** These are +agent-adapter choices that the sections above leave open. `LegacyAgentWorker` +(`fly-session/src/legacy_agent.rs`) implements them: + +- *Seed.* The kernel version `lif-1ms-f64-v2` hashes the LIF seed. Every seed except the legacy + default `22222` gives a different kernel version, so the profile pins the seed. + `Agent.Initialize` refuses any other seed (`INCOMPATIBLE_STATE`) before it builds a model. The + coordinator of this composition passes `22222`. It does not use a seed derived under + [seed-derivation-v1](seed-derivation-v1.md). +- *Learning telemetry.* `AgentTelemetry.learning` requires `changed <= updates`. The legacy + counters mean something else, so they map as follows. `updates` is the number of reinforcement + calls the agent has applied: one per commit while the rule is enabled, zero sums included. + `changed` is the legacy `plasticity.updates`: the reinforcements that moved at least one gain. + `signal` is `plasticity.signal`. The legacy per-synapse count (`LearningStats.changed`, the + gains away from 1.0) is not carried. It can still be read from a captured state. + `stimulusRemainingMs` is the network's `reward_remaining` after the operation. +- *Spikes.* Each `Agent.Commit` reply carries the attachment `telemetry.spikes`, with content type + `application/x-fly-spike-bitset`. It uses the legacy feed's layout: bit *i* is neuron *i*, + `ceil(neurons/8)` bytes. It covers the transition's ticks: a neuron is set when its last spike + is at or after the brain time before that transition's Prepare ticked. The mapping of bit + *i* is the graph's `indexDigest`. +- *Graph.* `datasetDigest` is the SHA-256 of the schema-1 fingerprint string. `indexDigest` is the + SHA-256 of `fly-session/legacy-agent-index-v1`, the fingerprint, the neuron count and every + `macro_*` population's members. The macro populations are the profile's declared + `macro-roles-outside-fingerprint` exception. Two datasets that relabel them differently + therefore get the same fingerprint and different index digests. +- *Initialize.* The readout transient starts as it does in a fresh legacy process: no held + channel, no last location, and a blocked window from 0 ms. `initialDecisionContext.location` + is **not** taken as the last location. The legacy loop reads a location only at the end of a + frame, so the window first restarts on it at the first commit, as it does in the legacy loop. +- *Capture.* The `State.Capture` payload is a `flybrain-core` checkpoint envelope with magic + `FLYAGT01`. Its manifest and chunks are exactly `agent_to_chunks`, with the frame remainder + taken from the session accumulator, as `Sim::checkpoint` does. It adds one `session` member: the + accumulator, the context, the profile, the seed, the reinforcement count, the macro channels + and the decoder configuration digest. It does not carry the readout transient (section 14). It + is not FLYSIM01. Writing a FLYSIM01 export from it and from the environment's state is still + STATE-01/ENV-01 work (section 16). +- *Restore.* `State.StageRestore` builds a replacement network over the same dataset, imports + the state and refuses any mismatch between the state's clock and the accumulator. + `ActivateRestore` then installs the state and resets the readout transient, as a fresh legacy + process does. The visual drive is the restored `visualDrive` chunk. Legacy `try_restore` + instead re-projects the saved framebuffer, and the two are the same values (the parity + harness compares the full state after a restore). +- *Decision.* `macro` is the first channel in the context's `bound` order that the decode holds. + This is the channel the legacy macro layer's `asked` would start. + ## 14. Restore `legacy-transient-reset` The legacy composition declares that a restore (a FLYSIM01 load today, and any group restore From e28b0d89998f049f9bcd105b585038ea330ea2fb Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:16:22 +0000 Subject: [PATCH 09/26] fly-session: LegacyGameboyEnvironment, the ENV-01 Game Boy environment worker The emulator half of flysim's LegacyFrame behind the environment methods: the one-frame setup scaffold, one joypad batch per Advance, f32le audio (sample/255, unfiltered), the per-boundary memory image behind the MEM-01 seam (read between an export and an import, because emulator_read_mem syncs OAM/VRAM/timer/STAT/LY), gameboy-slots-v1 SaveSlot/RestoreSlot, capture and staged restore, and the world's half of FLYSIM01. SaveSlot, RestoreSlot and Agent.Rollback are step mutations under the ipc-v1 operation key. The parity harness (toy cartridge, direct reference in LegacyFrame order, bus driver, FLY_TRACE replay) is in legacy_env_parity. --- services/flysim/Cargo.lock | 2 + services/flysim/crates/fly-session/Cargo.toml | 5 + .../crates/fly-session/src/legacy_env.rs | 1627 +++++++++++++++++ .../fly-session/src/legacy_env_parity.rs | 1544 ++++++++++++++++ services/flysim/crates/fly-session/src/lib.rs | 2 + .../flysim/crates/fly-session/src/worker.rs | 7 + 6 files changed, 3187 insertions(+) create mode 100644 services/flysim/crates/fly-session/src/legacy_env.rs create mode 100644 services/flysim/crates/fly-session/src/legacy_env_parity.rs diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index 25f88d6..aa51bcd 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -440,6 +440,8 @@ name = "fly-session" version = "0.1.1" dependencies = [ "fly-session-types", + "flybrain-core", + "flybrain-gb", "flybus", "serde_json", "tempfile", diff --git a/services/flysim/crates/fly-session/Cargo.toml b/services/flysim/crates/fly-session/Cargo.toml index 25d9a76..579efc1 100644 --- a/services/flysim/crates/fly-session/Cargo.toml +++ b/services/flysim/crates/fly-session/Cargo.toml @@ -23,6 +23,11 @@ path = "src/bin/fly-session.rs" # Everything else this crate needs is std or Tokio. fly-session-types = { path = "../fly-session-types" } flybus = { path = "../flybus" } +# ENV-01: the legacy Game Boy environment worker drives the binjgb emulator through +# flybrain-gb's safe wrapper, and flybrain-core's frozen envelope layout reads and writes the +# world's half of a FLYSIM01 checkpoint. (AGENT-01 adds flybrain-core for the agent as well.) +flybrain-core = { path = "../flybrain-core" } +flybrain-gb = { path = "../flybrain-gb" } serde_json = { workspace = true } # `rt-multi-thread` is not only for the tests: a worker process and a dedicated-thread diff --git a/services/flysim/crates/fly-session/src/legacy_env.rs b/services/flysim/crates/fly-session/src/legacy_env.rs new file mode 100644 index 0000000..be49534 --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_env.rs @@ -0,0 +1,1627 @@ +//! ENV-01: the Game Boy compatibility environment worker of the legacy composition. +//! +//! `legacy-gameboy-v1` sections 7 to 9, 11, 14 and 16, and the RT-01a amendments to +//! `workers-v1` (sections 3 and 7), `step-v1` (section 6) and `state-media-v1` (sections 2 to 5). +//! It is the emulator half of flysim's `LegacyFrame`, moved behind the environment methods, and it +//! makes exactly the emulator calls `LegacyFrame` makes, in the same order: +//! +//! | `LegacyFrame` (flysim `frame.rs`) | this worker | +//! | --- | --- | +//! | `initialize`: `run_frame`, framebuffer, `take_audio_u8` (the counter becomes 1) | `Environment.Initialize`: the one-frame setup scaffold, no button down; O[0] with `engineFrame` "1", its audio discarded | +//! | `run` + `take_frame`: `set_buttons(mask)`, `run_frame`, framebuffer, `take_audio_u8` | `Environment.Advance`: the joypad mask of the one port, then O[k+1] with its f32 audio chunk | +//! | `boundary`'s capture: `export_state` + the frame on screen | `Environment.SaveSlot` (`gameboy-slots-v1`) | +//! | `rollback` via `recover_game`: `import_state`, `set_buttons(0)` twice, the slot's frame | `Environment.RestoreSlot` under a new epoch, no frame run | +//! | `restore` from FLYSIM01: `import_state`, `set_buttons(buttons)`, the saved framebuffer | `State.StageRestore` + `State.ActivateRestore` | +//! +//! What the worker adds is only what the contracts ask for and the legacy loop never needed: +//! native audio as `f32le` (`sample / 255`, no filtering: the DC blocker is the edge's), one +//! memory image per boundary as the `gameboy-memory-inspection-v1` inspection, the rational world +//! clock, epochs, batch identity and the capture payload. +//! +//! The joypad is the only write into a running game. `import_state` is a write only on the +//! declared recovery paths (a slot restore and a group restore), exactly as it is in flysim. +//! +//! The memory image is read through [`memory_image`], the one seam MEM-01 replaces with the shim's +//! bulk read. Until then its body is 65,536 `fly_gb_read_mem` calls through the existing +//! `read_uncached`, which is by definition the image `legacy-gameboy-v1` section 8 specifies. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; + +use fly_session_types::extensions::{ + MAX_SLOTS, METHOD_RESTORE_SLOT, METHOD_SAVE_SLOT, RestoreSlotParams, RestoreSlotResult, + SLOTS_CAPABILITY, SaveSlotParams, SaveSlotResult, +}; +use fly_session_types::gameboy::{self, MemoryInspection}; +use flybrain_core::envelope::{decode_envelope, encode_envelope}; +use flybrain_core::json::JsonValue; +use flybrain_gb::emulator::{DEFAULT_AUDIO_FRAMES, Emulator, FRAMEBUFFER_LEN}; +use serde_json::{Value, json}; + +use crate::media::{self, AUDIO_CONTENT_TYPE, FRAME_CONTENT_TYPE}; +// `crate::types` is this crate's facade over the shared `fly-session-types` crate; the +// glob keeps the contract's own names in sight instead of restating them. +use crate::types::*; +use crate::worker::{BoxFuture, HandlerCtx, HandlerReply, StatusCell, WorkerEndpoint}; + +/// The one audio stream: binjgb's stereo mix at the configured rate. +pub const AUDIO_STREAM_ID: &str = "apu"; +/// The attachment the boundary's memory image travels under. +pub const MEMORY_ATTACHMENT: &str = "inspection.memory"; +/// The memory image's content type (`legacy-gameboy-v1` section 8). +pub const MEMORY_CONTENT_TYPE: &str = "application/octet-stream"; +/// The legacy composition declares one slot. +pub const DEFAULT_SLOT: &str = "best"; +/// The legacy port. +pub const DEFAULT_PORT: &str = "p1"; +/// flysim's default `feed.audio_hz`. +pub const DEFAULT_AUDIO_RATE: u64 = 48_000; +/// Stereo. +pub const AUDIO_CHANNELS: u64 = 2; +/// The backend configuration document's form. +pub const BACKEND_CONFIG_FORM: &str = "gameboy-backend-config-v1"; +/// The capture payload's envelope magic: flybrain-core's frozen layout, like FLYSIM01's. +pub const PAYLOAD_MAGIC: &str = "FLYENV01"; +/// The capture payload's layout version. +pub const PAYLOAD_VERSION: u64 = 1; +/// The state format this environment captures under (a participant compatibility identity). +pub const STATE_FORMAT_ID: &str = "fly-gb-env-v1"; +/// The FLYSIM01 magic, for the world's half of a legacy checkpoint. +pub const FLYSIM01_MAGIC: &str = "FLYSIM01"; + +/// The capabilities the worker advertises in `Worker.Hello`. +pub fn capabilities() -> Vec { + vec![ + id("world-step-v1"), + id("pixel-observation-v1"), + id(crate::state::CHECKPOINT_CAPABILITY), + id(SLOTS_CAPABILITY), + ] +} + +// ------------------------------------------------------------------------------------------- +// The emulator seams + +/// The boundary's memory image: byte `i` is `fly_gb_read_mem(i)` (`legacy-gameboy-v1` section 8), +/// read without leaving a trace in the emulator. +/// +/// **The MEM-01 seam.** MEM-01 adds one read-only bulk read to the binjgb shim; when it lands the +/// 65,536 reads below become that one call and nothing else in this worker changes. The interim +/// body is the same function called 65,536 times through the existing `read_uncached`, so the +/// bytes are already the specified ones; the per-frame read cache is neither consulted nor +/// filled. +/// +/// **Why the save and the import.** `emulator_read_mem` is not state-neutral: reading OAM, VRAM, +/// the serial and timer registers, `IF`, `STAT` or `LY` runs binjgb's lazy synchronisation up to +/// the current tick, which changes the bytes `export_state` writes (never, in a 3,199-frame +/// replay, a frame or WRAM). The legacy loop reads none of them between a frame and the ratchet's +/// capture, so a slot saved after an unguarded image read would not be the slot the service +/// saves. The image is therefore read between an `export_state` and an `import_state` of the same +/// bytes, which leaves the emulator exactly as the frame left it (`tests/legacy_env.rs`, +/// `the_memory_image_leaves_the_emulator_as_it_found_it`). +pub fn memory_image(emulator: &mut Emulator) -> Result, String> { + let saved = emulator + .export_state() + .map_err(|e| format!("saving before the image: {e}"))?; + let image = (0..=u16::MAX) + .map(|address| emulator.read_uncached(address)) + .collect(); + emulator + .import_state(&saved) + .map_err(|e| format!("restoring after the image: {e}"))?; + Ok(image) +} + +/// binjgb's unsigned 8-bit interleaved stereo as the declared `f32le-interleaved`, with binjgb's +/// own host rule `sample / 255`: unipolar, silence at exactly 0.0. No filtering; the DC blocker +/// is the edge's presentation state (`legacy-gameboy-v1` section 9). +pub fn audio_f32le(raw: &[u8]) -> Vec { + let mut out = Vec::with_capacity(raw.len() * 4); + for &sample in raw { + let value = f32::from(sample) / flybrain_gb::emulator::AUDIO_FULL_SCALE; + out.extend_from_slice(&value.to_le_bytes()); + } + out +} + +/// The legacy mask of one complete port control: bit `i` is `GAMEBOY_BUTTONS[i]`, which is +/// `flybrain_gb::emulator::buttons`' order (`legacy-gameboy-v1` sections 6 and 7). +pub fn mask_of(control: &PortControl) -> u8 { + control + .buttons + .iter() + .enumerate() + .filter(|(_, button)| button.down) + .fold(0u8, |mask, (bit, _)| mask | (1u8 << bit)) +} + +/// The complete port control for a legacy mask. +pub fn control_of(port_id: &str, mask: u8) -> PortControl { + PortControl { + port_id: port_id.to_owned(), + buttons: gameboy::GAMEBOY_BUTTONS + .iter() + .enumerate() + .map(|(bit, button)| ButtonState { + id: (*button).to_owned(), + down: mask & (1u8 << bit) != 0, + }) + .collect(), + axes: Vec::new(), + } +} + +/// `ControllerSchema {schema: gameboy-joypad-v1, buttons: [up, down, left, right, a, b, start, +/// select], axes: []}` (`legacy-gameboy-v1` section 7). +pub fn joypad_schema() -> ControllerSchema { + ControllerSchema { + schema: gameboy::JOYPAD.schema_ref(), + buttons: gameboy::GAMEBOY_BUTTONS + .iter() + .map(|b| (*b).to_owned()) + .collect(), + axes: Vec::new(), + } +} + +/// The `lcd` view: 160 x 144 `rgba8`, row stride 640, no render delay. +pub fn view_descriptor() -> ViewDescriptor { + ViewDescriptor { + view_id: gameboy::VIEW_ID.to_owned(), + width: gameboy::VIEW_WIDTH, + height: gameboy::VIEW_HEIGHT, + row_stride: gameboy::VIEW_WIDTH * 4, + pixel_aspect_numerator: 1, + pixel_aspect_denominator: 1, + observation_delay_steps: 0, + } +} + +/// The `apu` stream at `sample_rate`, stereo. +pub fn audio_descriptor(sample_rate: u64) -> AudioDescriptor { + AudioDescriptor { + stream_id: id(AUDIO_STREAM_ID), + sample_rate, + channels: AUDIO_CHANNELS, + } +} + +/// The backend identity: the vendored binjgb core behind flybrain-gb's shim, with the size of its +/// save state on this target (an ABI-dependent layout a state is only valid under). +pub fn backend_digest() -> Digest { + digest_of_bytes( + format!( + "fly-session/gameboy-backend-v1\nbinjgb+flybrain-gb-shim\nstateBytes={}\n", + Emulator::state_size() + ) + .as_bytes(), + ) +} + +// ------------------------------------------------------------------------------------------- +// The backend configuration + +/// `gameboy-backend-config-v1`: everything about the backend that is identity. The cartridge is +/// named by digest, never by path; the setup scaffold, the slots and the audio configuration are +/// the composition's `environment` block. Its canonical bytes are the `backendConfig` AssetRef. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BackendConfig { + /// SHA-256 of the cartridge: the environment's `contentDigest` and the executor's `rom`. + pub rom_digest: Digest, + pub port_id: Id, + pub slots: Vec, + pub audio_sample_rate: u64, + /// binjgb's audio buffer, in stereo frames (flysim: `DEFAULT_AUDIO_FRAMES`). + pub audio_buffer_frames: u64, + /// The declared setup scaffold. The legacy composition declares exactly one frame. + pub setup_frames: u64, +} + +impl BackendConfig { + /// The legacy composition's configuration for a cartridge. + pub fn legacy(rom_digest: &str) -> BackendConfig { + BackendConfig { + rom_digest: rom_digest.to_owned(), + port_id: id(DEFAULT_PORT), + slots: vec![id(DEFAULT_SLOT)], + audio_sample_rate: DEFAULT_AUDIO_RATE, + audio_buffer_frames: u64::from(DEFAULT_AUDIO_FRAMES), + setup_frames: gameboy::SETUP_FRAMES, + } + } + + pub fn to_json(&self) -> Value { + json!({ + "form": BACKEND_CONFIG_FORM, + "romDigest": self.rom_digest, + "portId": self.port_id, + "slots": self.slots, + "audio": { + "sampleRate": self.audio_sample_rate, + "channels": AUDIO_CHANNELS, + "bufferFrames": self.audio_buffer_frames, + }, + "setupFrames": self.setup_frames, + "view": gameboy::VIEW_ID, + "controllerSchema": gameboy::JOYPAD.id, + "inspectionSchema": gameboy::MEMORY_INSPECTION.id, + }) + } + + /// The canonical bytes (RFC 8785) the AssetRef digests. + pub fn canonical_bytes(&self) -> Vec { + canonicalize(&self.to_json()) + .expect("a backend configuration canonicalizes") + .into_bytes() + } + + pub fn asset_ref(&self) -> AssetRef { + let bytes = self.canonical_bytes(); + AssetRef { + id: id("gameboy-backend-config"), + digest: digest_of_bytes(&bytes), + byte_length: bytes.len() as u64, + format: id(BACKEND_CONFIG_FORM), + } + } + + /// Refuses a configuration this worker cannot be: another scaffold, no slot or too many, an + /// audio configuration binjgb cannot run, a malformed digest. + pub fn validate(&self) -> Result<(), String> { + if !is_digest(&self.rom_digest) { + return Err("romDigest must be 64 lowercase hex digits".to_owned()); + } + if !is_id(&self.port_id) { + return Err("portId is not an Id".to_owned()); + } + if self.setup_frames != gameboy::SETUP_FRAMES { + return Err(format!( + "the legacy composition declares a setup scaffold of exactly {} frame, not {}", + gameboy::SETUP_FRAMES, + self.setup_frames + )); + } + if self.slots.is_empty() || self.slots.len() > MAX_SLOTS { + return Err(format!("1..={MAX_SLOTS} slots")); + } + let unique: BTreeSet<&Id> = self.slots.iter().collect(); + if unique.len() != self.slots.len() || self.slots.iter().any(|s| !is_id(s)) { + return Err("slots must be unique Ids".to_owned()); + } + if !(8_000..=192_000).contains(&self.audio_sample_rate) { + return Err("audio sampleRate must be 8000..=192000".to_owned()); + } + if self.audio_buffer_frames == 0 || self.audio_buffer_frames > u64::from(u32::MAX) { + return Err("audio bufferFrames must be a positive u32".to_owned()); + } + Ok(()) + } +} + +/// What one environment worker is started with. Everything crosses a process boundary as argv. +#[derive(Clone, Debug)] +pub struct LegacyEnvironmentConfig { + pub session_id: Id, + pub worker_id: Id, + pub incarnation_id: Id, + pub worker_threads: usize, + /// Where the cartridge is. Read-only, outside the checkout; never identity. + pub rom_path: PathBuf, + /// The backend this worker is: `Environment.Initialize` must name exactly this document, and + /// the cartridge at `rom_path` must be the one it names. + pub backend: BackendConfig, +} + +// ------------------------------------------------------------------------------------------- +// World state: what a capture carries + +/// One slot: the emulator's exported state and the frame that was on screen, as the ratchet's +/// `Snapshot` holds them, plus the boundary it was saved at. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SlotState { + pub game: Vec, + pub frame: Vec, + pub boundary: u64, +} + +/// The world at one committed boundary, as data. `State.Capture` encodes it, `State.StageRestore` +/// decodes it, and [`WorldState::from_flysim01`] / [`WorldState::flysim01_chunks`] convert its +/// FLYSIM01 half. +#[derive(Clone, Debug, PartialEq)] +pub struct WorldState { + pub rom_digest: Digest, + pub episode_id: Id, + pub boundary: u64, + pub world_time: RationalNs, + /// The legacy frame counter: `engineFrame`, FLYSIM01's `emulatorFrame`. + pub engine_frame: u64, + /// The mask on the joypad (FLYSIM01's `buttons`). + pub buttons: u8, + pub emulator: Vec, + /// The frame on screen: the last one produced, or a restored slot's. + pub framebuffer: Vec, + /// Declared slots in composition order; a slot never saved is absent. + pub slots: Vec<(Id, SlotState)>, + /// Where the next audio chunk starts, relative to the episode's audio origin. + pub audio_next_sample: u64, +} + +/// The header of a capture payload: whose, which checkpoint, which boundary, which backend. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PayloadHeader { + pub worker_id: Id, + pub checkpoint_id: Id, + pub source_scope: Scope, + /// The backend configuration digest the world ran under. + pub configuration_digest: Digest, +} + +/// The FLYSIM01 fields the world owns: the manifest scalars and the four chunks +/// (`crates/flysim/src/store.rs`: `romHash`, `emulatorFrame`, `buttons`; `emulator`, +/// `framebuffer`, `ratchetGame`, `ratchetFrame`). The agent's half is `agent_to_chunks`; the +/// task's is the adapter and ratchet state. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Flysim01World { + pub rom_hash: String, + pub emulator_frame: u64, + pub buttons: u32, + pub emulator: Vec, + pub framebuffer: Vec, + pub ratchet_game: Vec, + pub ratchet_frame: Vec, +} + +fn slot_chunk_names(index: usize) -> (String, String) { + let letter = (b'A' + index as u8) as char; + (format!("slotGame{letter}"), format!("slotFrame{letter}")) +} + +fn to_core_json(value: &Value) -> JsonValue { + JsonValue::parse(&value.to_string()).expect("serde_json output is JSON") +} + +fn from_core_json(value: &JsonValue) -> Result { + serde_json::from_str(&value.stringify()).map_err(|e| format!("manifest: {e}")) +} + +impl WorldState { + /// The world at the boundary `k = emulatorFrame - setupFrames` of a legacy checkpoint. + /// + /// FLYSIM01 carries the emulator, the frame on screen, the joypad, the frame counter and the + /// ratchet's one slot, which is the composition's slot `best`. It carries no boundary number, + /// world clock or audio position, because the legacy loop has none; they are derived from the + /// frame counter, which advances exactly once per transition and never across a rollback, so + /// `engineFrame = k + 1` holds for a legacy run from its fresh start on. The audio position is + /// the sample of `worldTime` at the configured rate, rounded down; the first chunk after the + /// restore marks the discontinuity, so no continuity is claimed across it. + pub fn from_flysim01( + bytes: &[u8], + episode_id: &Id, + slot_id: &Id, + audio_sample_rate: u64, + ) -> Result { + let world = Flysim01World::decode(bytes)?; + world.into_state(episode_id, slot_id, audio_sample_rate) + } + + /// The world's half of a FLYSIM01 export: the composition's first slot is the ratchet's. + pub fn flysim01_chunks(&self, slot_id: &Id) -> Flysim01World { + let slot = self + .slots + .iter() + .find(|(id, _)| id == slot_id) + .map(|(_, s)| s); + Flysim01World { + rom_hash: self.rom_digest.clone(), + emulator_frame: self.engine_frame, + buttons: u32::from(self.buttons), + emulator: self.emulator.clone(), + framebuffer: self.framebuffer.clone(), + ratchet_game: slot.map(|s| s.game.clone()).unwrap_or_default(), + ratchet_frame: slot.map(|s| s.frame.clone()).unwrap_or_default(), + } + } + + /// Encodes the capture payload: flybrain-core's envelope with [`PAYLOAD_MAGIC`], the scalars + /// in the manifest and every byte array as a chunk. + pub fn encode(&self, header: &PayloadHeader) -> Vec { + let slots: Vec = self + .slots + .iter() + .map( + |(slot_id, slot)| json!({"slotId": slot_id, "boundary": slot.boundary.to_string()}), + ) + .collect(); + let manifest = json!({ + "payloadVersion": PAYLOAD_VERSION, + "kind": "gameboy-environment", + "workerId": header.worker_id, + "checkpointId": header.checkpoint_id, + "sourceScope": header.source_scope.to_json(), + "configurationDigest": header.configuration_digest, + "romDigest": self.rom_digest, + "episodeId": self.episode_id, + "committedStep": self.boundary.to_string(), + "worldTime": self.world_time.to_json(), + "engineFrame": self.engine_frame.to_string(), + "buttons": self.buttons, + "audioNextSample": self.audio_next_sample.to_string(), + "slots": slots, + }); + let mut chunks = vec![ + ("emulator".to_owned(), self.emulator.clone()), + ("framebuffer".to_owned(), self.framebuffer.clone()), + ]; + for (index, (_, slot)) in self.slots.iter().enumerate() { + let (game, frame) = slot_chunk_names(index); + chunks.push((game, slot.game.clone())); + chunks.push((frame, slot.frame.clone())); + } + encode_envelope(PAYLOAD_MAGIC, &to_core_json(&manifest), &chunks) + .expect("letter-only chunk names and an ASCII magic encode") + } + + /// Decodes a capture payload. Shapes are checked here; identities by the caller. + pub fn decode(bytes: &[u8]) -> Result<(PayloadHeader, WorldState), String> { + let parts = decode_envelope(bytes, PAYLOAD_MAGIC).map_err(|e| e.to_string())?; + let manifest = from_core_json(&parts.manifest)?; + let text = |key: &str| -> Result { + manifest + .get(key) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| format!("the world payload has no {key}")) + }; + let number = |key: &str| -> Result { + text(key)? + .parse::() + .map_err(|_| format!("the world payload's {key} is not a U64")) + }; + if manifest.get("payloadVersion").and_then(Value::as_u64) != Some(PAYLOAD_VERSION) { + return Err("the world payload is another payload version".to_owned()); + } + if text("kind")? != "gameboy-environment" { + return Err("this payload is not a Game Boy world's state".to_owned()); + } + let chunk = |name: &str| -> Result, String> { + parts + .chunk(name) + .map(<[u8]>::to_vec) + .ok_or_else(|| format!("the world payload has no {name} chunk")) + }; + let source_scope = Scope::from_json( + manifest + .get("sourceScope") + .ok_or("the world payload has no sourceScope")?, + ) + .map_err(|e| format!("sourceScope: {}", e.0))?; + let world_time = RationalNs::from_json( + manifest + .get("worldTime") + .ok_or("the world payload has no worldTime")?, + ) + .map_err(|e| format!("worldTime: {}", e.0))?; + let buttons = manifest + .get("buttons") + .and_then(Value::as_u64) + .and_then(|b| u8::try_from(b).ok()) + .ok_or("the world payload's buttons are not a mask")?; + let slot_list = manifest + .get("slots") + .and_then(Value::as_array) + .ok_or("the world payload has no slot list")?; + if slot_list.len() > MAX_SLOTS { + return Err(format!( + "the world payload holds more than {MAX_SLOTS} slots" + )); + } + let mut slots = Vec::with_capacity(slot_list.len()); + for (index, entry) in slot_list.iter().enumerate() { + let slot_id = entry + .get("slotId") + .and_then(Value::as_str) + .ok_or("a captured slot has no slotId")?; + let slot_id = parse_id(slot_id)?; + let boundary = entry + .get("boundary") + .and_then(Value::as_str) + .and_then(|b| b.parse::().ok()) + .ok_or("a captured slot has no boundary")?; + let (game, frame) = slot_chunk_names(index); + let slot = SlotState { + game: chunk(&game)?, + frame: chunk(&frame)?, + boundary, + }; + if slot.frame.len() != FRAMEBUFFER_LEN { + return Err(format!( + "slot {slot_id}'s frame is not {FRAMEBUFFER_LEN} bytes" + )); + } + slots.push((slot_id, slot)); + } + let framebuffer = chunk("framebuffer")?; + if framebuffer.len() != FRAMEBUFFER_LEN { + return Err(format!("the framebuffer is not {FRAMEBUFFER_LEN} bytes")); + } + let header = PayloadHeader { + worker_id: parse_id(&text("workerId")?)?, + checkpoint_id: parse_id(&text("checkpointId")?)?, + source_scope, + configuration_digest: text("configurationDigest")?, + }; + let state = WorldState { + rom_digest: text("romDigest")?, + episode_id: parse_id(&text("episodeId")?)?, + boundary: number("committedStep")?, + world_time, + engine_frame: number("engineFrame")?, + buttons, + emulator: chunk("emulator")?, + framebuffer, + slots, + audio_next_sample: number("audioNextSample")?, + }; + Ok((header, state)) + } +} + +/// The world time of boundary `k`: `k x stepDuration`, exactly. +pub fn world_time_at(boundary: u64) -> Result { + let step = gameboy::step_duration(); + RationalNs::reduced( + u128::from(step.numerator) * u128::from(boundary), + u128::from(step.denominator), + ) + .map_err(|e| e.0) +} + +/// The sample of `world_time` at `rate`, rounded down. +pub fn sample_at(world_time: &RationalNs, rate: u64) -> u64 { + let numerator = u128::from(world_time.numerator) * u128::from(rate); + let denominator = u128::from(world_time.denominator) * 1_000_000_000u128; + (numerator / denominator) as u64 +} + +impl Flysim01World { + /// Reads the world's fields of a FLYSIM01 envelope. The agent's chunks and the task's manifest + /// entries are left to their owners. + pub fn decode(bytes: &[u8]) -> Result { + let parts = decode_envelope(bytes, FLYSIM01_MAGIC).map_err(|e| e.to_string())?; + let manifest = &parts.manifest; + let chunk = |name: &str| -> Result, String> { + parts + .chunk(name) + .map(<[u8]>::to_vec) + .ok_or_else(|| format!("checkpoint is missing the {name} chunk")) + }; + let number = |key: &str| -> Result { + manifest + .get(key) + .and_then(JsonValue::as_f64) + .ok_or_else(|| format!("checkpoint manifest is missing {key}")) + }; + Ok(Flysim01World { + rom_hash: manifest + .get("romHash") + .and_then(JsonValue::as_str) + .map(str::to_owned) + .ok_or("checkpoint manifest is missing romHash")?, + emulator_frame: number("emulatorFrame")? as u64, + buttons: number("buttons")? as u32, + emulator: chunk("emulator")?, + framebuffer: chunk("framebuffer")?, + ratchet_game: chunk("ratchetGame")?, + ratchet_frame: chunk("ratchetFrame")?, + }) + } + + /// This world as the environment's state at `k = emulatorFrame - setupFrames`. + pub fn into_state( + self, + episode_id: &Id, + slot_id: &Id, + audio_sample_rate: u64, + ) -> Result { + if self.framebuffer.len() != FRAMEBUFFER_LEN { + return Err(format!( + "checkpoint framebuffer is {} bytes", + self.framebuffer.len() + )); + } + if self.emulator_frame < gameboy::SETUP_FRAMES { + return Err("checkpoint frame counter is before the setup scaffold".to_owned()); + } + let buttons = + u8::try_from(self.buttons).map_err(|_| "checkpoint buttons are not a mask")?; + let boundary = self.emulator_frame - gameboy::SETUP_FRAMES; + let world_time = world_time_at(boundary)?; + let slots = if self.ratchet_game.is_empty() { + Vec::new() + } else { + if self.ratchet_frame.len() != FRAMEBUFFER_LEN { + return Err("the ratchet snapshot has no framebuffer".to_owned()); + } + vec![( + slot_id.clone(), + SlotState { + game: self.ratchet_game, + frame: self.ratchet_frame, + boundary, + }, + )] + }; + Ok(WorldState { + rom_digest: self.rom_hash, + episode_id: episode_id.clone(), + boundary, + audio_next_sample: sample_at(&world_time, audio_sample_rate), + world_time, + engine_frame: self.emulator_frame, + buttons, + emulator: self.emulator, + framebuffer: self.framebuffer, + slots, + }) + } + + /// The manifest entries and chunks this world contributes to a FLYSIM01 export, in + /// `store::encode`'s order. The caller merges them with the agent's and the task's. + pub fn manifest_entries(&self) -> Vec<(&'static str, JsonValue)> { + vec![ + ("romHash", self.rom_hash.as_str().into()), + ("emulatorFrame", (self.emulator_frame as f64).into()), + ("buttons", f64::from(self.buttons).into()), + ] + } + + pub fn chunks(&self) -> Vec<(String, Vec)> { + vec![ + ("emulator".to_owned(), self.emulator.clone()), + ("framebuffer".to_owned(), self.framebuffer.clone()), + ("ratchetGame".to_owned(), self.ratchet_game.clone()), + ("ratchetFrame".to_owned(), self.ratchet_frame.clone()), + ] + } +} + +// ------------------------------------------------------------------------------------------- +// The worker + +/// The live world: an emulator at a committed boundary. +struct Live { + emulator: Emulator, + epoch: Id, + episode_id: Id, + descriptor: EnvironmentDescriptor, + boundary: u64, + world_time: RationalNs, + engine_frame: u64, + buttons: u8, + framebuffer: Vec, + slots: BTreeMap, + /// Batch ids applied in this epoch. + batches: BTreeSet, + audio_next_sample: u64, + /// The next chunk starts a new timeline: after a slot restore or a group restore. + audio_discontinuity: bool, +} + +/// A validated replacement world the live session cannot see yet, on a stopped emulator of its +/// own (`state-media-v1` section 5: "stage a stopped replacement emulator"). +struct Staged { + token: Id, + checkpoint_id: Id, + scope: Scope, + emulator: Emulator, + state: WorldState, + descriptor: EnvironmentDescriptor, +} + +/// The Game Boy environment endpoint. +pub struct LegacyGameboyEnvironment { + config: LegacyEnvironmentConfig, + status: StatusCell, + live: Option, + staged: Option, + activated: BTreeSet, +} + +fn incompatible(message: impl std::fmt::Display) -> DomainError { + DomainError::before(ErrorCode::IncompatibleState, message) +} + +fn backend_failure(message: impl std::fmt::Display) -> DomainError { + DomainError::new( + ErrorCode::BackendFailure, + message, + MutationCertainty::Applied, + ) +} + +impl LegacyGameboyEnvironment { + pub fn new(config: LegacyEnvironmentConfig) -> LegacyGameboyEnvironment { + LegacyGameboyEnvironment { + config, + status: StatusCell::new(), + live: None, + staged: None, + activated: BTreeSet::new(), + } + } + + pub fn status(&self) -> StatusCell { + self.status.clone() + } + + /// The descriptor this worker advertises: built from its launch configuration alone, so a + /// replacement computes the same one before it has run a frame. + pub fn descriptor_for(backend: &BackendConfig) -> EnvironmentDescriptor { + EnvironmentDescriptor { + backend_digest: backend_digest(), + content_digest: backend.rom_digest.clone(), + configuration_digest: backend.asset_ref().digest, + step_duration: gameboy::step_duration(), + ports: vec![PortDescriptor { + port_id: backend.port_id.clone(), + controls: joypad_schema(), + }], + inspection_schema: gameboy::MEMORY_INSPECTION.schema_ref(), + views: vec![view_descriptor()], + audio: vec![audio_descriptor(backend.audio_sample_rate)], + recovery: Recovery::ExactCheckpoint, + determinism: Determinism::FixedBuild, + } + } + + fn build_descriptor(&self) -> DomainResult { + self.config + .backend + .validate() + .map_err(|e| incompatible(format!("this worker's backend configuration: {e}")))?; + let descriptor = LegacyGameboyEnvironment::descriptor_for(&self.config.backend); + descriptor.validate().map_err(DomainError::invalid)?; + Ok(descriptor) + } + + /// The participant compatibility digest of a capture: the descriptor's identities under this + /// worker's own state format. + pub fn compatibility_digest(descriptor: &EnvironmentDescriptor) -> Digest { + crate::state::Compatibility { + state_format_id: id(STATE_FORMAT_ID), + ..crate::state::Compatibility::of(descriptor) + } + .digest() + } + + /// Boots the configured cartridge, refusing one that is not the cartridge the backend + /// configuration names. Nothing has run on the emulator it returns. + fn boot(&self) -> DomainResult { + let rom = std::fs::read(&self.config.rom_path).map_err(|e| { + DomainError::before( + ErrorCode::BackendFailure, + format!("the cartridge could not be read: {e}"), + ) + })?; + let actual = digest_of_bytes(&rom); + if actual != self.config.backend.rom_digest { + return Err(incompatible(format!( + "the cartridge is {actual}, not the {} this backend configuration names", + self.config.backend.rom_digest + ))); + } + let emulator = Emulator::new( + &rom, + self.config.backend.audio_sample_rate as u32, + self.config.backend.audio_buffer_frames as u32, + ) + .map_err(|e| DomainError::before(ErrorCode::BackendFailure, format!("booting: {e}")))?; + if emulator.audio_frequency() as u64 != self.config.backend.audio_sample_rate { + return Err(incompatible(format!( + "binjgb runs its audio at {} Hz, not the configured {}", + emulator.audio_frequency(), + self.config.backend.audio_sample_rate + ))); + } + Ok(emulator) + } + + fn check_session(&self, scope: &Scope) -> DomainResult<()> { + if scope.session_id != self.config.session_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "this environment belongs to another session", + )); + } + Ok(()) + } + + /// The live world at exactly the scope's epoch and boundary. + fn live_at(&mut self, scope: &Scope, what: &str) -> DomainResult<&mut Live> { + self.check_session(scope)?; + let live = self.live.as_mut().ok_or_else(|| { + DomainError::before(ErrorCode::InvalidPhase, "this environment is uninitialized") + })?; + if live.epoch != scope.epoch { + return Err(DomainError::before( + ErrorCode::StaleEpoch, + format!("{what} names an epoch this environment is not in"), + )); + } + if scope.step != live.boundary { + return Err(DomainError::before( + if scope.step < live.boundary { + ErrorCode::StaleStep + } else { + ErrorCode::FutureStep + }, + format!("{what} must name the boundary the world is at"), + )); + } + Ok(live) + } + + /// The observation of the live world: the frame on screen as one immutable artifact (sensory + /// and broadcast), the memory image read now, and the audio chunk of the interval just run, + /// if there was one. + async fn observation( + live: &mut Live, + client: &flybus::Client, + audio: Option>, + ) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> { + let frame = + media::seal_copy(client, FRAME_CONTENT_TYPE.to_owned(), &live.framebuffer).await?; + let image = memory_image(&mut live.emulator).map_err(backend_failure)?; + let memory = media::seal_copy(client, MEMORY_CONTENT_TYPE.to_owned(), &image).await?; + let view = ViewRef { + view_id: gameboy::VIEW_ID.to_owned(), + produced_step: live.boundary, + pixels: frame.reference().clone(), + }; + let inspection = MemoryInspection { + memory: memory.reference().clone(), + rom_digest: live.descriptor.content_digest.clone(), + } + .to_typed(); + let mut attachments = vec![ + (media::view_attachment(gameboy::VIEW_ID), frame), + (MEMORY_ATTACHMENT.to_owned(), memory), + ]; + let mut chunks = Vec::new(); + if let Some(raw) = audio { + if raw.len() % AUDIO_CHANNELS as usize != 0 { + return Err(backend_failure("binjgb returned half a stereo frame")); + } + let frames = (raw.len() / AUDIO_CHANNELS as usize) as u64; + let samples = + media::seal_copy(client, AUDIO_CONTENT_TYPE.to_owned(), &audio_f32le(&raw)).await?; + chunks.push(AudioRef { + stream_id: id(AUDIO_STREAM_ID), + first_sample: live.audio_next_sample, + sample_frames: frames, + samples: samples.reference().clone(), + discontinuity: live.audio_discontinuity, + }); + attachments.push((media::audio_attachment(AUDIO_STREAM_ID), samples)); + live.audio_next_sample = live + .audio_next_sample + .checked_add(frames) + .ok_or_else(|| backend_failure("the audio position overflows"))?; + live.audio_discontinuity = false; + } + let observation = WorldObservation { + boundary: live.boundary, + world_time: live.world_time, + engine_frame: Some(live.engine_frame.to_string()), + sensory_views: vec![view.clone()], + inspection, + broadcast_views: vec![view], + audio: chunks, + }; + observation + .validate_against(&live.descriptor) + .map_err(|e| { + backend_failure(format!( + "the observation does not fit the descriptor: {}", + e.0 + )) + })?; + Ok((observation, attachments)) + } + + // -- Environment.Initialize -------------------------------------------------------------- + + async fn initialize(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + self.check_session(&scope)?; + if self.live.is_some() || self.staged.is_some() { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "this environment is already initialized", + )); + } + if scope.step != 0 { + return Err(DomainError::before( + ErrorCode::FutureStep, + "Environment.Initialize uses the new epoch at step 0", + )); + } + let params: EnvironmentInitializeParams = ctx.params()?; + let descriptor = self.build_descriptor()?; + let own = self.config.backend.asset_ref(); + if params.backend_config != own { + return Err(incompatible(format!( + "Environment.Initialize names the backend configuration {}, and this worker is {}", + params.backend_config.digest, own.digest + ))); + } + match params.port_bindings.as_slice() { + [(port_id, _agent)] if *port_id == self.config.backend.port_id => {} + _ => { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + format!( + "the legacy composition binds exactly one port, {}", + self.config.backend.port_id + ), + )); + } + } + let mut emulator = self.boot()?; + // The declared setup scaffold: one frame with no button down, attributed to no fly + // (`LegacyFrame::initialize`). Its audio is not published; the audio origin is the first + // sample of transition 0 -> 1. + emulator + .run_frame() + .map_err(|e| backend_failure(format!("running the setup frame: {e}")))?; + let framebuffer = emulator.framebuffer().to_vec(); + let _setup_audio = emulator.take_audio_u8(); + let mut live = Live { + emulator, + epoch: scope.epoch.clone(), + episode_id: params.episode_id.clone(), + descriptor: descriptor.clone(), + boundary: 0, + world_time: RationalNs::ZERO, + engine_frame: gameboy::SETUP_FRAMES, + buttons: 0, + framebuffer, + slots: BTreeMap::new(), + batches: BTreeSet::new(), + audio_next_sample: 0, + audio_discontinuity: false, + }; + let (observation, attachments) = + LegacyGameboyEnvironment::observation(&mut live, ctx.client, None).await?; + self.live = Some(live); + // The world is stopped when O[0] goes out and cannot free-run while the brain warms up. + self.status.set_state(WorkerState::Ready); + self.status.set_scope(Some(scope)); + self.status.progress(1); + let result = EnvironmentInitializeResult { + descriptor, + observation, + }; + let mut reply = HandlerReply::from(&result); + reply.artifacts = attachments; + Ok(reply) + } + + // -- Environment.Advance ----------------------------------------------------------------- + + async fn advance(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + let params: AdvanceParams = ctx.params()?; + let status = self.status.clone(); + let live = self.live_at(&scope, "Environment.Advance")?; + if live.batches.contains(¶ms.batch_id) { + return Err(DomainError::before( + ErrorCode::Conflict, + format!( + "batch {} was already applied in this epoch", + params.batch_id + ), + )); + } + // One complete batch: the one port, every button in descriptor order, no axes. + match params.controls.as_slice() { + [control] if control.port_id == live.descriptor.ports[0].port_id => { + control + .validate_against(&live.descriptor.ports[0].controls) + .map_err(|e| DomainError::invalid(e.0))?; + } + _ => { + return Err(DomainError::invalid(format!( + "the batch must hold exactly one control, for port {}", + live.descriptor.ports[0].port_id + ))); + } + } + let mask = mask_of(¶ms.controls[0]); + let digest = controls_digest(¶ms.controls); + let applied_from = live.boundary; + + // `LegacyFrame::run` and `take_frame`: the joypad, one frame, the frame it drew, its audio. + live.buttons = mask; + live.emulator.set_buttons(mask); + live.emulator + .run_frame() + .map_err(|e| backend_failure(format!("frame {}: {e}", live.engine_frame + 1)))?; + live.engine_frame += 1; + live.framebuffer + .copy_from_slice(live.emulator.framebuffer()); + let audio = live.emulator.take_audio_u8(); + live.boundary += 1; + live.world_time = live + .world_time + .checked_add(&live.descriptor.step_duration) + .map_err(|e| backend_failure(e.0))?; + live.batches.insert(params.batch_id.clone()); + status.set_batch(params.batch_id.clone()); + status.set_scope(Some(scope_at( + &scope.session_id, + &scope.epoch, + live.boundary, + ))); + status.progress(1); + + let (observation, attachments) = + LegacyGameboyEnvironment::observation(live, ctx.client, Some(audio)).await?; + let result = StepResult { + batch_id: params.batch_id, + applied_from_step: applied_from, + next_step: live.boundary, + applied_controls_digest: digest, + observation, + }; + let mut reply = HandlerReply::from(&result); + reply.artifacts = attachments; + Ok(reply) + } + + // -- gameboy-slots-v1 -------------------------------------------------------------------- + + async fn save_slot(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + let params: SaveSlotParams = ctx.params()?; + let declared = self.config.backend.slots.contains(¶ms.slot_id); + let status = self.status.clone(); + let live = self.live_at(&scope, METHOD_SAVE_SLOT)?; + if !declared { + return Err(DomainError::invalid(format!( + "slot {} is not a slot this composition declares", + params.slot_id + ))); + } + status.set_state(WorkerState::Capturing); + // The ratchet's capture: the exported state and the frame on screen. + let game = live.emulator.export_state().map_err(|e| { + status.set_state(WorkerState::Ready); + DomainError::before( + ErrorCode::BackendFailure, + format!("exporting the state: {e}"), + ) + })?; + let result = SaveSlotResult { + slot_id: params.slot_id.clone(), + boundary: live.boundary, + state_digest: digest_of_bytes(&game), + byte_length: game.len() as u64, + }; + live.slots.insert( + params.slot_id, + SlotState { + game, + frame: live.framebuffer.clone(), + boundary: live.boundary, + }, + ); + status.set_state(WorkerState::Ready); + status.progress(1); + result + .validate_against_scope(&scope) + .map_err(|e| DomainError::invalid(e.0))?; + Ok(HandlerReply::from(&result)) + } + + async fn restore_slot(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + self.check_session(&scope)?; + let params: RestoreSlotParams = ctx.params()?; + params + .validate_against_scope(&scope) + .map_err(|e| DomainError::invalid(e.0))?; + let status = self.status.clone(); + let prior = scope_at(&scope.session_id, ¶ms.prior_epoch, scope.step); + let live = self.live_at(&prior, METHOD_RESTORE_SLOT)?; + let slot = live.slots.get(¶ms.slot_id).cloned().ok_or_else(|| { + DomainError::before( + ErrorCode::InvalidPhase, + format!("slot {} holds nothing to restore", params.slot_id), + ) + })?; + if slot.frame.len() != FRAMEBUFFER_LEN { + return Err(incompatible("the slot's frame is not a 160x144 RGBA frame")); + } + status.set_state(WorkerState::Restoring); + // `recover_game` then `LegacyFrame::rollback`: import the slot, release every button + // (both calls, as flysim makes them), and the slot's frame is the frame on screen. No + // frame runs. + live.emulator.import_state(&slot.game).map_err(|e| { + DomainError::new( + ErrorCode::BackendFailure, + format!("restoring slot {}: {e}", params.slot_id), + MutationCertainty::Unknown, + ) + })?; + live.emulator.set_buttons(0); + live.framebuffer.copy_from_slice(&slot.frame); + live.buttons = 0; + live.emulator.set_buttons(0); + live.epoch = scope.epoch.clone(); + live.batches.clear(); + live.audio_discontinuity = true; + let (observation, attachments) = + LegacyGameboyEnvironment::observation(live, ctx.client, None).await?; + status.set_state(WorkerState::Ready); + status.set_scope(Some(scope.clone())); + status.progress(1); + let result = RestoreSlotResult { + slot_id: params.slot_id, + committed_step: scope.step, + observation, + }; + result + .validate_against_scope(&scope) + .map_err(|e| DomainError::new(ErrorCode::Internal, e.0, MutationCertainty::Applied))?; + let mut reply = HandlerReply::from(&result); + reply.artifacts = attachments; + Ok(reply) + } + + // -- State.Capture / StageRestore / ActivateRestore -------------------------------------- + + async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + let params: CaptureParams = ctx.params()?; + let worker_id = self.config.worker_id.clone(); + let slot_order = self.config.backend.slots.clone(); + let status = self.status.clone(); + let live = self.live_at(&scope, "State.Capture")?; + let previous = status.state(); + status.set_state(WorkerState::Capturing); + let emulator = live.emulator.export_state().map_err(|e| { + status.set_state(previous); + DomainError::before( + ErrorCode::BackendFailure, + format!("exporting the state: {e}"), + ) + })?; + let state = WorldState { + rom_digest: live.descriptor.content_digest.clone(), + episode_id: live.episode_id.clone(), + boundary: live.boundary, + world_time: live.world_time, + engine_frame: live.engine_frame, + buttons: live.buttons, + emulator, + framebuffer: live.framebuffer.clone(), + slots: slot_order + .iter() + .filter_map(|slot_id| { + live.slots + .get(slot_id) + .map(|s| (slot_id.clone(), s.clone())) + }) + .collect(), + audio_next_sample: live.audio_next_sample, + }; + let header = PayloadHeader { + worker_id, + checkpoint_id: params.checkpoint_id.clone(), + source_scope: scope.clone(), + configuration_digest: live.descriptor.configuration_digest.clone(), + }; + let bytes = state.encode(&header); + let digest = digest_of_bytes(&bytes); + let artifact = crate::state::seal_payload(ctx.client, &bytes, &digest).await?; + status.set_state(previous); + let result = CaptureResult { + checkpoint_id: params.checkpoint_id, + boundary: live.boundary, + compatibility_digest: LegacyGameboyEnvironment::compatibility_digest(&live.descriptor), + payload: artifact.reference().clone(), + }; + Ok(HandlerReply::with_artifacts( + object(result.to_json()), + vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)], + )) + } + + async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + self.check_session(&scope)?; + if self.live.is_some() { + // A world already running a boundary is not a quiescent replacement: the group + // replaces it rather than restoring over a live one. + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "State.StageRestore needs an uninitialized replacement environment", + )); + } + if let Some(staged) = &self.staged { + return Err(DomainError::before( + ErrorCode::Conflict, + format!( + "this environment already holds the staged restore {} for checkpoint {}", + staged.token, staged.checkpoint_id + ), + )); + } + let params: StageRestoreParams = ctx.params()?; + if params.source_scope.step != scope.step { + return Err(DomainError::invalid( + "State.StageRestore's scope step must be the source boundary", + )); + } + if params.source_scope.epoch == scope.epoch { + return Err(DomainError::before( + ErrorCode::StaleEpoch, + "State.StageRestore proposes the epoch the checkpoint was captured in", + )); + } + let artifact = ctx.artifact(crate::state::PAYLOAD_ATTACHMENT)?; + if artifact.reference() != ¶ms.payload { + return Err(DomainError::before( + ErrorCode::BufferInvalid, + "the staged payload attachment is not the artifact the request names", + )); + } + let bytes = artifact.read_all().await.map_err(|e| { + DomainError::before( + ErrorCode::BufferInvalid, + format!("the staged payload could not be read: {}", e.message), + ) + })?; + let declared = params + .payload + .digest + .clone() + .ok_or_else(|| incompatible("a checkpoint payload must carry a content digest"))?; + let actual = digest_of_bytes(&bytes); + if actual != declared || bytes.len() as u64 != params.payload.byte_length { + return Err(incompatible( + "the staged payload is not the content the request declares", + )); + } + let (header, state) = WorldState::decode(&bytes).map_err(incompatible)?; + if header.worker_id != self.config.worker_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "the staged payload belongs to another world", + )); + } + if header.checkpoint_id != params.checkpoint_id { + return Err(incompatible( + "the staged payload belongs to another checkpoint", + )); + } + if header.source_scope != params.source_scope || state.boundary != scope.step { + return Err(incompatible( + "the staged payload was captured at another source scope", + )); + } + let descriptor = self.build_descriptor()?; + if header.configuration_digest != descriptor.configuration_digest { + return Err(incompatible( + "the staged world was captured under another backend configuration", + )); + } + if state.rom_digest != descriptor.content_digest { + return Err(incompatible(format!( + "the staged world runs the cartridge {}, not this backend's {}", + state.rom_digest, descriptor.content_digest + ))); + } + let expected = LegacyGameboyEnvironment::compatibility_digest(&descriptor); + if expected != params.compatibility_digest { + return Err(incompatible(format!( + "the staged world's compatibility {expected} is not the {} the restore requires", + params.compatibility_digest + ))); + } + for (slot_id, _) in &state.slots { + if !self.config.backend.slots.contains(slot_id) { + return Err(incompatible(format!("slot {slot_id} is not declared here"))); + } + } + if state.world_time != world_time_at(state.boundary).map_err(incompatible)? { + return Err(incompatible("the staged world clock is not its boundary's")); + } + // Validation that needs a mutation happens on a stopped replacement emulator: the + // import either succeeds there or the live nothing is touched. + let mut emulator = self.boot()?; + emulator + .import_state(&state.emulator) + .map_err(|e| incompatible(format!("the emulator state does not load: {e}")))?; + let token = crate::agent::restore_token( + ¶ms.checkpoint_id, + &scope, + &actual, + &self.config.incarnation_id, + ); + if self.activated.contains(&token) { + return Err(DomainError::before( + ErrorCode::Conflict, + "this exact restore was already activated on this environment", + )); + } + self.staged = Some(Staged { + token: token.clone(), + checkpoint_id: params.checkpoint_id.clone(), + scope, + emulator, + state, + descriptor, + }); + self.status.set_state(WorkerState::StagedRestore); + let result = StageRestoreResult { + checkpoint_id: params.checkpoint_id, + restore_token: token, + }; + Ok(HandlerReply::from(&result)) + } + + /// Installs the staged world and returns its observation: nothing runs, the view is the saved + /// frame, the memory image is read after the import, and there is no audio chunk; the next + /// one marks the discontinuity. The legacy restore's joypad write is repeated here + /// (`LegacyFrame::restore`: `set_buttons(runtime.buttons)`). + async fn state_activate_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let params: ActivateRestoreParams = ctx.params()?; + if self.activated.contains(¶ms.restore_token) { + return Err(DomainError::before( + ErrorCode::Conflict, + "this restore token has already been activated", + )); + } + let Some(staged) = self.staged.take() else { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "this environment holds no staged restore", + )); + }; + if staged.token != params.restore_token { + let token = staged.token.clone(); + self.staged = Some(staged); + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + format!( + "this environment's staged restore is {token}, not {}", + params.restore_token + ), + )); + } + self.status.set_state(WorkerState::Restoring); + let Staged { + token, + checkpoint_id, + scope, + mut emulator, + state, + descriptor, + } = staged; + emulator.set_buttons(state.buttons); + let mut live = Live { + emulator, + epoch: scope.epoch.clone(), + episode_id: state.episode_id, + descriptor, + boundary: state.boundary, + world_time: state.world_time, + engine_frame: state.engine_frame, + buttons: state.buttons, + framebuffer: state.framebuffer, + slots: state.slots.into_iter().collect(), + batches: BTreeSet::new(), + audio_next_sample: state.audio_next_sample, + audio_discontinuity: true, + }; + let (observation, attachments) = + LegacyGameboyEnvironment::observation(&mut live, ctx.client, None).await?; + self.live = Some(live); + self.activated.insert(token); + self.status.set_state(WorkerState::Ready); + self.status.set_scope(Some(scope.clone())); + let result = ActivateRestoreResult { + committed_step: scope.step, + checkpoint_id, + observation: Some(observation), + }; + result + .validate_for_role(Role::Environment) + .map_err(|e| DomainError::invalid(e.0))?; + let mut reply = HandlerReply::from(&result); + reply.artifacts = attachments; + Ok(reply) + } +} + +impl WorkerEndpoint for LegacyGameboyEnvironment { + fn worker_id(&self) -> Id { + self.config.worker_id.clone() + } + + fn incarnation_id(&self) -> Id { + self.config.incarnation_id.clone() + } + + fn session_id(&self) -> Id { + self.config.session_id.clone() + } + + fn role(&self) -> Role { + Role::Environment + } + + fn capabilities(&self) -> Vec { + capabilities() + } + + fn status_cell(&self) -> StatusCell { + self.status.clone() + } + + fn worker_threads(&self) -> u64 { + self.config.worker_threads as u64 + } + + fn methods(&self) -> Vec<&'static str> { + vec![ + "Environment.Initialize", + "Environment.Advance", + METHOD_SAVE_SLOT, + METHOD_RESTORE_SLOT, + "State.Capture", + "State.StageRestore", + "State.ActivateRestore", + ] + } + + fn handle<'a>(&'a mut self, ctx: HandlerCtx<'a>) -> BoxFuture<'a, DomainResult> { + Box::pin(async move { + match ctx.method { + "Environment.Initialize" => self.initialize(&ctx).await, + "Environment.Advance" => self.advance(&ctx).await, + METHOD_SAVE_SLOT => self.save_slot(&ctx).await, + METHOD_RESTORE_SLOT => self.restore_slot(&ctx).await, + "State.Capture" => self.state_capture(&ctx).await, + "State.StageRestore" => self.state_stage_restore(&ctx).await, + "State.ActivateRestore" => self.state_activate_restore(&ctx).await, + other => Err(DomainError::before( + ErrorCode::Unsupported, + format!("{other} is not a Game Boy environment method"), + )), + } + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_mask_and_the_control_are_one_order() { + for mask in 0..=u8::MAX { + let control = control_of("p1", mask); + control + .validate_against(&joypad_schema()) + .expect("complete"); + assert_eq!(mask_of(&control), mask); + } + // Bit order is flybrain-gb's. + assert_eq!( + mask_of(&control_of("p1", flybrain_gb::emulator::buttons::START)), + 1 << 6 + ); + assert_eq!(gameboy::GAMEBOY_BUTTONS[6], "start"); + } + + #[test] + fn audio_is_sample_over_255_with_silence_at_zero() { + let bytes = audio_f32le(&[0, 255, 51]); + let values: Vec = bytes + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(); + assert_eq!(values, vec![0.0, 1.0, 51.0 / 255.0]); + } + + #[test] + fn the_world_clock_is_the_boundary_times_the_frame() { + assert_eq!(world_time_at(0).unwrap(), RationalNs::ZERO); + let mut acc = RationalNs::ZERO; + for k in 1..=1000u64 { + acc = acc.checked_add(&gameboy::step_duration()).unwrap(); + assert_eq!(world_time_at(k).unwrap(), acc); + } + // 1000 frames at 48 kHz: 16742.68 ms -> 803,649 whole samples. + assert_eq!(sample_at(&world_time_at(1000).unwrap(), 48_000), 803_649); + } + + #[test] + fn the_backend_configuration_refuses_another_scaffold_and_bad_slots() { + let good = BackendConfig::legacy(&"ab".repeat(32)); + good.validate().unwrap(); + let mut two = good.clone(); + two.setup_frames = 2; + assert!(two.validate().unwrap_err().contains("setup scaffold")); + let mut none = good.clone(); + none.slots.clear(); + assert!(none.validate().is_err()); + let mut five = good.clone(); + five.slots = (0..5).map(|i| id(&format!("s{i}"))).collect(); + assert!(five.validate().is_err()); + // The digest moves with every identity field. + let mut rate = good.clone(); + rate.audio_sample_rate = 44_100; + assert_ne!(rate.asset_ref().digest, good.asset_ref().digest); + } + + #[test] + fn the_payload_round_trips_and_the_flysim01_half_is_the_legacy_layout() { + let slot = SlotState { + game: vec![7; 33], + frame: vec![9; FRAMEBUFFER_LEN], + boundary: 41, + }; + let state = WorldState { + rom_digest: "cd".repeat(32), + episode_id: id("ep1"), + boundary: 99, + world_time: world_time_at(99).unwrap(), + engine_frame: 100, + buttons: 0b1001_0000, + emulator: vec![1, 2, 3], + framebuffer: vec![4; FRAMEBUFFER_LEN], + slots: vec![(id("best"), slot.clone())], + audio_next_sample: 12_345, + }; + let header = PayloadHeader { + worker_id: id("world"), + checkpoint_id: id("c1"), + source_scope: scope_at("s", "e1", 99), + configuration_digest: "ef".repeat(32), + }; + let bytes = state.encode(&header); + assert_eq!(WorldState::decode(&bytes).unwrap(), (header, state.clone())); + + // The FLYSIM01 half, through flybrain-core's envelope with flysim's chunk names. + let world = state.flysim01_chunks(&id("best")); + let mut manifest = JsonValue::object(); + for (key, value) in world.manifest_entries() { + manifest.set(key, value); + } + let envelope = encode_envelope(FLYSIM01_MAGIC, &manifest, &world.chunks()).unwrap(); + let back = WorldState::from_flysim01(&envelope, &id("ep1"), &id("best"), 48_000).unwrap(); + assert_eq!(back.boundary, 99); + assert_eq!(back.engine_frame, 100); + assert_eq!(back.buttons, state.buttons); + assert_eq!(back.emulator, state.emulator); + assert_eq!(back.framebuffer, state.framebuffer); + assert_eq!( + back.slots, + vec![( + id("best"), + SlotState { + boundary: 99, + ..slot + } + )] + ); + assert_eq!( + back.audio_next_sample, + sample_at(&world_time_at(99).unwrap(), 48_000) + ); + } +} diff --git a/services/flysim/crates/fly-session/src/legacy_env_parity.rs b/services/flysim/crates/fly-session/src/legacy_env_parity.rs new file mode 100644 index 0000000..f226aae --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_env_parity.rs @@ -0,0 +1,1544 @@ +//! ENV-01's parity harness: recorded button inputs, a reference that drives the emulator directly +//! the way flysim's `LegacyFrame` does, the same inputs driven through a launched +//! [`LegacyGameboyEnvironment`] over the bus, and a record-by-record comparison. +//! +//! ```text +//! EnvScript ──> DirectEmulator (flybrain-gb Emulator in LegacyFrame order) ──> Vec +//! ──> EnvDriver (Environment.* / State.* RPCs to a launched worker) ──> Vec +//! └─ compare() ─┘ +//! FlyTrace (FND-01 FLY_TRACE of the running service) ──> replay_trace() through the worker +//! ``` +//! +//! An [`EnvRecord`] is everything both sides can observe of the world at one boundary: the +//! boundary, the engine frame and the world clock, the mask that produced it, the digest of the +//! frame on screen, of the whole 64 KiB memory image and of its WRAM window (the field FND-01's +//! trace records), the audio chunk (position, length, digest of the `f32le` bytes, discontinuity), +//! and at a slot save or a capture the digest of the exported emulator state. Equality of the +//! state digest is equality of every byte binjgb saves: CPU, memory, PPU, APU, timers, joypad. +//! +//! Three sources of recorded inputs: +//! +//! - [`toy_cart`]: a cartridge this module assembles (a few hundred bytes of our own code, no +//! game content) that reads the joypad and folds it into WRAM, VRAM, scroll, palette and a +//! square-wave channel, so frames, memory and audio all depend on the inputs. It runs with no +//! ROM installed; the committed goldens are its records. +//! - a `FLYSIM01` checkpoint with the real cartridge (`FLY_ROM`, rom-env), driven by a seeded +//! button walk with slot saves, rollbacks and a capture/restore; +//! - [`FlyTrace`]: a `FLY_TRACE` written by the running service (FND-01), whose masks and +//! boundary actions are replayed from its start checkpoint, and whose recorded frame, WRAM and +//! slot-state digests the worker must reproduce. This is "legacy fixtures unchanged" measured +//! against the service itself rather than against a transcription of it. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use fly_session_types::extensions::{ + METHOD_RESTORE_SLOT, METHOD_SAVE_SLOT, ROLLBACK_POLICY, RestoreSlotParams, RestoreSlotResult, + SaveSlotParams, SaveSlotResult, +}; +use fly_session_types::gameboy::{self, MemoryInspection}; +use flybrain_gb::emulator::{Emulator, FRAMEBUFFER_LEN}; +use flybus::{Client, Grants, Pattern, Policy, Router, RouterConfig}; +use serde_json::{Value, json}; + +use crate::launcher::{ + ExecutionMode, Launcher, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT, ThreadBudget, Via, +}; +use crate::legacy_env::{ + self, AUDIO_STREAM_ID, BackendConfig, MEMORY_ATTACHMENT, PayloadHeader, SlotState, WorldState, + audio_f32le, control_of, memory_image, world_time_at, +}; +use crate::media::{AudioTimelines, ObservationOrigin, check_required_audio, check_required_views}; +use crate::rpc::{Serials, WorkerRef, call}; +use crate::types::*; + +/// The WRAM window FND-01's trace digests (`crates/flysim/src/trace.rs`). +pub const WRAM: std::ops::RangeInclusive = 0xc000..=0xdfff; + +// ------------------------------------------------------------------------------------------- +// The toy cartridge + +pub mod toy_cart { + //! A 32 KiB cartridge assembled here: our own program, no game content, nothing committed but + //! this code. binjgb runs it without a boot ROM from the post-boot state (LCD on, BG from + //! tile data at `$8000`, map at `$9800`). + //! + //! Once per frame, at the start of vertical blank, it reads the joypad into `$C000`, counts + //! frames in `$C001`, accumulates the pad into `$C002`, scrolls the background by both, writes + //! the accumulator into one byte of tile 0 (which the whole background map shows), sets the + //! palette from the pad, and triggers square channel 1 at a pitch set by the pad whenever a + //! button is down. Frames, memory and audio therefore all depend on the recorded inputs. + + /// The title bytes at `$0134`; a variant changes the last one, so its digest differs. + const TITLE: &[u8] = b"FLYTOYCART"; + + struct Asm { + out: Vec, + } + + impl Asm { + fn here(&self) -> usize { + self.out.len() + } + fn emit(&mut self, bytes: &[u8]) { + self.out.extend_from_slice(bytes); + } + /// `jr cc, target` with `opcode` 0x18 (always), 0x20 (nz) or 0x28 (z). + fn jr_to(&mut self, opcode: u8, target: usize) { + let next = self.here() as i64 + 2; + let offset = target as i64 - next; + assert!((-128..=127).contains(&offset), "jr out of range"); + self.emit(&[opcode, offset as i8 as u8]); + } + /// A forward `jr cc` whose target is patched later; returns the offset byte's index. + fn jr_forward(&mut self, opcode: u8) -> usize { + self.emit(&[opcode, 0]); + self.here() - 1 + } + fn patch_forward(&mut self, at: usize) { + let offset = self.here() as i64 - (at as i64 + 1); + assert!((0..=127).contains(&offset)); + self.out[at] = offset as u8; + } + } + + fn program() -> Vec { + let mut a = Asm { out: Vec::new() }; + a.emit(&[0xf3]); // di + a.emit(&[0x31, 0xfe, 0xff]); // ld sp, $fffe + a.emit(&[0x3e, 0x80, 0xe0, 0x26]); // NR52: sound on + a.emit(&[0x3e, 0x77, 0xe0, 0x24]); // NR50: full volume both sides + a.emit(&[0x3e, 0xff, 0xe0, 0x25]); // NR51: every channel both sides + let wait_vblank = a.here(); + a.emit(&[0xf0, 0x44, 0xfe, 0x90]); // ldh a,[LY]; cp 144 + a.jr_to(0x20, wait_vblank); // jr nz + // The directions, then the buttons, active low. + a.emit(&[0x3e, 0x20, 0xe0, 0x00, 0xf0, 0x00, 0xf0, 0x00]); // select d-pad, read twice + a.emit(&[0x2f, 0xe6, 0x0f, 0xcb, 0x37, 0x47]); // cpl; and $0f; swap a; ld b,a + a.emit(&[0x3e, 0x10, 0xe0, 0x00, 0xf0, 0x00, 0xf0, 0x00]); // select buttons, read twice + a.emit(&[0x2f, 0xe6, 0x0f, 0xb0]); // cpl; and $0f; or b + a.emit(&[0xea, 0x00, 0xc0, 0x47]); // ld [$c000],a; ld b,a + a.emit(&[0x21, 0x01, 0xc0, 0x34]); // ld hl,$c001; inc [hl] + a.emit(&[0xfa, 0x02, 0xc0, 0x80, 0xea, 0x02, 0xc0]); // $c002 += pad + a.emit(&[0xe0, 0x43]); // SCX = accumulator + a.emit(&[0xfa, 0x01, 0xc0, 0xe0, 0x42]); // SCY = frame count + a.emit(&[0xe6, 0x0f, 0x6f, 0x26, 0x80]); // hl = $8000 + (count & 15) + a.emit(&[0xfa, 0x02, 0xc0, 0x77]); // [hl] = accumulator + a.emit(&[0x78, 0xee, 0xe4, 0xe0, 0x47]); // BGP = pad ^ $e4 + a.emit(&[0x78, 0xa7]); // ld a,b; and a + let skip = a.jr_forward(0x28); // jr z, no sound + a.emit(&[0x3e, 0x80, 0xe0, 0x11]); // NR11: 50% duty + a.emit(&[0x3e, 0xf0, 0xe0, 0x12]); // NR12: volume 15, no envelope + a.emit(&[0x78, 0xe0, 0x13]); // NR13: pitch low = pad + a.emit(&[0x3e, 0x87, 0xe0, 0x14]); // NR14: trigger, pitch high 7 + a.patch_forward(skip); + let wait_out = a.here(); + a.emit(&[0xf0, 0x44, 0xfe, 0x90]); // ldh a,[LY]; cp 144 + a.jr_to(0x28, wait_out); // jr z: leave vertical blank first + a.jr_to(0x18, wait_vblank); + a.out + } + + /// The cartridge. `variant` 0 is the one the goldens run; any other is another cartridge + /// with another digest (for the wrong-ROM refusals). + pub fn rom(variant: u8) -> Vec { + let mut rom = vec![0u8; 0x8000]; + rom[0x100..0x104].copy_from_slice(&[0x00, 0xc3, 0x50, 0x01]); // nop; jp $0150 + rom[0x134..0x134 + TITLE.len()].copy_from_slice(TITLE); + rom[0x134 + TITLE.len()] = b'0' + (variant % 10); + rom[0x147] = 0x00; // ROM only + rom[0x148] = 0x00; // 32 KiB + rom[0x149] = 0x00; // no RAM + rom[0x14a] = 0x01; + let program = program(); + rom[0x150..0x150 + program.len()].copy_from_slice(&program); + let mut header = 0u8; + for byte in &rom[0x134..0x14d] { + header = header.wrapping_sub(*byte).wrapping_sub(1); + } + rom[0x14d] = header; + let global: u16 = rom + .iter() + .enumerate() + .filter(|(i, _)| *i != 0x14e && *i != 0x14f) + .fold(0u16, |sum, (_, b)| sum.wrapping_add(u16::from(*b))); + rom[0x14e..0x150].copy_from_slice(&global.to_be_bytes()); + rom + } +} + +// ------------------------------------------------------------------------------------------- +// Scripts and records + +/// One operation of a script, applied at the boundary the world is at. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EnvOp { + /// One transition with this joypad mask. + Advance(u8), + /// `Environment.SaveSlot` at the committed boundary. + SaveSlot(Id), + /// `Environment.RestoreSlot` under a new epoch (`legacy-ratchet-rollback-v1`). + Rollback(Id), + /// `State.Capture`, then a group restore of that payload into a fresh replacement worker + /// under a new epoch (a restart of the service, `legacy-transient-reset`). + CaptureRestore, +} + +/// Where a script starts. +#[derive(Clone, Debug)] +pub enum EnvStart { + /// `Environment.Initialize`: the one-frame setup scaffold. + Fresh, + /// A `FLYSIM01` checkpoint's world, restored into a fresh worker. + Flysim01(Arc>), +} + +#[derive(Clone, Debug)] +pub struct EnvScript { + pub name: String, + pub start: EnvStart, + pub ops: Vec, +} + +/// One audio chunk as both sides see it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AudioRecord { + pub first_sample: u64, + pub frames: u64, + pub digest: Digest, + pub discontinuity: bool, +} + +/// What both sides observe of the world after one operation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EnvRecord { + pub index: u64, + pub op: &'static str, + pub boundary: u64, + pub engine_frame: u64, + pub world_time: RationalNs, + pub mask: Option, + pub frame: Digest, + pub memory: Digest, + pub wram: Digest, + pub audio: Option, + /// The exported emulator state: at a slot save, the slot's; at a capture, the world's. + pub state: Option, +} + +impl EnvRecord { + pub fn to_json(&self) -> Value { + json!({ + "index": self.index, + "op": self.op, + "boundary": self.boundary.to_string(), + "engineFrame": self.engine_frame.to_string(), + "worldTime": self.world_time.to_json(), + "mask": self.mask, + "frame": self.frame, + "memory": self.memory, + "wram": self.wram, + "audio": self.audio.as_ref().map(|a| json!({ + "firstSample": a.first_sample.to_string(), + "frames": a.frames, + "digest": a.digest, + "discontinuity": a.discontinuity, + })), + "state": self.state, + }) + } + + pub fn row(&self) -> String { + format!( + "#{} {} k={} f={} mask={:?} frame={} mem={} audio={:?} state={:?}", + self.index, + self.op, + self.boundary, + self.engine_frame, + self.mask, + &self.frame[..12], + &self.memory[..12], + self.audio.as_ref().map(|a| ( + a.first_sample, + a.frames, + a.digest[..12].to_owned(), + a.discontinuity + )), + self.state.as_ref().map(|s| s[..12].to_owned()), + ) + } +} + +/// The first difference between two record lists, or none. +pub fn compare(left: &[EnvRecord], right: &[EnvRecord]) -> Result<(), String> { + for (a, b) in left.iter().zip(right) { + if a != b { + return Err(format!( + "records differ at #{}:\n left: {}\n right: {}", + a.index, + a.row(), + b.row() + )); + } + } + if left.len() != right.len() { + return Err(format!("{} records against {}", left.len(), right.len())); + } + Ok(()) +} + +/// The golden form of a script's records. +pub fn golden_json(script: &EnvScript, records: &[EnvRecord]) -> Value { + json!({ + "format": "fly-session/legacy-env-golden-v1", + "script": script.name, + "records": records.iter().map(EnvRecord::to_json).collect::>(), + }) +} + +async fn read_attachment( + artifacts: &BTreeMap, + op: &str, + name: &str, +) -> Result, String> { + let artifact = artifacts + .get(name) + .ok_or_else(|| format!("{op}: no {name} attachment"))?; + artifact.read_all().await.map_err(|e| e.message) +} + +fn memory_record(image: &[u8]) -> (Digest, Digest) { + (digest_of_bytes(image), digest_of_bytes(&image[WRAM])) +} + +fn audio_record(first_sample: u64, raw_f32: &[u8], discontinuity: bool) -> AudioRecord { + AudioRecord { + first_sample, + frames: (raw_f32.len() / 4 / legacy_env::AUDIO_CHANNELS as usize) as u64, + digest: digest_of_bytes(raw_f32), + discontinuity, + } +} + +// ------------------------------------------------------------------------------------------- +// The direct reference + +/// The emulator driven directly, call for call as flysim's `LegacyFrame` drives it (`initialize`, +/// `run` + `take_frame`, the ratchet's capture, `recover_game` + `rollback`, `restore`), with the +/// session's boundary, clock and audio position kept beside it. +pub struct DirectEmulator { + rom: Arc>, + backend: BackendConfig, + emulator: Emulator, + framebuffer: Vec, + engine_frame: u64, + buttons: u8, + boundary: u64, + world_time: RationalNs, + audio_next: u64, + discontinuity: bool, + slots: BTreeMap, + episode_id: Id, + index: u64, +} + +impl DirectEmulator { + fn boot(rom: &[u8], backend: &BackendConfig) -> Result { + Emulator::new( + rom, + backend.audio_sample_rate as u32, + backend.audio_buffer_frames as u32, + ) + .map_err(|e| e.to_string()) + } + + fn record( + &mut self, + op: &'static str, + mask: Option, + audio: Option, + state: Option, + ) -> EnvRecord { + let image = memory_image(&mut self.emulator).expect("the image reads"); + let (memory, wram) = memory_record(&image); + let record = EnvRecord { + index: self.index, + op, + boundary: self.boundary, + engine_frame: self.engine_frame, + world_time: self.world_time, + mask, + frame: digest_of_bytes(&self.framebuffer), + memory, + wram, + audio, + state, + }; + self.index += 1; + record + } + + /// `LegacyFrame::initialize`: one frame, no button pressed. + pub fn fresh( + rom: Arc>, + backend: BackendConfig, + ) -> Result<(DirectEmulator, EnvRecord), String> { + let mut emulator = DirectEmulator::boot(&rom, &backend)?; + emulator.run_frame().map_err(|e| e.to_string())?; + let framebuffer = emulator.framebuffer().to_vec(); + let _ = emulator.take_audio_u8(); + let mut direct = DirectEmulator { + rom, + backend, + emulator, + framebuffer, + engine_frame: 1, + buttons: 0, + boundary: 0, + world_time: RationalNs::ZERO, + audio_next: 0, + discontinuity: false, + slots: BTreeMap::new(), + episode_id: id("ep1"), + index: 0, + }; + let record = direct.record("initialize", None, None, None); + Ok((direct, record)) + } + + /// `Sim::try_restore` + `LegacyFrame::restore`: a new emulator, `import_state`, + /// `set_buttons(buttons)`, the saved framebuffer, and the ratchet's snapshot. + pub fn from_state( + rom: Arc>, + backend: BackendConfig, + state: WorldState, + index: u64, + ) -> Result<(DirectEmulator, EnvRecord), String> { + let mut emulator = DirectEmulator::boot(&rom, &backend)?; + emulator + .import_state(&state.emulator) + .map_err(|e| e.to_string())?; + emulator.set_buttons(state.buttons); + let mut direct = DirectEmulator { + rom, + backend, + emulator, + framebuffer: state.framebuffer, + engine_frame: state.engine_frame, + buttons: state.buttons, + boundary: state.boundary, + world_time: state.world_time, + audio_next: state.audio_next_sample, + discontinuity: true, + slots: state.slots.into_iter().collect(), + episode_id: state.episode_id, + index, + }; + let record = direct.record("restore", None, None, None); + Ok((direct, record)) + } + + /// `LegacyFrame::run` + `take_frame`. + pub fn advance(&mut self, mask: u8) -> Result { + self.buttons = mask; + self.emulator.set_buttons(mask); + self.emulator.run_frame().map_err(|e| e.to_string())?; + self.engine_frame += 1; + self.framebuffer + .copy_from_slice(self.emulator.framebuffer()); + let raw = self.emulator.take_audio_u8(); + self.boundary += 1; + self.world_time = self + .world_time + .checked_add(&gameboy::step_duration()) + .map_err(|e| e.0)?; + let samples = audio_f32le(&raw); + let audio = audio_record(self.audio_next, &samples, self.discontinuity); + self.audio_next += audio.frames; + self.discontinuity = false; + Ok(self.record("advance", Some(mask), Some(audio), None)) + } + + /// The ratchet's capture in `LegacyFrame::boundary`: `export_state` and the frame on screen. + pub fn save_slot(&mut self, slot_id: &Id) -> Result { + let game = self.emulator.export_state().map_err(|e| e.to_string())?; + let digest = digest_of_bytes(&game); + self.slots.insert( + slot_id.clone(), + SlotState { + game, + frame: self.framebuffer.clone(), + boundary: self.boundary, + }, + ); + Ok(self.record("save-slot", None, None, Some(digest))) + } + + /// `recover_game` + `LegacyFrame::rollback`, the emulator's half. + pub fn rollback(&mut self, slot_id: &Id) -> Result { + let slot = self.slots.get(slot_id).cloned().ok_or("no such slot")?; + self.emulator + .import_state(&slot.game) + .map_err(|e| e.to_string())?; + self.emulator.set_buttons(0); + self.framebuffer.copy_from_slice(&slot.frame); + self.buttons = 0; + self.emulator.set_buttons(0); + self.discontinuity = true; + Ok(self.record("rollback", None, None, None)) + } + + /// The world a capture holds at this boundary. + pub fn state(&mut self) -> Result { + Ok(WorldState { + rom_digest: self.backend.rom_digest.clone(), + episode_id: self.episode_id.clone(), + boundary: self.boundary, + world_time: self.world_time, + engine_frame: self.engine_frame, + buttons: self.buttons, + emulator: self.emulator.export_state().map_err(|e| e.to_string())?, + framebuffer: self.framebuffer.clone(), + slots: self + .backend + .slots + .iter() + .filter_map(|s| self.slots.get(s).map(|slot| (s.clone(), slot.clone()))) + .collect(), + audio_next_sample: self.audio_next, + }) + } + + /// A capture and a restart of the service onto it: a new emulator restored from the state. + pub fn capture_restore(self) -> Result<(DirectEmulator, EnvRecord, EnvRecord), String> { + let mut this = self; + let state = this.state()?; + let capture = this.record("capture", None, None, Some(world_digest(&state))); + let (restored, record) = + DirectEmulator::from_state(this.rom.clone(), this.backend.clone(), state, this.index)?; + Ok((restored, capture, record)) + } +} + +/// The digest of a world's content: every byte array and every scalar, without the payload +/// header (which names the worker and the checkpoint, not the world). +pub fn world_digest(state: &WorldState) -> Digest { + let slots: Vec = state + .slots + .iter() + .map(|(id, slot)| { + json!({ + "slotId": id, + "boundary": slot.boundary.to_string(), + "game": digest_of_bytes(&slot.game), + "frame": digest_of_bytes(&slot.frame), + }) + }) + .collect(); + digest_of(&json!({ + "romDigest": state.rom_digest, + "episodeId": state.episode_id, + "boundary": state.boundary.to_string(), + "worldTime": state.world_time.to_json(), + "engineFrame": state.engine_frame.to_string(), + "buttons": state.buttons, + "emulator": digest_of_bytes(&state.emulator), + "framebuffer": digest_of_bytes(&state.framebuffer), + "audioNextSample": state.audio_next_sample.to_string(), + "slots": slots, + })) + .expect("a world digest canonicalizes") +} + +/// Runs a script on the direct reference. +pub fn run_direct( + rom: Arc>, + backend: &BackendConfig, + script: &EnvScript, +) -> Result, String> { + let (mut direct, first) = match &script.start { + EnvStart::Fresh => DirectEmulator::fresh(rom, backend.clone())?, + EnvStart::Flysim01(bytes) => { + let state = WorldState::from_flysim01( + bytes, + &id("ep1"), + &backend.slots[0], + backend.audio_sample_rate, + )?; + DirectEmulator::from_state(rom, backend.clone(), state, 0)? + } + }; + let mut records = vec![first]; + for op in &script.ops { + match op { + EnvOp::Advance(mask) => records.push(direct.advance(*mask)?), + EnvOp::SaveSlot(slot) => records.push(direct.save_slot(slot)?), + EnvOp::Rollback(slot) => records.push(direct.rollback(slot)?), + EnvOp::CaptureRestore => { + let (next, capture, restore) = direct.capture_restore()?; + records.push(capture); + records.push(restore); + direct = next; + } + } + } + Ok(records) +} + +// ------------------------------------------------------------------------------------------- +// The rig: a router, a launcher in one mode, the environment it started + +const DRIVER_CLIENT: &str = "env-driver"; +const MAX_GENERATIONS: u32 = 8; + +fn env_service(worker_id: &str) -> String { + format!("env.{worker_id}") +} + +fn env_client(worker_id: &str, generation: u32) -> String { + format!("world-{worker_id}-r{generation}") +} + +fn grants(f: impl FnOnce(&mut Grants)) -> Grants { + let mut g = Grants::default(); + f(&mut g); + g +} + +fn domain(e: DomainError) -> String { + format!("{:?}: {}", e.code, e.message) +} + +/// The smallest composition that runs [`LegacyGameboyEnvironment`] under `fly-session`'s own +/// supervisor, in one execution mode. The coordinator's part is played by an [`EnvDriver`]. +pub struct EnvRig { + pub launcher: Launcher, + pub client: Client, + pub session_id: Id, + pub worker_id: Id, + pub mode: ExecutionMode, + rom_path: PathBuf, + backend: BackendConfig, + generation: u32, +} + +impl EnvRig { + pub async fn start( + root: &Path, + mode: ExecutionMode, + rom_path: &Path, + backend: BackendConfig, + ) -> Result { + let session_id = id("legacy"); + let worker_id = id("world"); + let store_root = root.join("store"); + let sockets = root.join("sockets"); + std::fs::create_dir_all(&sockets).map_err(|e| format!("sockets: {e}"))?; + let service = env_service(&worker_id); + let mut policy = Policy::closed() + .client( + DRIVER_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("env.")]), + ) + .client( + SUPERVISOR_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("env.")]), + ); + for generation in 1..=MAX_GENERATIONS { + policy = policy.client( + &env_client(&worker_id, generation), + grants(|g| g.register = vec![Pattern::exact(&service)]), + ); + } + let mut config = RouterConfig::new(&store_root); + config.policy = policy; + let router = Router::new(config).map_err(|e| format!("router: {e}"))?; + let budget = ThreadBudget::new(3, 1).map_err(|e| e.message)?; + let launcher = Launcher::start(router, mode, Via::Unix, &store_root, &sockets, budget) + .await + .map_err(|e| format!("launcher: {}", e.message))?; + let client = launcher + .connect(DRIVER_CLIENT) + .await + .map_err(|e| format!("connect: {}", e.message))?; + let mut rig = EnvRig { + launcher, + client, + session_id, + worker_id, + mode, + rom_path: rom_path.to_owned(), + backend, + generation: 0, + }; + rig.launch().await?; + Ok(rig) + } + + /// The launch specification of the next generation. + pub fn next_spec(&self) -> LegacyEnvironmentLaunch { + let generation = self.generation + 1; + LegacyEnvironmentLaunch { + session_id: self.session_id.clone(), + worker_id: self.worker_id.clone(), + incarnation_id: parse_id(&format!("{}-inc-{generation}", self.worker_id)) + .expect("an incarnation id"), + worker_threads: 1, + rom_path: self.rom_path.clone(), + backend: self.backend.clone(), + client_id: env_client(&self.worker_id, generation), + service: env_service(&self.worker_id), + } + } + + async fn launch(&mut self) -> Result { + let spec = self.next_spec(); + self.generation += 1; + self.launcher + .launch_legacy_environment(spec) + .await + .map_err(|e| e.message)?; + Ok(self.worker_ref()) + } + + /// Launches a worker from an explicit specification (for the refusals), as the next + /// generation. + pub async fn launch_spec( + &mut self, + spec: LegacyEnvironmentLaunch, + ) -> Result { + self.launcher.reap(&self.worker_id, &id("replaced")).await; + self.generation += 1; + self.launcher.launch_legacy_environment(spec).await?; + Ok(self.worker_ref()) + } + + pub fn worker_ref(&self) -> WorkerRef { + self.launcher + .worker(&self.worker_id) + .expect("launched") + .worker_ref() + } + + /// Stops the worker and starts its replacement: a new process in process mode, with a new + /// incarnation and client identity, uninitialized. + pub async fn replace(&mut self) -> Result { + self.launcher.reap(&self.worker_id, &id("replaced")).await; + self.launch().await + } + + pub async fn stop(mut self) { + self.launcher.reap_all(&id("done")).await; + } + + pub fn driver(&self) -> EnvDriver { + EnvDriver { + client: self.client.clone(), + target: self.worker_ref(), + session_id: self.session_id.clone(), + worker_id: self.worker_id.clone(), + backend: self.backend.clone(), + descriptor: None, + epoch_serial: 1, + boundary: 0, + serials: Serials::default(), + batches: 0, + timelines: AudioTimelines::default(), + index: 0, + checkpoints: 0, + last: None, + } + } +} + +/// The coordinator's side of the environment: scopes, epochs, batch ids, the descriptor it was +/// given, and the coordinator's own media checks on every observation. +pub struct EnvDriver { + client: Client, + target: WorkerRef, + session_id: Id, + worker_id: Id, + backend: BackendConfig, + descriptor: Option, + epoch_serial: u32, + boundary: u64, + serials: Serials, + batches: u64, + timelines: AudioTimelines, + index: u64, + checkpoints: u64, + /// The last observation's record, which a slot save and a capture repeat. + last: Option, +} + +/// A captured payload, held for a restore. +pub struct Captured { + pub result: CaptureResult, + pub artifact: flybus::Artifact, + pub bytes: Vec, + pub scope: Scope, +} + +const WANT: [&str; 3] = ["view.lcd", MEMORY_ATTACHMENT, "audio.apu"]; + +impl EnvDriver { + fn epoch(&self) -> Id { + id(&format!("e{}", self.epoch_serial)) + } + + pub fn scope(&self) -> Scope { + scope_at(&self.session_id, &self.epoch(), self.boundary) + } + + pub fn boundary(&self) -> u64 { + self.boundary + } + + pub fn target(&self) -> &WorkerRef { + &self.target + } + + pub fn descriptor(&self) -> Option<&EnvironmentDescriptor> { + self.descriptor.as_ref() + } + + /// Moves the driver to the next epoch without telling the worker, to address it wrongly. + pub fn bump_epoch(&mut self) { + self.epoch_serial += 1; + } + + pub fn set_target(&mut self, target: WorkerRef) { + self.target = target; + } + + async fn call( + &mut self, + method: &str, + scope: Option, + params: Value, + attachments: &[(&str, &flybus::Artifact)], + ) -> Result { + let reply = self + .call_raw(method, scope, params, attachments) + .await + .map_err(|e| format!("{method}: {}", domain(e)))?; + reply + .result() + .map_err(|e| format!("{method}: {}", domain(e)))?; + Ok(reply) + } + + /// One call with any params, its domain outcome returned as it stands. + pub async fn call_raw( + &mut self, + method: &str, + scope: Option, + params: Value, + attachments: &[(&str, &flybus::Artifact)], + ) -> Result { + let request_id = self.serials.next(&self.target.service); + self.retry_raw(request_id, method, scope, params, attachments) + .await + } + + /// The same request id again: a domain retry, or a duplicate. + pub async fn retry_raw( + &mut self, + request_id: DomainRequestId, + method: &str, + scope: Option, + params: Value, + attachments: &[(&str, &flybus::Artifact)], + ) -> Result { + let want: Vec = WANT + .iter() + .map(|w| (*w).to_owned()) + .chain([crate::state::PAYLOAD_ATTACHMENT.to_owned()]) + .collect(); + call( + &self.client, + &self.target, + method, + scope, + object(params), + attachments, + request_id, + &want, + ) + .await + } + + async fn acknowledge(&mut self, request_id: DomainRequestId) -> Result<(), String> { + let params = AcknowledgeParams { + request_ids: vec![request_id], + }; + self.call("Worker.Acknowledge", None, params.to_json(), &[]) + .await + .map(|_| ()) + } + + /// The `Environment.Initialize` params for this backend. + pub fn initialize_params(&self) -> EnvironmentInitializeParams { + EnvironmentInitializeParams { + backend_config: self.backend.asset_ref(), + task_config: crate::environment::synthetic_asset("pokered-task", "pokered-macros-v1"), + episode_id: id("ep1"), + port_bindings: vec![(self.backend.port_id.clone(), id("fly"))], + } + } + + /// Reads one observation's artifacts into a record, after the coordinator's Phase C checks: + /// the descriptor's shapes, the required view at its producing boundary, the audio rule for + /// the observation's origin, the audio timeline, the memory image's schema and ROM. + async fn observe( + &mut self, + op: &'static str, + mask: Option, + observation: &WorldObservation, + artifacts: &BTreeMap, + origin: ObservationOrigin, + state: Option, + ) -> Result { + let descriptor = self.descriptor.clone().ok_or("no descriptor")?; + observation.validate_against(&descriptor).map_err(|e| e.0)?; + check_required_views(&descriptor, observation).map_err(domain)?; + check_required_audio(&descriptor, observation, origin).map_err(domain)?; + self.timelines + .accept(&descriptor, observation) + .map_err(domain)?; + if observation.boundary != self.boundary { + return Err(format!( + "{op}: observation at {} for boundary {}", + observation.boundary, self.boundary + )); + } + if observation.world_time != world_time_at(self.boundary)? { + return Err(format!( + "{op}: the world clock is not boundary {}'s", + self.boundary + )); + } + let engine_frame: u64 = observation + .engine_frame + .as_deref() + .ok_or("no engineFrame")? + .parse() + .map_err(|_| "engineFrame is not a counter")?; + let inspection = MemoryInspection::from_typed(&observation.inspection).map_err(|e| e.0)?; + if inspection.rom_digest != descriptor.content_digest { + return Err("the inspection names another cartridge".to_owned()); + } + let view = &observation.sensory_views[0]; + let frame = read_attachment(artifacts, op, "view.lcd").await?; + if frame.len() != FRAMEBUFFER_LEN || artifacts["view.lcd"].reference() != &view.pixels { + return Err(format!("{op}: the view attachment is not the view")); + } + if observation.broadcast_views != observation.sensory_views { + return Err(format!("{op}: the broadcast view is not the sensory one")); + } + let image = read_attachment(artifacts, op, MEMORY_ATTACHMENT).await?; + if image.len() != gameboy::MEMORY_IMAGE_BYTES as usize + || artifacts[MEMORY_ATTACHMENT].reference() != &inspection.memory + { + return Err(format!( + "{op}: the memory attachment is not the inspection's image" + )); + } + let audio = match observation.audio.first() { + Some(chunk) => { + let samples = read_attachment(artifacts, op, "audio.apu").await?; + if artifacts["audio.apu"].reference() != &chunk.samples + || chunk.stream_id != AUDIO_STREAM_ID + { + return Err(format!("{op}: the audio attachment is not the chunk")); + } + if samples.len() as u64 != chunk.sample_frames * legacy_env::AUDIO_CHANNELS * 4 { + return Err(format!("{op}: the chunk's length is not its sampleFrames")); + } + Some(audio_record( + chunk.first_sample, + &samples, + chunk.discontinuity, + )) + } + None => None, + }; + let (memory, wram) = memory_record(&image); + let record = EnvRecord { + index: self.index, + op, + boundary: self.boundary, + engine_frame, + world_time: observation.world_time, + mask, + frame: digest_of_bytes(&frame), + memory, + wram, + audio, + state, + }; + self.index += 1; + self.last = Some(record.clone()); + Ok(record) + } + + /// Checks the descriptor the worker advertised against the composition's declaration. + fn accept_descriptor(&mut self, descriptor: &EnvironmentDescriptor) -> Result<(), String> { + descriptor.validate().map_err(|e| e.0)?; + let expected = legacy_env::LegacyGameboyEnvironment::descriptor_for(&self.backend); + if *descriptor != expected { + return Err("the environment advertised another descriptor".to_owned()); + } + if descriptor.step_duration != gameboy::step_duration() + || descriptor.content_digest != self.backend.rom_digest + || descriptor.configuration_digest != self.backend.asset_ref().digest + || descriptor.inspection_schema != gameboy::MEMORY_INSPECTION.schema_ref() + { + return Err("the descriptor is not the legacy composition's".to_owned()); + } + self.descriptor = Some(descriptor.clone()); + Ok(()) + } + + /// `Environment.Initialize`: O[0] after the one-frame scaffold. + pub async fn initialize(&mut self) -> Result { + let params = self.initialize_params(); + let reply = self + .call( + "Environment.Initialize", + Some(self.scope()), + params.to_json(), + &[], + ) + .await?; + let result: EnvironmentInitializeResult = reply.parse().map_err(domain)?; + self.accept_descriptor(&result.descriptor)?; + self.timelines = AudioTimelines::fresh(&result.descriptor); + let record = self + .observe( + "initialize", + None, + &result.observation, + &reply.artifacts, + ObservationOrigin::Installed, + None, + ) + .await?; + self.acknowledge(reply.request_id).await?; + Ok(record) + } + + /// The `AdvanceParams` of the next batch. + pub fn advance_params(&mut self, mask: u8) -> AdvanceParams { + self.batches += 1; + AdvanceParams { + batch_id: id(&format!("b{}-{}", self.epoch_serial, self.batches)), + controls: vec![control_of(&self.backend.port_id, mask)], + } + } + + /// `Environment.Advance` with one complete joypad batch. + pub async fn advance(&mut self, mask: u8) -> Result { + let params = self.advance_params(mask); + let reply = self + .call( + "Environment.Advance", + Some(self.scope()), + params.to_json(), + &[], + ) + .await?; + let result: StepResult = reply.parse().map_err(domain)?; + if result.applied_from_step != self.boundary || result.next_step != self.boundary + 1 { + return Err("Environment.Advance moved another interval".to_owned()); + } + if result.applied_controls_digest != controls_digest(¶ms.controls) + || result.batch_id != params.batch_id + { + return Err("Environment.Advance applied another batch".to_owned()); + } + self.boundary += 1; + self.observe( + "advance", + Some(mask), + &result.observation, + &reply.artifacts, + ObservationOrigin::Transition, + None, + ) + .await + } + + /// A record that changes no observation: the last one's, renumbered. + fn repeat(&mut self, op: &'static str, state: Option) -> Result { + let last = self.last.clone().ok_or("no observation yet")?; + let record = EnvRecord { + index: self.index, + op, + mask: None, + audio: None, + state, + ..last + }; + self.index += 1; + Ok(record) + } + + /// `Environment.SaveSlot` at the committed boundary. + pub async fn save_slot(&mut self, slot_id: &Id) -> Result { + let params = SaveSlotParams { + slot_id: slot_id.clone(), + }; + let scope = self.scope(); + let reply = self + .call(METHOD_SAVE_SLOT, Some(scope.clone()), params.to_json(), &[]) + .await?; + let result: SaveSlotResult = reply.parse().map_err(domain)?; + result.validate_against_scope(&scope).map_err(|e| e.0)?; + if result.slot_id != *slot_id { + return Err("SaveSlot saved another slot".to_owned()); + } + self.repeat("save-slot", Some(result.state_digest)) + } + + /// The `RestoreSlotParams` of a rollback from the current epoch. + pub fn restore_slot_params(&self, slot_id: &Id) -> RestoreSlotParams { + RestoreSlotParams { + slot_id: slot_id.clone(), + prior_epoch: self.epoch(), + policy: ROLLBACK_POLICY.to_owned(), + } + } + + /// `Environment.RestoreSlot` under the next epoch, same boundary. + pub async fn rollback(&mut self, slot_id: &Id) -> Result { + let params = self.restore_slot_params(slot_id); + self.epoch_serial += 1; + let scope = self.scope(); + let reply = self + .call( + METHOD_RESTORE_SLOT, + Some(scope.clone()), + params.to_json(), + &[], + ) + .await?; + let result: RestoreSlotResult = reply.parse().map_err(domain)?; + result.validate_against_scope(&scope).map_err(|e| e.0)?; + let descriptor = self.descriptor.clone().ok_or("no descriptor")?; + self.timelines = + AudioTimelines::restored(&descriptor, &self.timelines.positions()).map_err(domain)?; + self.observe( + "rollback", + None, + &result.observation, + &reply.artifacts, + ObservationOrigin::Installed, + None, + ) + .await + } + + /// `State.Capture` at the committed boundary, acknowledged. + pub async fn capture(&mut self) -> Result { + self.checkpoints += 1; + let scope = self.scope(); + let params = CaptureParams { + checkpoint_id: id(&format!("c{}", self.checkpoints)), + }; + let reply = self + .call("State.Capture", Some(scope.clone()), params.to_json(), &[]) + .await?; + let result: CaptureResult = reply.parse().map_err(domain)?; + let artifact = reply + .artifacts + .get(crate::state::PAYLOAD_ATTACHMENT) + .cloned() + .ok_or("State.Capture carried no payload")?; + let bytes = artifact.read_all().await.map_err(|e| e.message)?; + if Some(digest_of_bytes(&bytes)) != result.payload.digest { + return Err("the capture payload is not the digest it declares".to_owned()); + } + self.acknowledge(reply.request_id).await?; + Ok(Captured { + result, + artifact, + bytes, + scope, + }) + } + + /// A capture's record: the last observation plus the digest of the captured world. + pub fn capture_record(&mut self, captured: &Captured) -> Result { + let (_, state) = WorldState::decode(&captured.bytes)?; + self.repeat("capture", Some(world_digest(&state))) + } + + /// A group restore of `captured` into `target`, a fresh replacement worker, under a new epoch. + pub async fn restore_into( + &mut self, + target: WorkerRef, + captured: &Captured, + ) -> Result { + self.target = target; + self.epoch_serial += 1; + let (_, state) = WorldState::decode(&captured.bytes)?; + self.boundary = captured.scope.step; + let params = StageRestoreParams { + checkpoint_id: captured.result.checkpoint_id.clone(), + source_scope: captured.scope.clone(), + compatibility_digest: captured.result.compatibility_digest.clone(), + payload: captured.artifact.reference().clone(), + }; + let reply = self + .call( + "State.StageRestore", + Some(self.scope()), + params.to_json(), + &[(crate::state::PAYLOAD_ATTACHMENT, &captured.artifact)], + ) + .await?; + let staged: StageRestoreResult = reply.parse().map_err(domain)?; + self.acknowledge(reply.request_id).await?; + let params = ActivateRestoreParams { + restore_token: staged.restore_token, + }; + let reply = self + .call("State.ActivateRestore", None, params.to_json(), &[]) + .await?; + let activated: ActivateRestoreResult = reply.parse().map_err(domain)?; + if activated.committed_step != self.boundary { + return Err("State.ActivateRestore landed on another boundary".to_owned()); + } + let observation = activated + .observation + .ok_or("the environment restored no observation")?; + let descriptor = legacy_env::LegacyGameboyEnvironment::descriptor_for(&self.backend); + self.descriptor = Some(descriptor.clone()); + let positions = BTreeMap::from([(id(AUDIO_STREAM_ID), state.audio_next_sample)]); + self.timelines = AudioTimelines::restored(&descriptor, &positions).map_err(domain)?; + let record = self + .observe( + "restore", + None, + &observation, + &reply.artifacts, + ObservationOrigin::Installed, + None, + ) + .await?; + self.acknowledge(reply.request_id).await?; + Ok(record) + } + + /// Seals `state` as a capture payload this worker would have written at `source`, for a + /// restore that starts from a legacy checkpoint rather than from a capture. + pub async fn payload_of( + &mut self, + state: &WorldState, + source: Scope, + ) -> Result { + self.checkpoints += 1; + let checkpoint_id = id(&format!("c{}", self.checkpoints)); + let descriptor = legacy_env::LegacyGameboyEnvironment::descriptor_for(&self.backend); + let header = PayloadHeader { + worker_id: self.worker_id.clone(), + checkpoint_id: checkpoint_id.clone(), + source_scope: source.clone(), + configuration_digest: descriptor.configuration_digest.clone(), + }; + let bytes = state.encode(&header); + let digest = digest_of_bytes(&bytes); + let artifact = crate::state::seal_payload(&self.client, &bytes, &digest) + .await + .map_err(domain)?; + Ok(Captured { + result: CaptureResult { + checkpoint_id, + boundary: state.boundary, + compatibility_digest: legacy_env::LegacyGameboyEnvironment::compatibility_digest( + &descriptor, + ), + payload: artifact.reference().clone(), + }, + artifact, + bytes, + scope: source, + }) + } + + /// Starts the world from a `FLYSIM01` checkpoint, the way the service starts after a restart: + /// its world half becomes this environment's payload and is group-restored into the (fresh, + /// uninitialized) worker under epoch `e2`. + pub async fn restore_flysim01(&mut self, checkpoint: &[u8]) -> Result { + let state = WorldState::from_flysim01( + checkpoint, + &id("ep1"), + &self.backend.slots[0], + self.backend.audio_sample_rate, + )?; + // The legacy file carries no session identity: its source scope is a legacy epoch. + let source = scope_at(&self.session_id, "legacy", state.boundary); + let captured = self.payload_of(&state, source).await?; + let target = self.target.clone(); + self.restore_into(target, &captured).await + } +} + +/// Runs a script on a launched worker. `CaptureRestore` replaces the worker: a new process in +/// process mode. +pub async fn run_on_worker(rig: &mut EnvRig, script: &EnvScript) -> Result, String> { + let mut driver = rig.driver(); + let mut records = vec![match &script.start { + EnvStart::Fresh => driver.initialize().await?, + EnvStart::Flysim01(bytes) => driver.restore_flysim01(bytes).await?, + }]; + for op in &script.ops { + match op { + EnvOp::Advance(mask) => records.push(driver.advance(*mask).await?), + EnvOp::SaveSlot(slot) => records.push(driver.save_slot(slot).await?), + EnvOp::Rollback(slot) => records.push(driver.rollback(slot).await?), + EnvOp::CaptureRestore => { + let captured = driver.capture().await?; + records.push(driver.capture_record(&captured)?); + let target = rig.replace().await?; + records.push(driver.restore_into(target, &captured).await?); + } + } + } + Ok(records) +} + +// ------------------------------------------------------------------------------------------- +// Scripts + +/// A seeded button walk, the way the fly plays: a held direction for a while, sometimes a +/// button, sometimes nothing. xorshift32, so the script is reproducible from its seed. +pub fn button_walk(frames: usize, seed: u32) -> Vec { + let mut state = seed.max(1); + let mut next = || { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + state + }; + let mut masks = Vec::with_capacity(frames); + while masks.len() < frames { + let pick = next(); + let hold = 4 + (pick >> 8) as usize % 21; + let mask = match pick % 10 { + 0..=5 => 1u8 << (pick >> 4 & 3), // a direction + 6 => flybrain_gb::emulator::buttons::A, + 7 => flybrain_gb::emulator::buttons::B, + 8 => 0, + _ => (1u8 << (pick >> 4 & 3)) | flybrain_gb::emulator::buttons::A, + }; + for _ in 0..hold { + masks.push(mask); + } + } + masks.truncate(frames); + masks +} + +/// A script over `masks` with the boundary actions a ratchet and a restart would take: a slot +/// save, two rollbacks onto it (the second after a capture/restore, so the slot crosses a +/// restore), a second save, and a rollback that lands on a boundary where a save happened too +/// (save first, then roll back: `legacy-gameboy-v1` section 11 step 1). +pub fn scripted(name: &str, start: EnvStart, masks: &[u8]) -> EnvScript { + let slot = id(legacy_env::DEFAULT_SLOT); + let n = masks.len(); + let mut ops = Vec::new(); + for (t, mask) in masks.iter().enumerate() { + ops.push(EnvOp::Advance(*mask)); + if t == n / 8 { + ops.push(EnvOp::SaveSlot(slot.clone())); + } + if t == n * 3 / 8 { + ops.push(EnvOp::Rollback(slot.clone())); + } + if t == n / 2 { + ops.push(EnvOp::CaptureRestore); + } + if t == n * 5 / 8 { + ops.push(EnvOp::Rollback(slot.clone())); + } + if t == n * 3 / 4 { + ops.push(EnvOp::SaveSlot(slot.clone())); + ops.push(EnvOp::Rollback(slot.clone())); + } + } + EnvScript { + name: name.to_owned(), + start, + ops, + } +} + +/// The toy cartridge's golden script: a fresh start and 240 frames. +pub fn toy_script() -> EnvScript { + scripted( + "toy-cart-fresh-240", + EnvStart::Fresh, + &button_walk(240, 20_260_929), + ) +} + +/// The committed golden of [`toy_script`]. +pub fn toy_golden_path() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/legacy-env/toy-cart.golden.json") +} + +// ------------------------------------------------------------------------------------------- +// FND-01's trace + +/// One transition of a `flysim-legacy-frame-trace-v1` trace, as the environment sees it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TraceFrame { + /// The legacy frame counter before the transition: `engineFrame` of O[k]. + pub step: u64, + pub mask: u8, + pub framebuffer: Digest, + pub wram: Digest, + /// `save-slot` (with the slot's state digest) and `rollback`, in the order applied. + pub actions: Vec<(String, Option)>, +} + +/// The environment's half of a `FLY_TRACE` written by the running service. +#[derive(Clone, Debug)] +pub struct FlyTrace { + pub frames: Vec, +} + +impl FlyTrace { + pub fn read(path: &Path, limit: Option) -> Result { + let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut lines = text.lines(); + let header: Value = + serde_json::from_str(lines.next().ok_or("empty trace")?).map_err(|e| e.to_string())?; + if header.get("format").and_then(Value::as_str) != Some("flysim-legacy-frame-trace-v1") { + return Err("not a flysim-legacy-frame-trace-v1 trace".to_owned()); + } + let mut frames = Vec::new(); + for line in lines { + if limit.is_some_and(|n| frames.len() >= n) { + break; + } + let value: Value = serde_json::from_str(line).map_err(|e| e.to_string())?; + let Some(b) = value.get("behaviour") else { + continue; + }; + let text = |key: &str| { + b.get(key) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| format!("trace: no {key}")) + }; + let mut actions = Vec::new(); + for action in b + .get("boundaryActions") + .and_then(Value::as_array) + .ok_or("trace: no boundaryActions")? + { + let kind = action + .get("kind") + .and_then(Value::as_str) + .ok_or("trace: action kind")? + .to_owned(); + let digest = action + .get("stateDigest") + .and_then(Value::as_str) + .map(str::to_owned); + actions.push((kind, digest)); + } + frames.push(TraceFrame { + step: text("step")?.parse().map_err(|_| "trace: step")?, + mask: b + .get("mask") + .and_then(Value::as_u64) + .and_then(|m| u8::try_from(m).ok()) + .ok_or("trace: mask")?, + framebuffer: text("framebufferDigest")?, + wram: text("wramDigest")?, + actions, + }); + } + Ok(FlyTrace { frames }) + } + + /// The script this trace's environment inputs make, from its start checkpoint. + pub fn script(&self, name: &str, checkpoint: Arc>) -> EnvScript { + let slot = id(legacy_env::DEFAULT_SLOT); + let mut ops = Vec::new(); + for frame in &self.frames { + ops.push(EnvOp::Advance(frame.mask)); + for (kind, _) in &frame.actions { + ops.push(if kind == "save-slot" { + EnvOp::SaveSlot(slot.clone()) + } else { + EnvOp::Rollback(slot.clone()) + }); + } + } + EnvScript { + name: name.to_owned(), + start: EnvStart::Flysim01(checkpoint), + ops, + } + } + + /// Checks records produced by [`FlyTrace::script`] against what the service recorded: each + /// transition's engine frame, frame digest and WRAM digest, each slot save's state digest. + /// Returns the number of values compared. + pub fn check(&self, records: &[EnvRecord]) -> Result { + let mut at = 1; // records[0] is the restore + let mut compared = 0; + for (t, frame) in self.frames.iter().enumerate() { + let before = &records[at - 1]; + let record = records + .get(at) + .ok_or_else(|| format!("no record for transition {t}"))?; + if record.op != "advance" || before.engine_frame != frame.step { + return Err(format!( + "transition {t}: the world was at frame {} and the service at {}", + before.engine_frame, frame.step + )); + } + if record.frame != frame.framebuffer { + return Err(format!( + "transition {t} (frame {}): the frame differs from the service's", + frame.step + )); + } + if record.wram != frame.wram { + return Err(format!( + "transition {t} (frame {}): WRAM differs from the service's", + frame.step + )); + } + compared += 3; + at += 1; + for (kind, digest) in &frame.actions { + let record = records.get(at).ok_or("a boundary action has no record")?; + if kind == "save-slot" { + if record.op != "save-slot" || record.state != *digest { + return Err(format!( + "transition {t}: the slot saved is not the service's" + )); + } + compared += 1; + } else if record.op != "rollback" { + return Err(format!( + "transition {t}: no rollback where the service rolled back" + )); + } + at += 1; + } + } + if at != records.len() { + return Err("records beyond the trace".to_owned()); + } + Ok(compared) + } +} diff --git a/services/flysim/crates/fly-session/src/lib.rs b/services/flysim/crates/fly-session/src/lib.rs index 6849001..4b92dc5 100644 --- a/services/flysim/crates/fly-session/src/lib.rs +++ b/services/flysim/crates/fly-session/src/lib.rs @@ -29,6 +29,8 @@ pub mod dedup; pub mod environment; pub mod harness; pub mod launcher; +pub mod legacy_env; +pub mod legacy_env_parity; pub mod measure; pub mod media; pub mod metrics; diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index e361af3..4451900 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -606,6 +606,13 @@ async fn execute( fn classify_default(method: &str) -> Option { match method { "Agent.Prepare" | "Agent.Commit" | "Environment.Advance" => Some(OpClass::StepMutation), + // The extension methods of `workers-v1` section 7 are mutations under the step operation + // key (`legacy-gameboy-v1` section 11): `SaveSlot` at `(e, k)`, `RestoreSlot` and + // `Agent.Rollback` at the new epoch `(e', k)`. A lost reply replays from the same cache + // rather than rolling back twice. + "Agent.Rollback" | "Environment.SaveSlot" | "Environment.RestoreSlot" => { + Some(OpClass::StepMutation) + } // `ipc-v1` section 5 retains lifecycle *and capture* replies until // `Worker.Acknowledge`. The restore methods join them: their replies carry a // once-only token and, for an environment, the restored observation's artifact, and a From 4819f6ccd9a0f77ed3ed63de9b8c3c84966649d3 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:16:22 +0000 Subject: [PATCH 10/26] fly-session: the launcher starts the legacy Game Boy environment in-process, on a thread or as a process --- services/flysim/crates/fly-session/README.md | 3 + services/flysim/crates/fly-session/src/cli.rs | 36 ++++- .../flysim/crates/fly-session/src/launcher.rs | 130 ++++++++++++++++++ 3 files changed, 167 insertions(+), 2 deletions(-) diff --git a/services/flysim/crates/fly-session/README.md b/services/flysim/crates/fly-session/README.md index 219af28..46ef664 100644 --- a/services/flysim/crates/fly-session/README.md +++ b/services/flysim/crates/fly-session/README.md @@ -47,6 +47,8 @@ Ready(k) ─ Prepare all agents concurrently ─────────── | `cli` | The binary's subcommands: `agent`, `environment`, `measure` | | `state` | The durable checkpoint store over `FLYSESS1`: compatibility, generations, the bounded writer | | `harness` | The runnable composition: router, the flies, one arena, one coordinator | +| `legacy_env` | ENV-01: the legacy Game Boy environment worker over binjgb -- the one-frame setup scaffold, the joypad batch, `f32le` audio, the per-boundary memory image, `gameboy-slots-v1`, the capture payload and the world's half of `FLYSIM01` | +| `legacy_env_parity` | ENV-01's parity harness: the toy cartridge, recorded scripts, the emulator driven directly in `LegacyFrame` order, the worker driven over the bus, and the replay of the service's own `FLY_TRACE` | ## Execution modes and the launcher @@ -88,6 +90,7 @@ A separate-process participant is a subcommand of this crate's one binary, which ```sh fly-session agent --socket S --store-root D --client-id C --service N --threads T ... fly-session environment --socket S --store-root D --client-id C --service N --threads T ... +fly-session legacy-environment ... --worker ID --port p1 --rom PATH --rom-digest SHA256 --slots best fly-session measure --steps 300 --agents 1,2,4 ``` diff --git a/services/flysim/crates/fly-session/src/cli.rs b/services/flysim/crates/fly-session/src/cli.rs index dcb0df7..1c421d9 100644 --- a/services/flysim/crates/fly-session/src/cli.rs +++ b/services/flysim/crates/fly-session/src/cli.rs @@ -22,8 +22,10 @@ use std::process::ExitCode; use crate::agent::AgentFaults; use crate::environment::EnvironmentFaults; use crate::launcher::{ - AgentLaunch, EnvironmentLaunch, ExecutionMode, Started, flags, serve_one, + AgentLaunch, EnvironmentLaunch, ExecutionMode, LegacyEnvironmentLaunch, Started, flags, + serve_one, }; +use crate::legacy_env::BackendConfig; use crate::types::*; const USAGE: &str = "\ @@ -31,6 +33,8 @@ fly-session [options] agent serve one agent worker on a launcher-created endpoint environment serve the environment worker on a launcher-created endpoint + legacy-environment + serve the legacy Game Boy environment (ENV-01) on a launcher endpoint measure compare the execution modes and print the measurement table measure-row measure one row and print it as JSON (one child per row) @@ -50,6 +54,9 @@ Worker options (agent and environment): environment: --worker ID --ports p1,p2 --step-numerator N --step-denominator N [--advance-delay-ms N] [--omit-view-at-boundary N] [--fail-stage-restore 0|1] [--fail-activate-restore 0|1] + legacy-environment: + --worker ID --port ID --rom PATH --rom-digest SHA256 --slots best + --audio-rate 48000 --audio-buffer-frames 4096 --setup-frames 1 Measure options: --steps N transitions per run (default 200) @@ -77,6 +84,10 @@ pub fn main() -> ExitCode { .and_then(|o| serve(&command, &o)), "environment" => Options::parse(&rest, &[flags::COMMON, flags::ENVIRONMENT_ONLY]) .and_then(|o| serve(&command, &o)), + "legacy-environment" => { + Options::parse(&rest, &[flags::COMMON, flags::LEGACY_ENVIRONMENT_ONLY]) + .and_then(|o| serve(&command, &o)) + } "measure" => Options::parse(&rest, &[flags::MEASURE]).and_then(|o| measure(&o)), "measure-row" => Options::parse(&rest, &[flags::MEASURE]).and_then(|o| measure_row(&o)), "--help" | "-h" | "help" => { @@ -220,6 +231,23 @@ fn serve(role: &str, options: &Options) -> Result<(), String> { client_id: client_id.clone(), service: service.clone(), }), + "legacy-environment" => Started::LegacyEnvironment(LegacyEnvironmentLaunch { + session_id, + worker_id: options.id(flags::WORKER)?, + incarnation_id, + worker_threads: threads, + rom_path: options.path(flags::ROM)?, + backend: BackendConfig { + rom_digest: options.required(flags::ROM_DIGEST)?.to_owned(), + port_id: options.id(flags::PORT)?, + slots: parse_ids(options.required(flags::SLOTS)?, flags::SLOTS)?, + audio_sample_rate: options.u64(flags::AUDIO_RATE, 0)?, + audio_buffer_frames: options.u64(flags::AUDIO_BUFFER_FRAMES, 0)?, + setup_frames: options.u64(flags::SETUP_FRAMES, 0)?, + }, + client_id: client_id.clone(), + service: service.clone(), + }), _ => Started::Environment(EnvironmentLaunch { session_id, worker_id: options.id(flags::WORKER)?, @@ -260,10 +288,14 @@ fn serve(role: &str, options: &Options) -> Result<(), String> { } fn parse_ports(value: &str) -> Result, String> { + parse_ids(value, flags::PORTS) +} + +fn parse_ids(value: &str, flag: &str) -> Result, String> { value .split(',') .filter(|part| !part.is_empty()) - .map(|part| parse_id(part).map_err(|e| format!("--ports: {e}"))) + .map(|part| parse_id(part).map_err(|e| format!("--{flag}: {e}"))) .collect() } diff --git a/services/flysim/crates/fly-session/src/launcher.rs b/services/flysim/crates/fly-session/src/launcher.rs index 65827b6..9ff4e0b 100644 --- a/services/flysim/crates/fly-session/src/launcher.rs +++ b/services/flysim/crates/fly-session/src/launcher.rs @@ -30,6 +30,7 @@ use flybus::{Client, ClientConfig, Router, ServiceConfig, Transport, UnixListene use crate::agent::{AgentConfig, AgentFaults, FakeAgentWorker}; use crate::environment::{CounterEnvironment, EnvironmentConfig, EnvironmentFaults}; +use crate::legacy_env::{BackendConfig, LegacyEnvironmentConfig, LegacyGameboyEnvironment}; use crate::rpc::WorkerRef; use crate::types::*; use crate::worker::{StatusCell, WorkerHandle, serve}; @@ -257,6 +258,24 @@ pub struct EnvironmentLaunch { pub service: String, } +/// What the legacy Game Boy environment participant (ENV-01) is started with. +/// +/// Everything crosses a process boundary as argv: the cartridge's path (read-only, outside the +/// checkout, never identity) and the backend configuration it must be -- the cartridge digest, +/// the port, the declared slots and the audio configuration. `Environment.Initialize` must name +/// exactly that configuration's `AssetRef`. +#[derive(Clone, Debug)] +pub struct LegacyEnvironmentLaunch { + pub session_id: Id, + pub worker_id: Id, + pub incarnation_id: Id, + pub worker_threads: usize, + pub rom_path: PathBuf, + pub backend: BackendConfig, + pub client_id: String, + pub service: String, +} + // ------------------------------------------------------------------------------------------- // A launched participant @@ -613,6 +632,39 @@ impl Launcher { } } + /// Starts the legacy Game Boy environment (ENV-01), in the launcher's configured mode, and + /// identifies it. + pub async fn launch_legacy_environment( + &mut self, + spec: LegacyEnvironmentLaunch, + ) -> Result { + let threads = self.budget.allocate(&spec.worker_id, spec.worker_threads)?; + let identity = WorkerIdentity { + session_id: spec.session_id.clone(), + client_id: spec.client_id.clone(), + service: spec.service.clone(), + worker_id: spec.worker_id.clone(), + incarnation_id: spec.incarnation_id.clone(), + role: Role::Environment, + port_id: None, + worker_threads: threads, + }; + let started = self + .start_participant(&identity, Started::LegacyEnvironment(spec.clone()), threads) + .await; + match started { + Ok(worker) => { + let identity = worker.identity.clone(); + self.workers.insert(spec.worker_id.clone(), worker); + Ok(identity) + } + Err(e) => { + self.budget.release(&spec.worker_id); + Err(e) + } + } + } + async fn start_participant( &mut self, identity: &WorkerIdentity, @@ -695,6 +747,14 @@ impl Launcher { let status = endpoint.status(); (serve(client, service, endpoint), status) } + Started::LegacyEnvironment(spec) => { + let endpoint = LegacyGameboyEnvironment::new(legacy_environment_config( + spec, + identity.worker_threads, + )); + let status = endpoint.status(); + (serve(client, service, endpoint), status) + } }) } @@ -1250,6 +1310,13 @@ pub(crate) mod flags { pub const OMIT_AUDIO_AT_BOUNDARY: &str = "omit-audio-at-boundary"; pub const OVERLAPPING_AUDIO_AT_BOUNDARY: &str = "overlapping-audio-at-boundary"; + pub const ROM: &str = "rom"; + pub const ROM_DIGEST: &str = "rom-digest"; + pub const SLOTS: &str = "slots"; + pub const AUDIO_RATE: &str = "audio-rate"; + pub const AUDIO_BUFFER_FRAMES: &str = "audio-buffer-frames"; + pub const SETUP_FRAMES: &str = "setup-frames"; + pub const MODE: &str = "mode"; pub const AGENTS: &str = "agents"; pub const STEPS: &str = "steps"; @@ -1297,6 +1364,17 @@ pub(crate) mod flags { FAIL_STAGE_RESTORE, FAIL_ACTIVATE_RESTORE, ]; + /// What only the legacy Game Boy environment (ENV-01) is given. + pub const LEGACY_ENVIRONMENT_ONLY: &[&str] = &[ + WORKER, + PORT, + ROM, + ROM_DIGEST, + SLOTS, + AUDIO_RATE, + AUDIO_BUFFER_FRAMES, + SETUP_FRAMES, + ]; /// What a measurement run or one of its row children is given. pub const MEASURE: &[&str] = &[MODE, AGENTS, STEPS, WARMUP_STEPS, WORKER_THREADS, MODES]; } @@ -1314,6 +1392,7 @@ fn arg(name: &str, value: impl std::fmt::Display) -> (String, String) { pub(crate) enum Started { Agent(AgentLaunch), Environment(EnvironmentLaunch), + LegacyEnvironment(LegacyEnvironmentLaunch), } impl Started { @@ -1321,6 +1400,7 @@ impl Started { match self { Started::Agent(_) => "agent", Started::Environment(_) => "environment", + Started::LegacyEnvironment(_) => "legacy-environment", } } @@ -1387,6 +1467,18 @@ impl Started { } args } + Started::LegacyEnvironment(spec) => vec![ + arg(flags::SESSION, &spec.session_id), + arg(flags::WORKER, &spec.worker_id), + arg(flags::INCARNATION, &spec.incarnation_id), + arg(flags::PORT, &spec.backend.port_id), + arg(flags::ROM, spec.rom_path.display()), + arg(flags::ROM_DIGEST, &spec.backend.rom_digest), + arg(flags::SLOTS, spec.backend.slots.join(",")), + arg(flags::AUDIO_RATE, spec.backend.audio_sample_rate), + arg(flags::AUDIO_BUFFER_FRAMES, spec.backend.audio_buffer_frames), + arg(flags::SETUP_FRAMES, spec.backend.setup_frames), + ], } } } @@ -1419,6 +1511,20 @@ pub(crate) fn environment_config(spec: &EnvironmentLaunch) -> EnvironmentConfig } } +pub(crate) fn legacy_environment_config( + spec: &LegacyEnvironmentLaunch, + worker_threads: usize, +) -> LegacyEnvironmentConfig { + LegacyEnvironmentConfig { + session_id: spec.session_id.clone(), + worker_id: spec.worker_id.clone(), + incarnation_id: spec.incarnation_id.clone(), + worker_threads, + rom_path: spec.rom_path.clone(), + backend: spec.backend.clone(), + } +} + /// Connects, registers and serves one participant. Used by a thread with its own runtime and, /// through the worker subcommand, by a separate process. pub(crate) async fn serve_one( @@ -1444,6 +1550,11 @@ pub(crate) async fn serve_one( Started::Environment(spec) => { serve(client, service, CounterEnvironment::new(environment_config(spec))) } + Started::LegacyEnvironment(spec) => serve( + client, + service, + LegacyGameboyEnvironment::new(legacy_environment_config(spec, worker_threads)), + ), }) } @@ -1528,6 +1639,21 @@ mod flag_tests { } } + fn legacy_environment_launch() -> LegacyEnvironmentLaunch { + let mut backend = BackendConfig::legacy(&"ab".repeat(32)); + backend.slots = vec![id("best"), id("spare")]; + LegacyEnvironmentLaunch { + session_id: id("demo"), + worker_id: id("world"), + incarnation_id: id("world-inc-1"), + worker_threads: 1, + rom_path: PathBuf::from("/nonexistent/cartridge"), + backend, + client_id: "environment".to_owned(), + service: "env.world".to_owned(), + } + } + /// Both halves of the command line name the same constants, and this proves it for every /// argument a launch can produce: a flag the launcher writes that the parser does not /// accept would be a silently ignored option, which is what the parser now refuses. @@ -1539,6 +1665,10 @@ mod flag_tests { [flags::COMMON, flags::ENVIRONMENT_ONLY], ), (Started::Agent(agent_launch()), [flags::COMMON, flags::AGENT_ONLY]), + ( + Started::LegacyEnvironment(legacy_environment_launch()), + [flags::COMMON, flags::LEGACY_ENVIRONMENT_ONLY], + ), ] { let arguments = started.arguments(); assert!(!arguments.is_empty()); From d130a5ffe030909d683a7305fa4b011d8e53851f Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:16:22 +0000 Subject: [PATCH 11/26] fly-session: a rollback request without a declared rollback policy fails the epoch --- .../crates/fly-session/src/coordinator.rs | 36 +++++++++++++++ .../flysim/crates/fly-session/src/task.rs | 39 +++++++++++++--- .../crates/fly-session/tests/session.rs | 44 +++++++++++++++++++ 3 files changed, 112 insertions(+), 7 deletions(-) diff --git a/services/flysim/crates/fly-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index 7e6189f..9d54739 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -336,6 +336,9 @@ pub struct Coordinator { /// Set by whoever asks for a normal pause, possibly while a transition is in flight. pause: std::sync::Arc, episode: Option, + /// The rollback policy the composition declares, if any (`legacy-ratchet-rollback-v1` is + /// the only one defined). Without one, a task's rollback request is a task failure. + rollback_policy: Option, lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>, stats: Stats, /// The ordered actions this session took, for the ordering assertions. @@ -431,6 +434,7 @@ impl Coordinator { pacing: None, pause: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), episode: None, + rollback_policy: None, lifecycle_acks: Vec::new(), stats: Stats::default(), audit: Vec::new(), @@ -526,6 +530,22 @@ impl Coordinator { self.timelines.positions() } + /// Declares the composition's rollback policy (`workers-v1` section 4 and `step-v1` section 6, + /// both amended 2026-09-23). Only `legacy-ratchet-rollback-v1` is defined. Until the rollback + /// sequence is wired (TASK-01), a declared rollback request pauses the session at its boundary + /// like a terminal one, which is safe; an undeclared one fails the epoch. + pub fn declare_rollback_policy(&mut self, policy: &str) -> Result<(), DomainError> { + if policy != fly_session_types::extensions::ROLLBACK_POLICY { + return Err(DomainError::invalid(format!("{policy} is not a defined rollback policy"))); + } + self.rollback_policy = Some(id(policy)); + Ok(()) + } + + pub fn rollback_policy(&self) -> Option<&Id> { + self.rollback_policy.as_ref() + } + pub fn episode_request(&self) -> Option<&EpisodeRequest> { self.episode.as_ref() } @@ -1676,6 +1696,22 @@ impl Coordinator { self.fail_now(e, "task-evaluate") })?; self.audit.push(format!("evaluate:{k}")); + if let Some(request) = &evaluation.episode + && request.kind == EpisodeRequestKind::Rollback + && self.rollback_policy.is_none() + { + // `workers-v1` section 4 (2026-09-23): a composition that declares no rollback policy + // treats the request as a task failure. The brains and the world already moved, so + // the epoch fails rather than committing a transition whose outcome it cannot apply. + return Err(self.fail_now( + DomainError::new( + ErrorCode::Unsupported, + "the task asked for a rollback and this composition declares no rollback policy", + MutationCertainty::Applied, + ), + "task-evaluate", + )); + } let mut outcomes = evaluation.outcomes.clone(); let mut next_contexts = evaluation.next_contexts.clone(); for agent in self.agent_ids() { diff --git a/services/flysim/crates/fly-session/src/task.rs b/services/flysim/crates/fly-session/src/task.rs index db8d8cd..bbb2bf4 100644 --- a/services/flysim/crates/fly-session/src/task.rs +++ b/services/flysim/crates/fly-session/src/task.rs @@ -208,6 +208,10 @@ pub enum Terminal { Counter(i64), /// This many transitions were evaluated. AfterTransitions(u64), + /// After this many transitions, ask for a *rollback* instead: the request a composition with + /// a declared rollback policy may make, and one without it must treat as a task failure + /// (`workers-v1` section 4, 2026-09-23). Only a test asks the counter task for this. + RollbackAfterTransitions(u64), } /// The deterministic counter task: rewards come from the arena counter each agent moved. @@ -404,15 +408,36 @@ impl Task for CounterTask { let terminal = match self.terminal { Terminal::Never => false, Terminal::Counter(target) => new >= target, - Terminal::AfterTransitions(n) => self.transitions >= n, + Terminal::AfterTransitions(n) | Terminal::RollbackAfterTransitions(n) => { + self.transitions >= n + } }; - // The synthetic task only ever asks for the end of the episode; `rollback` belongs to a - // composition that declares a rollback policy (workers-v1 section 4, 2026-09-23). - let episode = terminal.then(|| EpisodeRequest { - kind: EpisodeRequestKind::Terminal, - reason: id("counter-target"), - outcome: TypedValue::new(episode_schema(), json!({"counter": new, "transitions": self.transitions})) + let rollback = matches!(self.terminal, Terminal::RollbackAfterTransitions(_)); + // The synthetic task asks for the end of the episode; `rollback` belongs to a composition + // that declares a rollback policy (workers-v1 section 4, 2026-09-23), and the synthetic + // composition declares none, so asking for one is how a test meets the refusal. + let episode = terminal.then(|| { + if rollback { + EpisodeRequest { + kind: EpisodeRequestKind::Rollback, + reason: id("stall"), + outcome: fly_session_types::gameboy::RollbackRequest { + slot_id: "best".to_owned(), + trigger: "stall".to_owned(), + } + .to_typed(), + } + } else { + EpisodeRequest { + kind: EpisodeRequestKind::Terminal, + reason: id("counter-target"), + outcome: TypedValue::new( + episode_schema(), + json!({"counter": new, "transitions": self.transitions}), + ) .expect("a synthetic typed value fits the contract"), + } + } }); Ok(Evaluation { outcomes, diff --git a/services/flysim/crates/fly-session/tests/session.rs b/services/flysim/crates/fly-session/tests/session.rs index 48dc7d6..fcce346 100644 --- a/services/flysim/crates/fly-session/tests/session.rs +++ b/services/flysim/crates/fly-session/tests/session.rs @@ -24,6 +24,8 @@ both_transports!( bootstrap_cannot_advance_the_world_or_produce_a_reward, the_committed_snapshot_names_the_boundary_that_just_ended, a_terminal_episode_pauses_at_its_own_boundary, + a_rollback_request_without_a_declared_policy_fails_the_epoch, + a_declared_rollback_policy_holds_the_session_at_its_boundary, status_answers_with_the_committed_boundary, a_worker_refuses_a_second_initialize, a_single_agent_composition_runs_the_same_transaction, @@ -308,6 +310,48 @@ async fn a_terminal_episode_pauses_at_its_own_boundary(via: Via) { f.shutdown().await; } +/// `workers-v1` section 4 (2026-09-23): a composition that declares no rollback policy treats a +/// rollback request as a task failure. The transition does not commit and the epoch is fenced. +async fn a_rollback_request_without_a_declared_policy_fails_the_epoch(via: Via) { + let config = HarnessConfig { + terminal: fly_session::task::Terminal::RollbackAfterTransitions(2), + ..HarnessConfig::default() + }; + let mut f = fixture(via, config).await; + within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap(); + assert!(f.harness.coordinator.rollback_policy().is_none()); + within("step 1", f.harness.coordinator.step()).await.unwrap(); + let err = within("step 2", f.harness.coordinator.step()).await.expect_err("refused"); + assert_eq!(err.error.code, ErrorCode::Unsupported); + assert!(err.error.message.contains("no rollback policy"), "{}", err.error.message); + assert!(f.harness.coordinator.is_fenced()); + assert_eq!(f.harness.coordinator.stats().commits, 2, "two agents committed transition 1; transition 2 committed nothing"); + f.shutdown().await; +} + +/// With `legacy-ratchet-rollback-v1` declared the request is accepted: the transition commits and +/// the session holds at its boundary with the request recorded, for the policy to run. +async fn a_declared_rollback_policy_holds_the_session_at_its_boundary(via: Via) { + let config = HarnessConfig { + terminal: fly_session::task::Terminal::RollbackAfterTransitions(2), + ..HarnessConfig::default() + }; + let mut f = fixture(via, config).await; + f.harness + .coordinator + .declare_rollback_policy("legacy-ratchet-rollback-v1") + .unwrap(); + assert!(f.harness.coordinator.declare_rollback_policy("reset-everything").is_err()); + within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap(); + let reports = within("run", f.harness.coordinator.run(4)).await.unwrap(); + assert_eq!(reports.len(), 2); + assert!(!f.harness.coordinator.is_fenced()); + assert_eq!(f.harness.coordinator.phase(), Phase::Paused(2)); + let request = f.harness.coordinator.episode_request().unwrap(); + assert_eq!(request.kind, EpisodeRequestKind::Rollback); + f.shutdown().await; +} + /// `Worker.Status` answers with the worker's own committed boundary and progress. async fn status_answers_with_the_committed_boundary(via: Via) { let mut f = default_fixture(via).await; From d07653cc41a9eb3e75f165d64cf9647fc45edad0 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:16:22 +0000 Subject: [PATCH 12/26] tests: legacy environment goldens and parity in every execution mode, the refusals, and the service trace replay --- .../fixtures/legacy-env/toy-cart.golden.json | 5174 +++++++++++++++++ .../crates/fly-session/tests/legacy_env.rs | 634 ++ 2 files changed, 5808 insertions(+) create mode 100644 services/flysim/crates/fly-session/fixtures/legacy-env/toy-cart.golden.json create mode 100644 services/flysim/crates/fly-session/tests/legacy_env.rs diff --git a/services/flysim/crates/fly-session/fixtures/legacy-env/toy-cart.golden.json b/services/flysim/crates/fly-session/fixtures/legacy-env/toy-cart.golden.json new file mode 100644 index 0000000..4dbca36 --- /dev/null +++ b/services/flysim/crates/fly-session/fixtures/legacy-env/toy-cart.golden.json @@ -0,0 +1,5174 @@ +{ + "format": "fly-session/legacy-env-golden-v1", + "script": "toy-cart-fresh-240", + "records": [ + { + "index": 0, + "op": "initialize", + "boundary": "0", + "engineFrame": "1", + "worldTime": { + "numerator": "0", + "denominator": "1" + }, + "mask": null, + "frame": "cdff586e1c1656586617e610d276b3db933e76ad27b7a79148237427ee8a7a5f", + "memory": "3407c14c51bc513a9f33022579dea167a3e24c393a2f0b0639c79fe153469acf", + "wram": "0ba149ce666205c7c800d970694d8c1bfd3c6d501f77e89044c547206a322067", + "audio": null, + "state": null + }, + { + "index": 1, + "op": "advance", + "boundary": "1", + "engineFrame": "2", + "worldTime": { + "numerator": "8572265625", + "denominator": "512" + }, + "mask": 8, + "frame": "ae8b59e34dfc614749c6a047ced955771319208885814b2d2e4d0dc7ea892984", + "memory": "76e41ca90d4d4964cff33b16bedabae862e97a494214c6c971e507ded8fd239d", + "wram": "93b320bf9ff276d4fc80bb6a7fd5fb3d116501b8799e2e9aefe2d7f453a04687", + "audio": { + "firstSample": "0", + "frames": 803, + "digest": "0ec5b46c11264d7018f7cb4fcd6edb28e89ac0b729cfd33b05f15ee4bfc7a835", + "discontinuity": false + }, + "state": null + }, + { + "index": 2, + "op": "advance", + "boundary": "2", + "engineFrame": "3", + "worldTime": { + "numerator": "8572265625", + "denominator": "256" + }, + "mask": 8, + "frame": "c391eaf32fbd4a6a2313ba1c977df87487af0225937691471354b420788ae920", + "memory": "7c5d0dbd59915c2af8dbbba21a4f9da2873264a6428a192b40092ea0691ed2a4", + "wram": "5856ffe6bc26bc0391ebd1930f95d527c1e3f082769c5f3fbc4ca3eee81250aa", + "audio": { + "firstSample": "803", + "frames": 804, + "digest": "e498c7f43dac939c8f513b443f5f68af9565122c182174e4714ce8c414e4eb03", + "discontinuity": false + }, + "state": null + }, + { + "index": 3, + "op": "advance", + "boundary": "3", + "engineFrame": "4", + "worldTime": { + "numerator": "25716796875", + "denominator": "512" + }, + "mask": 8, + "frame": "517d9684f496617473bfa8ccdec4fc8ff317a9f123561d3c68ad171c4c8c15b2", + "memory": "96effed4e11bd694d139050e48c24e2716b1fcbd7c84693fcbcc29e8588d15f7", + "wram": "43451960631b8f93a7876d0ea3c1d1e921eabd0c3b9137f3487aae2cc8c55dec", + "audio": { + "firstSample": "1607", + "frames": 804, + "digest": "227af1e52e044e53937c06612b4495e78b2489e1c1e1ec3742c35e9262673678", + "discontinuity": false + }, + "state": null + }, + { + "index": 4, + "op": "advance", + "boundary": "4", + "engineFrame": "5", + "worldTime": { + "numerator": "8572265625", + "denominator": "128" + }, + "mask": 8, + "frame": "4db5a943f50ddb98d009be22c468c43713b0bd5e2f235c914e61c6a2a9c08f99", + "memory": "8de7068988170201602c4e77847338f03a86f5e55c2c38640999b23d1bdbe0ee", + "wram": "c495ba41e55df80105ab60334afd63afca43fbb85c259fc13134b0cd6022a237", + "audio": { + "firstSample": "2411", + "frames": 803, + "digest": "fd2d3a6e81bb54df8788d5d62d2c69eaea6385a2fdf7dd6d8d7b284ff08384b5", + "discontinuity": false + }, + "state": null + }, + { + "index": 5, + "op": "advance", + "boundary": "5", + "engineFrame": "6", + "worldTime": { + "numerator": "42861328125", + "denominator": "512" + }, + "mask": 8, + "frame": "2f695f5ffac753a184a0cae34b5778688aac5509878b8ea1a4108ca2ca1c6b7d", + "memory": "c52656bc184a4b1cfcaaec9fb63a220b249ab193e09e832e56c773bd056911be", + "wram": "9fa4af63f339bf8980db378e09cc7d7f8a5891913f2316f7b2bf1c0c4ddd878c", + "audio": { + "firstSample": "3214", + "frames": 804, + "digest": "1569572ae20874c071030fd672fc7f8ba514cd7f728570d57520aaa3cbea58f3", + "discontinuity": false + }, + "state": null + }, + { + "index": 6, + "op": "advance", + "boundary": "6", + "engineFrame": "7", + "worldTime": { + "numerator": "25716796875", + "denominator": "256" + }, + "mask": 1, + "frame": "55b65b34e18e43d5c6db69a577403a322bbe824a46482cd0248c5bc0f4db67fa", + "memory": "73694d53480b76539fce160ef0d76882008e598587912b355d82a74259050a3d", + "wram": "299abe94613acdad71eff9c301ed9346b48218ef0669054a1ebb084bc7244c99", + "audio": { + "firstSample": "4018", + "frames": 804, + "digest": "9eefc80e45d4f62d08cb3eacee8c171630fbe18494eac916a75b94cb2b855a53", + "discontinuity": false + }, + "state": null + }, + { + "index": 7, + "op": "advance", + "boundary": "7", + "engineFrame": "8", + "worldTime": { + "numerator": "60005859375", + "denominator": "512" + }, + "mask": 1, + "frame": "85f7361cacb6ebe14a6a4930b1e43949713a59179d0e9efc73d2bd759ee597e4", + "memory": "e4fd2378c4c99569a541213ddd8e7722045a55df4e557c617b3d108e39df4a47", + "wram": "57433f9fc527fed6edce04d19fe0cff41b40778a2cdeaa74df1f186fe3fe8f80", + "audio": { + "firstSample": "4822", + "frames": 803, + "digest": "3a8a8270aaad2fe615b89a90c2191978b8c7e8d9204c5a1445de304301611a19", + "discontinuity": false + }, + "state": null + }, + { + "index": 8, + "op": "advance", + "boundary": "8", + "engineFrame": "9", + "worldTime": { + "numerator": "8572265625", + "denominator": "64" + }, + "mask": 1, + "frame": "3ad1bb083cba14943f4081c74c667c914e9c08b97eb6e76bd6d501c03b50f317", + "memory": "87c58545deb969e259f1b42d3991889658c3ad5e25350ec374bc4b09cc8dffb4", + "wram": "73f909b4902c6827de0153b719d03c9fff6a1fed7668d7b0a777cf06a8f91716", + "audio": { + "firstSample": "5625", + "frames": 804, + "digest": "4a9aca2ae720af8036f7a958f6a382fc517fc4fbdc367d63de5985b903b79336", + "discontinuity": false + }, + "state": null + }, + { + "index": 9, + "op": "advance", + "boundary": "9", + "engineFrame": "10", + "worldTime": { + "numerator": "77150390625", + "denominator": "512" + }, + "mask": 1, + "frame": "7e2144cedf0dcd6eacdebd3306b3262288013f6416b33f9497735d05f4b51d70", + "memory": "b468554d3a3a9852262265022e40a3abafb3308615ebfb7a157fabcc0d2372ad", + "wram": "b379117d38667d157d9be8f731b464046c15320e4841d24a67be7dd73c9b1ae4", + "audio": { + "firstSample": "6429", + "frames": 804, + "digest": "4e9e7fb90da92c2a8c2e819ab96daf60f9c4aa7e129d2c5beb2b30842c3a4b0d", + "discontinuity": false + }, + "state": null + }, + { + "index": 10, + "op": "advance", + "boundary": "10", + "engineFrame": "11", + "worldTime": { + "numerator": "42861328125", + "denominator": "256" + }, + "mask": 1, + "frame": "32326467932ab56f861a01daadfccdb102ef8a3e565657fbc55d6222d03ada25", + "memory": "182ea7c35614ce4fc6fde82dc3a7786ac2d831c33eea333bd16cc4efd63668ea", + "wram": "2a04fb594c6f81b7765aa804f3b7cd4eee10f11af4fa6a8b500f787e42134f2a", + "audio": { + "firstSample": "7233", + "frames": 803, + "digest": "369e1e472a25a08741e8243d4c39de407e9fa31123e434924d674fc3c7c1459a", + "discontinuity": false + }, + "state": null + }, + { + "index": 11, + "op": "advance", + "boundary": "11", + "engineFrame": "12", + "worldTime": { + "numerator": "94294921875", + "denominator": "512" + }, + "mask": 1, + "frame": "0525949510d3d85c0703416240093fdd6514434b9ee328964eeb55432b96fc41", + "memory": "bda1ffa8907e42db9c83d527e1d7a23f17492877d4e1bf02988920949d84d778", + "wram": "6cae4061da252a2a80b5d56303a8f604fdcffb2fbf5fddf6131969e8b93a5bef", + "audio": { + "firstSample": "8036", + "frames": 804, + "digest": "c74d73c1b78074330c4fe093f44386c1dd189c34e21e6ede66510252f331dc8d", + "discontinuity": false + }, + "state": null + }, + { + "index": 12, + "op": "advance", + "boundary": "12", + "engineFrame": "13", + "worldTime": { + "numerator": "25716796875", + "denominator": "128" + }, + "mask": 4, + "frame": "43556abc8ba06dd840619f37f81cdd5ed02aa23e0430daa4ec909c1ee92e4044", + "memory": "7bf43bfb84e3feae7027ba48046a5cb9a0289da8b46d68d984e7fb0e282d7443", + "wram": "062acd59080b0b3f6510f28b594bb4b6454675dec0a2ca6d8407fd6bc565cc7f", + "audio": { + "firstSample": "8840", + "frames": 804, + "digest": "15f5a6625080b536ea81afd03d44dc74215af5d4e08f456b3789d940d61f5c55", + "discontinuity": false + }, + "state": null + }, + { + "index": 13, + "op": "advance", + "boundary": "13", + "engineFrame": "14", + "worldTime": { + "numerator": "111439453125", + "denominator": "512" + }, + "mask": 4, + "frame": "efc792276c1275617a18b7d7e536879a5f279a2e038ed43f31a311f421636a59", + "memory": "3c1a58040b9768bc4b81fa98530a6d3a8d815d2431bcfd3314a4340fb00e6e29", + "wram": "61ed22a03bf5da17a09289e7ff56cee05fe18b0be472a643ce972a35ff5f85da", + "audio": { + "firstSample": "9644", + "frames": 803, + "digest": "2e027a1192a309b9e666ef9fde1ae57dcb8c44d670f9b62b2eb794c7a7a3abf1", + "discontinuity": false + }, + "state": null + }, + { + "index": 14, + "op": "advance", + "boundary": "14", + "engineFrame": "15", + "worldTime": { + "numerator": "60005859375", + "denominator": "256" + }, + "mask": 4, + "frame": "84a7056520757fd6bb83213ef01fec4e5d205b70f7bdee0ddd35aefb0ee954c7", + "memory": "f46fd229a88180444b125f06383efffcfe38ffb70dd54f187594a988369b7cdc", + "wram": "a59aa5cc1de814b999a0e7405776621e48ca081eec53e90915f87fb0ad246162", + "audio": { + "firstSample": "10447", + "frames": 804, + "digest": "d804a2d98e95558ce1d5737a1c2729de9012af61bf6de26eb8fd0a2be8efca67", + "discontinuity": false + }, + "state": null + }, + { + "index": 15, + "op": "advance", + "boundary": "15", + "engineFrame": "16", + "worldTime": { + "numerator": "128583984375", + "denominator": "512" + }, + "mask": 4, + "frame": "46ffe557906a6b0f735c657995377a2c4ea0cc14fddaa984d438e7208a648d39", + "memory": "2992956f96c4c0ed3e1020a1e2da2c1b130c401931b762b50f31cd68c4e8b779", + "wram": "963b3d0f4b007d2053a98dfe1a64360f552258ef00103a29141143672fd58347", + "audio": { + "firstSample": "11251", + "frames": 803, + "digest": "26f123b0ef86328e574faba07b0a102f34cb275a8f960f9ae3369819069e0fc1", + "discontinuity": false + }, + "state": null + }, + { + "index": 16, + "op": "advance", + "boundary": "16", + "engineFrame": "17", + "worldTime": { + "numerator": "8572265625", + "denominator": "32" + }, + "mask": 4, + "frame": "e480cfba81346c628c443de3308eb0fc6574cb8a8efb92086420064dafc1c9f5", + "memory": "95a662dbafc4826703f4955f6a36a82cd2b0bf91ec5dd4712d050f82999bd44f", + "wram": "a0d3ec727fd4fd2e834f8be7219e3a6e470b0db019415706152333e569d8dc97", + "audio": { + "firstSample": "12054", + "frames": 804, + "digest": "43c07cbc82f9ffa058b315b5d1533e19c3a2c22edcd60d0628a1689abf53ad4a", + "discontinuity": false + }, + "state": null + }, + { + "index": 17, + "op": "advance", + "boundary": "17", + "engineFrame": "18", + "worldTime": { + "numerator": "145728515625", + "denominator": "512" + }, + "mask": 4, + "frame": "bd2d96681e9a17bb01829f45565fb76c898176d84b5755670d68708b373602fe", + "memory": "51ae290191f668a369dbe0dad510b4922d5ab0a20d73f501635017d567a31d0c", + "wram": "28dcac035334b30a22c345bd97d0aa135f40a35eca4f06788bbcc0df9cd3c845", + "audio": { + "firstSample": "12858", + "frames": 804, + "digest": "0ea89aebda20ad5d380de0edc9c73dd4fd9208fe26d791171d16694135fcc78d", + "discontinuity": false + }, + "state": null + }, + { + "index": 18, + "op": "advance", + "boundary": "18", + "engineFrame": "19", + "worldTime": { + "numerator": "77150390625", + "denominator": "256" + }, + "mask": 4, + "frame": "1a3e5749c74a9f3443b79f2fe65c57e37ccaf5c4de5a44b8f3153bb2505d7f26", + "memory": "e76947bb62e242ead867f0c96775ce361e82bb3569996a795cf25ac525467a3c", + "wram": "9c894fa65732409091e9fc159e688fad03bfcb7a5ac3f268fec78035a2d33a62", + "audio": { + "firstSample": "13662", + "frames": 803, + "digest": "69ac7a5d5ed3404bd78eabcfc9e9336d469a2f1076c9e08ba65d97e2f2b95d5e", + "discontinuity": false + }, + "state": null + }, + { + "index": 19, + "op": "advance", + "boundary": "19", + "engineFrame": "20", + "worldTime": { + "numerator": "162873046875", + "denominator": "512" + }, + "mask": 4, + "frame": "68f717267372032b63a6076f44a63b91c31b1049d85e92a567b951496929b921", + "memory": "d9523f4791eb2a4443d1f5ad8d3297c61f2d934ad1cb05b36e7ea81cdcc9c993", + "wram": "4f8abe428f0fa4818776b2f632e1202f682672890677ba6596b149bed8dd8634", + "audio": { + "firstSample": "14465", + "frames": 804, + "digest": "350a0c16fbbc7658ff932c75da2f9c612dc32709e65a669905d08319950e66f7", + "discontinuity": false + }, + "state": null + }, + { + "index": 20, + "op": "advance", + "boundary": "20", + "engineFrame": "21", + "worldTime": { + "numerator": "42861328125", + "denominator": "128" + }, + "mask": 4, + "frame": "20c3a130b5ae2beb7815bdff76a2a495142f5fb7fadb4f2eea461dc1ab2f14ba", + "memory": "1b78760076625897189b2354ceba21a99bc209b046d0f76c5bbababd18207e63", + "wram": "699871b9d964ecff582654959aa1e34a9249449e5ac8d100d19a8d3642abb0b4", + "audio": { + "firstSample": "15269", + "frames": 804, + "digest": "4060cd2371a867ecfd9ad9040e9e8b94f9439857bf8687ca33e1d30879361c4b", + "discontinuity": false + }, + "state": null + }, + { + "index": 21, + "op": "advance", + "boundary": "21", + "engineFrame": "22", + "worldTime": { + "numerator": "180017578125", + "denominator": "512" + }, + "mask": 8, + "frame": "1b5d0e132833cf4c638def1160561585cadc91ad31f37049cd1dffc46df64157", + "memory": "4a89fa393e10ec7b87aab4b70b3e6cd8d88d8918a92809501ab3c5bd26e20ffa", + "wram": "07bf8600d435ceb57a110cebfd21dd4831f27d456615508745fe9bc39cc928c7", + "audio": { + "firstSample": "16073", + "frames": 803, + "digest": "332fa5b628c519dee0c2fe508e40371f3e9068ccb1ff9c535a2a8813e7ad91e0", + "discontinuity": false + }, + "state": null + }, + { + "index": 22, + "op": "advance", + "boundary": "22", + "engineFrame": "23", + "worldTime": { + "numerator": "94294921875", + "denominator": "256" + }, + "mask": 8, + "frame": "fbc72371aaf008d91add1fef4987a513d58589e1e050a50d5a215b631f85c055", + "memory": "d4209d96082b14f8678ec0d7202a3ddf5efffd693e98bb433f0f847f683b12bc", + "wram": "9d46deba729e1efb3efabb568210c4960cb874f239d7cabb6c7a9b24d9fe6482", + "audio": { + "firstSample": "16876", + "frames": 804, + "digest": "4671cd66d1a76e31d9e6911e65502eff416b8889572e151e86b4ff48ca550407", + "discontinuity": false + }, + "state": null + }, + { + "index": 23, + "op": "advance", + "boundary": "23", + "engineFrame": "24", + "worldTime": { + "numerator": "197162109375", + "denominator": "512" + }, + "mask": 8, + "frame": "b050b0ec00c51e0085d9e2525343254133d673a01975351ffd10de16638d6ecc", + "memory": "a229f6bd580e00713f4e86c89e4835e41dd01a4698947282cb4cb70327237399", + "wram": "286bca08f100ab6bf60b440703459ae3fca30378ac5c718ee9b5b629875de3fb", + "audio": { + "firstSample": "17680", + "frames": 804, + "digest": "839c771d7a514dbf533b3e4dcfb6baadf52beace23b09517995c321fbd26e825", + "discontinuity": false + }, + "state": null + }, + { + "index": 24, + "op": "advance", + "boundary": "24", + "engineFrame": "25", + "worldTime": { + "numerator": "25716796875", + "denominator": "64" + }, + "mask": 8, + "frame": "de9cc7c4c263136f62b4da7eb4dd65fbbb1125232f3248a195de3f6fed59aab6", + "memory": "0a6d11062689d993292f25debca93574485183d5d661c8e9ed9f4b3d4c681e6d", + "wram": "07aacb020eab56d46b42474b5265a03f118176ddabcb45ac6a1e565cb1b04dcc", + "audio": { + "firstSample": "18484", + "frames": 803, + "digest": "79296a1e1854bec8ffbd292c6bcf0ebf0b5b83a50237cc25abecf682a93e06fb", + "discontinuity": false + }, + "state": null + }, + { + "index": 25, + "op": "advance", + "boundary": "25", + "engineFrame": "26", + "worldTime": { + "numerator": "214306640625", + "denominator": "512" + }, + "mask": 8, + "frame": "c6d09ca052f3e21982da216bae98d2fd3d3c588b325cb27f8bd17abd599243cf", + "memory": "da80335b3ca30df11550502fc78e00671fcc6c95b217b0d8e9bab0cac9502196", + "wram": "6f0fdec1c4879b20b83761cc1b58294f65ab46ec72e0d5d1264ae4dfed430f7f", + "audio": { + "firstSample": "19287", + "frames": 804, + "digest": "9d53f22af68650198f415f49cbfdb4d6441d6b749a42184bd98ed38077bc7d41", + "discontinuity": false + }, + "state": null + }, + { + "index": 26, + "op": "advance", + "boundary": "26", + "engineFrame": "27", + "worldTime": { + "numerator": "111439453125", + "denominator": "256" + }, + "mask": 8, + "frame": "debc5a0a4712def5eaa8f95a9014f258c4e0f6cc3319d562d426f757269e5f85", + "memory": "0a4737b1a0a43e033bbdd8d7b3e377eb0145d1892cff6eb278ab1bcaaabb1094", + "wram": "a694d38db7a58ed60a033cd84a8f877e546906f425e052f53e993b8f7ed03aeb", + "audio": { + "firstSample": "20091", + "frames": 804, + "digest": "36668a8b01598751686e21ed4ffdec506a049d907cc938e8e495627206a3f8a5", + "discontinuity": false + }, + "state": null + }, + { + "index": 27, + "op": "advance", + "boundary": "27", + "engineFrame": "28", + "worldTime": { + "numerator": "231451171875", + "denominator": "512" + }, + "mask": 8, + "frame": "22882827b8b6e95e5c4594bfa746daff156b228e0d2c6cdea9bc59443f9d51c2", + "memory": "a3051da16d6e0d47d5e551abe2e0b0ace5ddb330bdcecbd47b17c64b55563121", + "wram": "c9f3892d4530861ababd661dddd5a4bb121ebeb56216e56d5165edaddd456d8c", + "audio": { + "firstSample": "20895", + "frames": 803, + "digest": "124cc44a4bc56d885f525327903a6beb74cdc6b1f048073c87068bda491b32d1", + "discontinuity": false + }, + "state": null + }, + { + "index": 28, + "op": "advance", + "boundary": "28", + "engineFrame": "29", + "worldTime": { + "numerator": "60005859375", + "denominator": "128" + }, + "mask": 8, + "frame": "ddd6645f0d798231bd892aa38e12eeee34aaa73c3a8ad7f4064a36409cbee596", + "memory": "e43f4a04f255aedce0330c7e1c398b2c599346f207fd23c4e8eae8900fc49bfc", + "wram": "24cda2fd2de2226aca415ccc800f4f3243d5a57d4bab75d86d334755190b5e32", + "audio": { + "firstSample": "21698", + "frames": 804, + "digest": "680ac1f5c07e0297ebf299e2457d7106f9e1624bcb1984d0438ffe05edabd674", + "discontinuity": false + }, + "state": null + }, + { + "index": 29, + "op": "advance", + "boundary": "29", + "engineFrame": "30", + "worldTime": { + "numerator": "248595703125", + "denominator": "512" + }, + "mask": 8, + "frame": "48938f83b17eb573ab340182ea70e6ee14e0d18369e76dd8f78fda4455cacbdb", + "memory": "939bb78472cf9f2cdbfa5b301dd4844ff6cac82dd5eed6e618f1388c5c14e91e", + "wram": "aef2e51914a7076ebb8ed84bef179851cfcf5f18964a5a5b768614bc8a040e29", + "audio": { + "firstSample": "22502", + "frames": 804, + "digest": "8d5b74670990cbd4148181315bd08e7c8c499132224a51110498085f79cebbcc", + "discontinuity": false + }, + "state": null + }, + { + "index": 30, + "op": "advance", + "boundary": "30", + "engineFrame": "31", + "worldTime": { + "numerator": "128583984375", + "denominator": "256" + }, + "mask": 8, + "frame": "8d846d263b0f171ea8c5adc6dc7e2bc036abcfedee7d1f9d44c849541c3024a3", + "memory": "9b62e7b02b74f5cb30692d5216e4232053e518c5ba9e62cccab59124f7c2f9da", + "wram": "6d424492644267cbabb0f2ba6124f6233e0441a58cfef6c71fb96df1eb19bf6b", + "audio": { + "firstSample": "23306", + "frames": 803, + "digest": "dc0d209aba398de449373af8736ff8b295b87c0b342335ab09aa4137a184a01c", + "discontinuity": false + }, + "state": null + }, + { + "index": 31, + "op": "advance", + "boundary": "31", + "engineFrame": "32", + "worldTime": { + "numerator": "265740234375", + "denominator": "512" + }, + "mask": 8, + "frame": "64768d7167e34d306ba9083bb1dc7e65e6123b634079787faa19d0ef3798de86", + "memory": "66278bc8057194b81bf22fad68280b50e5035a4d8a0c5233cb8f80d172fac2d9", + "wram": "fd666c21dabe652d5a961e8b85ff4c93367d5519f588d860fbb4ba1ccf549ea4", + "audio": { + "firstSample": "24109", + "frames": 804, + "digest": "a280e35809a823b4944e39524e6e9e52fad557acc3270b8aed10a0da24d51868", + "discontinuity": false + }, + "state": null + }, + { + "index": 32, + "op": "save-slot", + "boundary": "31", + "engineFrame": "32", + "worldTime": { + "numerator": "265740234375", + "denominator": "512" + }, + "mask": null, + "frame": "64768d7167e34d306ba9083bb1dc7e65e6123b634079787faa19d0ef3798de86", + "memory": "66278bc8057194b81bf22fad68280b50e5035a4d8a0c5233cb8f80d172fac2d9", + "wram": "fd666c21dabe652d5a961e8b85ff4c93367d5519f588d860fbb4ba1ccf549ea4", + "audio": null, + "state": "a92187ebda5a7ea77d82a40566678177b8e29208b61de01e2fb6e0fb569c690e" + }, + { + "index": 33, + "op": "advance", + "boundary": "32", + "engineFrame": "33", + "worldTime": { + "numerator": "8572265625", + "denominator": "16" + }, + "mask": 1, + "frame": "a050ca382016f826839cbe4c25040e24c8c225a254da33b943c7c92f6e4fc037", + "memory": "5d275d54f384b0e8d6c156b6aa0e739927ff4d5f4ed5db5d00edb6e519987231", + "wram": "00f25d551cb2d5eaa17851ecad457e19b5933308f447ad6d52f5c3c65cf97c81", + "audio": { + "firstSample": "24913", + "frames": 803, + "digest": "9e652e66d5af99bd92fa81e1397a99fc788cfcb859665a80c35bc3283d03acf0", + "discontinuity": false + }, + "state": null + }, + { + "index": 34, + "op": "advance", + "boundary": "33", + "engineFrame": "34", + "worldTime": { + "numerator": "282884765625", + "denominator": "512" + }, + "mask": 1, + "frame": "d8139b0db41c1f39c72be87e25a23b40472057aa93c737a3f8f66b269952fa1d", + "memory": "406c977effc02283c4d167cc3baf1433d2c485cbfb68aa58a24b70b746e7f3b6", + "wram": "5270455eb61d0ada3eaf41e3f6624614c49cc65c3fe8057953902e1935974b93", + "audio": { + "firstSample": "25716", + "frames": 804, + "digest": "ad4b3044606c12be195655ed248f78529d668244ff0eabd215ac189e45e75982", + "discontinuity": false + }, + "state": null + }, + { + "index": 35, + "op": "advance", + "boundary": "34", + "engineFrame": "35", + "worldTime": { + "numerator": "145728515625", + "denominator": "256" + }, + "mask": 1, + "frame": "9bbefd79b32433a4e8b0428da0459326afe7efdf010d3ced5d5a17d14d180fa0", + "memory": "f9329f7f5c8acfc9c63e7093fe8ba6eae6cbb41614b443e9614d321583ce9d82", + "wram": "1b43d2faf5682a9a74c185b96ae1a3e8cb8c4f55de26572171b97c0eb680b3c8", + "audio": { + "firstSample": "26520", + "frames": 804, + "digest": "f211c35083b190a5a48c2dd75b9070cefe484f254a3ace31bbcc4e81ac76e977", + "discontinuity": false + }, + "state": null + }, + { + "index": 36, + "op": "advance", + "boundary": "35", + "engineFrame": "36", + "worldTime": { + "numerator": "300029296875", + "denominator": "512" + }, + "mask": 1, + "frame": "bb6238215feb130d609fe9f7e78217861b2121ec4cfaee6f36ad64eac3dde799", + "memory": "1707d900ee1791df38fc543d999471a1e875f02e35dd2aab84fe0f60a259113e", + "wram": "bdeca712b01ffda68acd4a3a56f8bdf1494d030d06fb0f370d2fbd83eea8657b", + "audio": { + "firstSample": "27324", + "frames": 803, + "digest": "fb68b8c5c95d2fa32f459b682b52a0f771f9f3562d8af5e4bf99a797bdc8a2f1", + "discontinuity": false + }, + "state": null + }, + { + "index": 37, + "op": "advance", + "boundary": "36", + "engineFrame": "37", + "worldTime": { + "numerator": "77150390625", + "denominator": "128" + }, + "mask": 1, + "frame": "1af800af522b08b0e5a4b12e9f22d77b7def8b29ff1592d37c4b3e82fab2f0a6", + "memory": "a275f9f2107616b53ef374b55f170a2fb11ee8a717a89f084c424b3e03874feb", + "wram": "45acecb148b4a974cc16ff6f5c255274e749ddb9ff5b2916b2ac24a9ca87968d", + "audio": { + "firstSample": "28127", + "frames": 804, + "digest": "eabd869537112808adc0b427a1ea032ae012b07ecf478a025163fbcd23e8aca3", + "discontinuity": false + }, + "state": null + }, + { + "index": 38, + "op": "advance", + "boundary": "37", + "engineFrame": "38", + "worldTime": { + "numerator": "317173828125", + "denominator": "512" + }, + "mask": 1, + "frame": "c1ea74658fd50c82ff511669d69f2c138745c645e6e5e31cc73508bca41058e7", + "memory": "148b53b8b18330dc3d7ffb0472da0fbfc32bfc475a423a88d3c6c9531b2c7d5b", + "wram": "7878fcca297a5cdf853dd733bf4368851a70bcb411b976a6b41e19fd84cf0971", + "audio": { + "firstSample": "28931", + "frames": 804, + "digest": "88adc0fb2f75d8d9aec35afe3a76c9784f0a308b9bcd2acf473f14a7064c0f8b", + "discontinuity": false + }, + "state": null + }, + { + "index": 39, + "op": "advance", + "boundary": "38", + "engineFrame": "39", + "worldTime": { + "numerator": "162873046875", + "denominator": "256" + }, + "mask": 1, + "frame": "dfebb4ab61b3df55c695afc7f14ac2e046c4ae61c2177b7fe5d9121a0980dd47", + "memory": "c185bc0757179cd04306813047a56bfc6b07f0afdfc38bc9a6e20c9d0851555b", + "wram": "4746b44bb5f8888ea83e4eaa659244946afdb8c13e1bca1dcda3c743332be90c", + "audio": { + "firstSample": "29735", + "frames": 803, + "digest": "317678d9330c86d2d21bbb6ff9640311b244fb01c4a916b8dbf91bb9b48a552f", + "discontinuity": false + }, + "state": null + }, + { + "index": 40, + "op": "advance", + "boundary": "39", + "engineFrame": "40", + "worldTime": { + "numerator": "334318359375", + "denominator": "512" + }, + "mask": 1, + "frame": "26ca74ae737a7a9a789d7489aadc31f3c1b47b71ffced1d437a8250037a9b58f", + "memory": "4c51674b92bec2d50cf20c9813acf33cab686160aaec66e63ad04e476d6d619f", + "wram": "499a57c4a43835a1f5e4155b5fd01014a3a0576c74d2ca42a2f3a2004e7b4ef6", + "audio": { + "firstSample": "30538", + "frames": 804, + "digest": "00cb17fd1bdbbe0ee9ed166d36e9a3ff500bd73130dc51d6c9701cac57099046", + "discontinuity": false + }, + "state": null + }, + { + "index": 41, + "op": "advance", + "boundary": "40", + "engineFrame": "41", + "worldTime": { + "numerator": "42861328125", + "denominator": "64" + }, + "mask": 1, + "frame": "039e8af968520b3444adb52a93d624a8767a3d58b34bcdca7e60cf6c24ea4986", + "memory": "f2359b8d86682fe75379502de15da6f51a4ce2731b81dcb1207ce10dca4eda2d", + "wram": "515153bfe02a44731c6400a2fa08c1e2d7f24636daca798bcff160cbeb886212", + "audio": { + "firstSample": "31342", + "frames": 804, + "digest": "58d3219564d0f37b78dddc47256292eea6a38773b144d5f37aa5277fbd76899b", + "discontinuity": false + }, + "state": null + }, + { + "index": 42, + "op": "advance", + "boundary": "41", + "engineFrame": "42", + "worldTime": { + "numerator": "351462890625", + "denominator": "512" + }, + "mask": 1, + "frame": "18f4c2289b95e3fd6295569af945e328697f4197c8920adc3a10c084fbb53c56", + "memory": "218aa83c013bc59c1ffdbfac627a5bd4db9d3c21a57c35dc5be86f2cfcc05bc1", + "wram": "ff785c2649cd8bcfc8c02fa174f6408c44f97973a8b4b84a5f46ff9382751316", + "audio": { + "firstSample": "32146", + "frames": 803, + "digest": "32cbfff29f236651e5beaa3e45f98364d5953504daf3da652c89db5439d884e3", + "discontinuity": false + }, + "state": null + }, + { + "index": 43, + "op": "advance", + "boundary": "42", + "engineFrame": "43", + "worldTime": { + "numerator": "180017578125", + "denominator": "256" + }, + "mask": 1, + "frame": "200056b02ca588f5e40fa1ed7f050205e74d051518e9bf1b25450acfc5bf51ea", + "memory": "8da83def88cc25203d22b6b7c32d96b359e87ad295ed718c8dea7471034ce525", + "wram": "dec8114b939629fb3b4d99f87759c9f07dd80d235e8f67b7fe816b9b1f6e5bf9", + "audio": { + "firstSample": "32949", + "frames": 804, + "digest": "1932e97cff89034a85c0d5ff2ecea2ffe1208b5aac9daa72f5776ba856958d74", + "discontinuity": false + }, + "state": null + }, + { + "index": 44, + "op": "advance", + "boundary": "43", + "engineFrame": "44", + "worldTime": { + "numerator": "368607421875", + "denominator": "512" + }, + "mask": 1, + "frame": "2fcd46f1b520b7949e9063c4e4d74d781e3e906d6358e70fa5fd149bb0d19d06", + "memory": "1e937852c1df253d9f293c7a4762118dac2168fe50c214d1485699da39f37b7d", + "wram": "3cac711f86972c7bbcad5619e40898699336bfe7217f291bf8fe004921095ec1", + "audio": { + "firstSample": "33753", + "frames": 804, + "digest": "cfbaf05cdf2c153eaa4acb96626575b8b63e02eb39eb9cc98abde9b4a97359db", + "discontinuity": false + }, + "state": null + }, + { + "index": 45, + "op": "advance", + "boundary": "44", + "engineFrame": "45", + "worldTime": { + "numerator": "94294921875", + "denominator": "128" + }, + "mask": 1, + "frame": "8c9572abe7d6b4ce97bcffe58c3ea372a72ebeed778098e32eb41048edd8d560", + "memory": "c211c33fcabe25be04431be13bf3bbab36536926b4ead01bbb5df25bd10d9e88", + "wram": "be72108bb43518a7e13ea615bc641f6f5bdf7e3e81f438cf66808ac384dc16a9", + "audio": { + "firstSample": "34557", + "frames": 803, + "digest": "3d68f22866262054afa6a540633b5d3e4d41600700299f9901433e696a1a5d34", + "discontinuity": false + }, + "state": null + }, + { + "index": 46, + "op": "advance", + "boundary": "45", + "engineFrame": "46", + "worldTime": { + "numerator": "385751953125", + "denominator": "512" + }, + "mask": 1, + "frame": "7f22d8431f7c21182ec14bcf1bf4db85585074597797a0e08c981c0fc8b3f9a3", + "memory": "438ab1efda1aeb99fcf0a71c80db853929662e02b864300f8f5cffe0f6a5289f", + "wram": "67d93c6cc8c62481e281fa7538d518c27af6fc34d5027696553b19ab283d18b0", + "audio": { + "firstSample": "35360", + "frames": 804, + "digest": "7d411cc947545532c5d60b64498f20d4406bb2472dd6a6a149463c8288cbec53", + "discontinuity": false + }, + "state": null + }, + { + "index": 47, + "op": "advance", + "boundary": "46", + "engineFrame": "47", + "worldTime": { + "numerator": "197162109375", + "denominator": "256" + }, + "mask": 1, + "frame": "60b84b3d90588daa7fc7b319d1f107902214ce3c3e52381371dbf4284c10660d", + "memory": "4f178169e2da1879adadb1cbddc20994ea397c663b499b28b59002c65add2ecc", + "wram": "0d7dccaa4f517c91ddff224869a288d499f0be872da311ef075ba330af8f07fe", + "audio": { + "firstSample": "36164", + "frames": 804, + "digest": "7e1617cb92203a8aaf818567752d7142dc68fff2cd9cffb12ba3eae980cd9f70", + "discontinuity": false + }, + "state": null + }, + { + "index": 48, + "op": "advance", + "boundary": "47", + "engineFrame": "48", + "worldTime": { + "numerator": "402896484375", + "denominator": "512" + }, + "mask": 1, + "frame": "7f22d8431f7c21182ec14bcf1bf4db85585074597797a0e08c981c0fc8b3f9a3", + "memory": "894ebedfbda45b1dba2d6b5c81b94e9a04e48aa7e2ffd87fa6c28ed4b32fe035", + "wram": "56bee67b4adfa5818fc538f3bf68088312269d770ef8f934eba2920d52158894", + "audio": { + "firstSample": "36968", + "frames": 803, + "digest": "3cff5a6ac4aa0e0b53dc5dfb8a93210c7369b8a179d298f941d317440efddcaa", + "discontinuity": false + }, + "state": null + }, + { + "index": 49, + "op": "advance", + "boundary": "48", + "engineFrame": "49", + "worldTime": { + "numerator": "25716796875", + "denominator": "32" + }, + "mask": 1, + "frame": "60b84b3d90588daa7fc7b319d1f107902214ce3c3e52381371dbf4284c10660d", + "memory": "af4c44f77becce4ccc6034aa3f25512a1d24fe3b3cc4427cfbe94630afb52640", + "wram": "72afca59f6a4d06f404b7bbd4ac3373e88e22fa4a5f83eec73a59720be8c5db8", + "audio": { + "firstSample": "37771", + "frames": 804, + "digest": "20d60a7d7dafde50631c5b1b2d50080e2d788f5933e9c8ac0c8f29da566a76c6", + "discontinuity": false + }, + "state": null + }, + { + "index": 50, + "op": "advance", + "boundary": "49", + "engineFrame": "50", + "worldTime": { + "numerator": "420041015625", + "denominator": "512" + }, + "mask": 1, + "frame": "7f22d8431f7c21182ec14bcf1bf4db85585074597797a0e08c981c0fc8b3f9a3", + "memory": "9e2e3d03e59563156678868c6cb57a8780abfc74cd890107ee5f0cf499baae24", + "wram": "5e8b5a9fa3a836649e4846352b9b2585f897fbe2dccac9075de3d99af32bcb94", + "audio": { + "firstSample": "38575", + "frames": 804, + "digest": "eedba30e8e9fb2754d74d0d3fdf858a2d4be7ee91c48b001815c306461c3d1aa", + "discontinuity": false + }, + "state": null + }, + { + "index": 51, + "op": "advance", + "boundary": "50", + "engineFrame": "51", + "worldTime": { + "numerator": "214306640625", + "denominator": "256" + }, + "mask": 2, + "frame": "d4c715ee576697b4a4820bca4d01a5d292bd3e9478175662483fda6f091b9999", + "memory": "e1124940b076ecc25d12194b0368922d03960545adc775e245b368db86a00787", + "wram": "10d14d0058535ba7c18f1ebf9e7b04558eb1cea66aab83db471744c7e5598889", + "audio": { + "firstSample": "39379", + "frames": 803, + "digest": "5aa85922cb6719b9720fc03589081ad88367c523a3736eca6eb65fde1c83fd1f", + "discontinuity": false + }, + "state": null + }, + { + "index": 52, + "op": "advance", + "boundary": "51", + "engineFrame": "52", + "worldTime": { + "numerator": "437185546875", + "denominator": "512" + }, + "mask": 2, + "frame": "a4fb8fdb51c58b199452d45fe8176e69f17713c7fb5524852c18ec16829d21ac", + "memory": "c2fca8e9eac4df19fce34595191dc195b979ef65f09fbad5ee9bed857a2e1651", + "wram": "039b4a0d24cf31e79eece9ca6d227b349e3a01f1c77650ea2914ee187ed53c22", + "audio": { + "firstSample": "40182", + "frames": 804, + "digest": "1fd28d74bff7738e70d18bc33d8c5c7fd6bb0a1a4a9bc66238ddd0e615f34154", + "discontinuity": false + }, + "state": null + }, + { + "index": 53, + "op": "advance", + "boundary": "52", + "engineFrame": "53", + "worldTime": { + "numerator": "111439453125", + "denominator": "128" + }, + "mask": 2, + "frame": "59466412ed8adbe2da60d11091ef7e1b460a712c3964b734fe79d174b0509721", + "memory": "76c52e4789d89894ad01c70cfe7ee9adc28ace963583794222143668f63cf25c", + "wram": "c6ba1291867dcb23fc75dca9ad792ea4c733a277ca754536640ea9dad655399d", + "audio": { + "firstSample": "40986", + "frames": 803, + "digest": "3a1c19e0d6e224f00f74fe8c11f5d3857bcedd4f04bb98dc3e6ab66d3537db9f", + "discontinuity": false + }, + "state": null + }, + { + "index": 54, + "op": "advance", + "boundary": "53", + "engineFrame": "54", + "worldTime": { + "numerator": "454330078125", + "denominator": "512" + }, + "mask": 2, + "frame": "02f57878f15f64f4dbb64dce297ef8b666693162bc5cf635a2ec56d15bba24b7", + "memory": "4ea73a71b9e8b19a52b322879fd6337478cef829e20fbed8ce897189b447dc24", + "wram": "b0acb846630aafbe133e5ccb8a8e9861c071fb3efae5ae89fe34ceaeffdb9685", + "audio": { + "firstSample": "41789", + "frames": 804, + "digest": "6b75e18c8d11c23b04e4e84fdafa7f0ea56ed9a6e49625854a3d647dbd967be0", + "discontinuity": false + }, + "state": null + }, + { + "index": 55, + "op": "advance", + "boundary": "54", + "engineFrame": "55", + "worldTime": { + "numerator": "231451171875", + "denominator": "256" + }, + "mask": 2, + "frame": "cef6896edb6076ae9d0291bfc16ee62817d967d07d0c2a9619c36645f3518fc0", + "memory": "4e3c8512ae532c88c407780b197de6e55d47ed8b1c8d35bdae6af621b598e27a", + "wram": "8586e560e733fae81d454b2043542c46e8a9ec7d10ad6f8e1d45fde50a5fc3d9", + "audio": { + "firstSample": "42593", + "frames": 804, + "digest": "7788378e33ebacbd96a8b70344a1b806318634e572ebac7518cf2dfabb59e9bf", + "discontinuity": false + }, + "state": null + }, + { + "index": 56, + "op": "advance", + "boundary": "55", + "engineFrame": "56", + "worldTime": { + "numerator": "471474609375", + "denominator": "512" + }, + "mask": 2, + "frame": "cdc5b08a6e0b2da69e4fe9cd961ca73b2828809caadda13c9e127264e5374465", + "memory": "ff3a7adfa4a594720363868920cd4099ee7c84aa3d6c9613b3ca35e5f3b060c7", + "wram": "61e9cbe5eecb25d7a1961e82b7af0d23a0008cce1ea29d6bf2f8bc2facf1ec34", + "audio": { + "firstSample": "43397", + "frames": 803, + "digest": "07ff7aed5004ecf5ad4ec873babc9b11c34c0b3fbc8a702e599fb9f327969fa0", + "discontinuity": false + }, + "state": null + }, + { + "index": 57, + "op": "advance", + "boundary": "56", + "engineFrame": "57", + "worldTime": { + "numerator": "60005859375", + "denominator": "64" + }, + "mask": 2, + "frame": "f606666cc532cf8be17672bc1fd43ca7928b6d1ff5c54be611d0d4ae52ee1041", + "memory": "e056cb370d043e8ac70ad98cbaf906b4cd070749d57e31df6569d221f94e6bfc", + "wram": "2951398b9ca06155ca990b0d62a95fe7a73f4d92498a02a80c19d97d411e8a50", + "audio": { + "firstSample": "44200", + "frames": 804, + "digest": "970a7108de1a9dc7b554e85458fd0dc4549a38ebc293dff5115c9b997b84714c", + "discontinuity": false + }, + "state": null + }, + { + "index": 58, + "op": "advance", + "boundary": "57", + "engineFrame": "58", + "worldTime": { + "numerator": "488619140625", + "denominator": "512" + }, + "mask": 2, + "frame": "94ba53bf422817d8dc5b142a554366e3baa4ea20df596ba2a62f97e07769e89b", + "memory": "d0ace0c488606fb08861e20d1a80d6793624b5e8a84d985a523b07e3e84097bb", + "wram": "ffa2427f9f9dc3f3e2cede7aa31b2fe85d18871fc5443fa60bd2ff71d3c5815d", + "audio": { + "firstSample": "45004", + "frames": 804, + "digest": "2649c25e80850f9ce23e5740906e04160de143f917a4fb7403abc6e85ea1e5be", + "discontinuity": false + }, + "state": null + }, + { + "index": 59, + "op": "advance", + "boundary": "58", + "engineFrame": "59", + "worldTime": { + "numerator": "248595703125", + "denominator": "256" + }, + "mask": 2, + "frame": "918304a0428502b5c0aafd48e5f4c617351f72c39d95a9d857c1f48cc374eabd", + "memory": "c0ae9cf9c02951364044568268e71e0ba3d702dfa38d805a3d7dcb9be99d98f8", + "wram": "4ff4c74f1ca0c8665848ae57014f2ebe187bd84681619afdd43f6742705269b6", + "audio": { + "firstSample": "45808", + "frames": 803, + "digest": "49b275884c84d178613be73c2670d2626196c68bbcb6cd577f33879270eefc8a", + "discontinuity": false + }, + "state": null + }, + { + "index": 60, + "op": "advance", + "boundary": "59", + "engineFrame": "60", + "worldTime": { + "numerator": "505763671875", + "denominator": "512" + }, + "mask": 32, + "frame": "fff758141fce2432c52d471c1ea3d934bc7783d50fb1e1c06d3b4158373eb56b", + "memory": "7a05408993bdf68bd5cb8f384d458d5b1e329ab2379c321d94981d481afcce45", + "wram": "229c617d30d9ffad29b7d9546391cc07d50647a8e419afb434afbc7f8e082560", + "audio": { + "firstSample": "46611", + "frames": 804, + "digest": "f6abf425ee4f961a1f59c5f19e2200fe04f4b6ffc07ffd95a205cf78c1705138", + "discontinuity": false + }, + "state": null + }, + { + "index": 61, + "op": "advance", + "boundary": "60", + "engineFrame": "61", + "worldTime": { + "numerator": "128583984375", + "denominator": "128" + }, + "mask": 32, + "frame": "15677644545269f92cd30cfe2ea852717316221746cc2c803d23d76a3ef85a6d", + "memory": "a57a2ad6d523fb4cb7e6151b7fb5aa203809c08392cd8c29c313afaf76f5844a", + "wram": "6ecd448b6d3dc9477eb5507b8328d15032a32ea120dc75d40b9fff1f0e5a6c03", + "audio": { + "firstSample": "47415", + "frames": 804, + "digest": "5ddbd4b9571935219bb9003a94110d335d63c84ed568aa859149cb0a65329e0a", + "discontinuity": false + }, + "state": null + }, + { + "index": 62, + "op": "advance", + "boundary": "61", + "engineFrame": "62", + "worldTime": { + "numerator": "522908203125", + "denominator": "512" + }, + "mask": 32, + "frame": "e0777dce09d2b3f902ce43e5d560ef35e4fd4292f7caa185cc7366b44fdc5860", + "memory": "3148b27b8395ece513dc1971f37e8df5693b7d0122877ee04fa1845c0046a775", + "wram": "acb6c9b1338c426e45dd340355a61ceae16581fc2246215752c417f3c131f588", + "audio": { + "firstSample": "48219", + "frames": 803, + "digest": "bfa5a937a3e5c2997f864a1673aaad9843c47c44184ecbf97f6e5781963009c7", + "discontinuity": false + }, + "state": null + }, + { + "index": 63, + "op": "advance", + "boundary": "62", + "engineFrame": "63", + "worldTime": { + "numerator": "265740234375", + "denominator": "256" + }, + "mask": 32, + "frame": "1221b3e645e05869bd9fb35b5316f37b4307982bf1af683eb7c39af87f2a2967", + "memory": "eb208bb1c93b1c6e434777b70fee7692a4d46db4111c83030300875fd107f0b7", + "wram": "90fe2e842a21aba9d3f543342e31752278d902ff5ec5a97d74c048f0c8e3b804", + "audio": { + "firstSample": "49022", + "frames": 804, + "digest": "0b42a6d8c333c0e654b045047a00930273013a78e9921eb64d6e7cfb721065bf", + "discontinuity": false + }, + "state": null + }, + { + "index": 64, + "op": "advance", + "boundary": "63", + "engineFrame": "64", + "worldTime": { + "numerator": "540052734375", + "denominator": "512" + }, + "mask": 32, + "frame": "29ae4b3c474123931c1eaede26b60ca3bf1a43bfe6c892dcfc4b63020c80f336", + "memory": "abdfbc9f5b2f38d888c60c9244b6ed581dc367d24b2f9f1978066ac5a4857fb4", + "wram": "308c16046bdedfcb401396eba12c900d0439b096b1a14c7f928d483c6fca65a3", + "audio": { + "firstSample": "49826", + "frames": 804, + "digest": "b18741e06b07ec4a438539f3b98a6261798939cae33d0d837520e1e67c8fce9d", + "discontinuity": false + }, + "state": null + }, + { + "index": 65, + "op": "advance", + "boundary": "64", + "engineFrame": "65", + "worldTime": { + "numerator": "8572265625", + "denominator": "8" + }, + "mask": 32, + "frame": "0db81ebf53100bec4af3862a3dcf53afd3ad736e1ac7acb408f44d957469e999", + "memory": "44d13e8cfe3289effff0c5c9d376b511f6b8ef4e9cfaa370d60c1e364cc50319", + "wram": "5c8929e4a2ab28b74f441c6c4fd84defd107fed09923dd21dd1f346c7a8cbe97", + "audio": { + "firstSample": "50630", + "frames": 803, + "digest": "e716165669c63128f28c5a387d6901cb9a37f85b85b5f2f8f68db4c81dd9a659", + "discontinuity": false + }, + "state": null + }, + { + "index": 66, + "op": "advance", + "boundary": "65", + "engineFrame": "66", + "worldTime": { + "numerator": "557197265625", + "denominator": "512" + }, + "mask": 32, + "frame": "4d250a37833494955379cf48826c510b2a0cdf23eb0c00f71b9972fad25aedff", + "memory": "01ca84071eeb1201608cab606c659bdb7b14ae34a65918c2b7346cfb3d8f3280", + "wram": "fdf6fc94eea410530fdb560032dfdd292d22d627796bb81638dcace9f693ceba", + "audio": { + "firstSample": "51433", + "frames": 804, + "digest": "7c299662c8e60c477a1bcbfe9beafd1dd1c5f017b2cacbd652ae601a50c90cc3", + "discontinuity": false + }, + "state": null + }, + { + "index": 67, + "op": "advance", + "boundary": "66", + "engineFrame": "67", + "worldTime": { + "numerator": "282884765625", + "denominator": "256" + }, + "mask": 32, + "frame": "5882156c8cfc0a882eae507c6b9b0533f93b8113a698bc4a2577004e74e4c783", + "memory": "8c186ccb2838cd0bca8ca19dc8c97e7fac39715aa479eb9b9d38c55532f2c41c", + "wram": "2b471b93355842bc6ddca559956ca31ba81735f093a315fe18b66624774ee53f", + "audio": { + "firstSample": "52237", + "frames": 804, + "digest": "966530b70fafcd67c0702c4a1341df7046e2b40595583d6b83ba24afea75126c", + "discontinuity": false + }, + "state": null + }, + { + "index": 68, + "op": "advance", + "boundary": "67", + "engineFrame": "68", + "worldTime": { + "numerator": "574341796875", + "denominator": "512" + }, + "mask": 32, + "frame": "bf868c6b0804c3323c0ce6b47d0d4a30d8943c891e7f83b59ca14664b402fb9b", + "memory": "5c2d5d839fc5290d970dd358bd1e29221bb269591ead076e91fccd611394b724", + "wram": "3349831fa3bff77c82ce40e8c21307b60b91fdb2aef9821d39d3043afd960df8", + "audio": { + "firstSample": "53041", + "frames": 803, + "digest": "580423a592269e4b8b6b80b511f0863a0b537b7950375f8c27b424cc15a6f30b", + "discontinuity": false + }, + "state": null + }, + { + "index": 69, + "op": "advance", + "boundary": "68", + "engineFrame": "69", + "worldTime": { + "numerator": "145728515625", + "denominator": "128" + }, + "mask": 32, + "frame": "1513da252d2c50920d65848a905a028d6fdcc7c544c55dd8a16e0ff94b0de3b6", + "memory": "dd7de9442f2564558691fb0dd92c8637ff47b9fa53bc93821a08f8ffbac6d774", + "wram": "ad98163a1e70adaee793fc0071fbd1b454314c93fd3a05a2f165d4353884d0d1", + "audio": { + "firstSample": "53844", + "frames": 804, + "digest": "3897f02ea8bafae2cb6c4d50a824a2fd9d42b9f061b12d19fe71873100890b7e", + "discontinuity": false + }, + "state": null + }, + { + "index": 70, + "op": "advance", + "boundary": "69", + "engineFrame": "70", + "worldTime": { + "numerator": "591486328125", + "denominator": "512" + }, + "mask": 20, + "frame": "bd99a5fcf17c2892fff090db1a3280917dd4355be5bfc63550fa71a98f911e2b", + "memory": "4d41698270f59fe18f5b62d7dd5b98ee8584b311ba8b19efdc9d95bfa3e834e8", + "wram": "c727af123d968426d84c84d15fa86a582941c66d716fa581c538adb0221e8fc6", + "audio": { + "firstSample": "54648", + "frames": 804, + "digest": "aa5d0eb33e9e981b953deaca808ac1446daa05831f3e8bdd98b4cda616e04014", + "discontinuity": false + }, + "state": null + }, + { + "index": 71, + "op": "advance", + "boundary": "70", + "engineFrame": "71", + "worldTime": { + "numerator": "300029296875", + "denominator": "256" + }, + "mask": 20, + "frame": "2254a74263113c999f8fb23968f7a25925728d6da267fcdf19df725c9b9f6409", + "memory": "0f6aea4a29de9a24adc5e2c62903fcef827756e6f0165bae94ed5ee76208726e", + "wram": "914357fe6563d531bf6d8f49a03471e0b39a547f54543b272eee45a4b3b454f9", + "audio": { + "firstSample": "55452", + "frames": 803, + "digest": "6e8465c9e38ed37bfce1ce933d9776dfb35a24bba9493eaa70fa95a750b07058", + "discontinuity": false + }, + "state": null + }, + { + "index": 72, + "op": "advance", + "boundary": "71", + "engineFrame": "72", + "worldTime": { + "numerator": "608630859375", + "denominator": "512" + }, + "mask": 20, + "frame": "fe296bd399c71d25516fd32fd21de38c26b9fdd738e8057210dffa915383a9f7", + "memory": "c74f050abd80d6566755dbd343ef8fece5631da1f1c2ad43afa364762bd582e7", + "wram": "926cefe3cbcc066e32a5bc7f6163e9134fc168edead57abe4514778035dc28c7", + "audio": { + "firstSample": "56255", + "frames": 804, + "digest": "3e0bf8c60822b177e7a0e7b80e5cb84d0d5aa1ff2cd8859cf39403b0b035c8ff", + "discontinuity": false + }, + "state": null + }, + { + "index": 73, + "op": "advance", + "boundary": "72", + "engineFrame": "73", + "worldTime": { + "numerator": "77150390625", + "denominator": "64" + }, + "mask": 20, + "frame": "b271a7a59f177591a8b2c6e59b4b60af9f96322b149d2e20d8b0af640b6b75ef", + "memory": "62beec6ed310d053d1f551aaf39173b9c0bfc95a739feb6093166041f126704f", + "wram": "9d50789b14c199c929b81224697ac367ac4f1afed5d74e4213b512bd3a045ce7", + "audio": { + "firstSample": "57059", + "frames": 803, + "digest": "34998a2e7a86a7e937a7fa9857b66b926723a999fca8c8f969b5ed7b7a5db1c5", + "discontinuity": false + }, + "state": null + }, + { + "index": 74, + "op": "advance", + "boundary": "73", + "engineFrame": "74", + "worldTime": { + "numerator": "625775390625", + "denominator": "512" + }, + "mask": 20, + "frame": "94f44b0ec7dc130be97b3bc24bc312229fcce89f4c95f1a309d0e455cf70b9ab", + "memory": "0e4596fcc489f532f4b0d95cd3fc6cc88d5ef84b75e4955d6beea76d85836fb7", + "wram": "1ed1ebf12e5c6d0b95252df02eb1b2db74bb25379bced1b43f7b2329e3b45d9d", + "audio": { + "firstSample": "57862", + "frames": 804, + "digest": "bfe12c81279cab0bc80cec788f66c4530534dc7e2d7c8279669023dd2462990d", + "discontinuity": false + }, + "state": null + }, + { + "index": 75, + "op": "advance", + "boundary": "74", + "engineFrame": "75", + "worldTime": { + "numerator": "317173828125", + "denominator": "256" + }, + "mask": 20, + "frame": "c00087978e31a8f87b88aca80ca87c43937ea4cc2cd438d464603e4a3d5a2192", + "memory": "be1bd1620fa8aa30f610b6b0d8d8c02ddd82f08272c6db68eb820cb130207415", + "wram": "2b46f3060c9df31241e15743e16c46c603b26f93b1a0ceb2023aab5076d0bd76", + "audio": { + "firstSample": "58666", + "frames": 804, + "digest": "064f977956e6ecb9229d03a9000ca4c8bcfe791d7c24571b813bdea838c0c4b7", + "discontinuity": false + }, + "state": null + }, + { + "index": 76, + "op": "advance", + "boundary": "75", + "engineFrame": "76", + "worldTime": { + "numerator": "642919921875", + "denominator": "512" + }, + "mask": 20, + "frame": "86db5e819c85c9122f7399a39a4fb377f8ae7d77bca3428b16d8c9b584fd7e05", + "memory": "45b8f84dc1be5177d2d87dedc4080091d55acc53c0c46850832eebc34b820af5", + "wram": "13c3194703d58a23bca6d3954e8fe6e97e72ff7fdfaba14302fc0bd15a2dad2c", + "audio": { + "firstSample": "59470", + "frames": 803, + "digest": "86540831af57c98b92bb656575e9e1a65ff7053e951bc4f835742dd7d81a9279", + "discontinuity": false + }, + "state": null + }, + { + "index": 77, + "op": "advance", + "boundary": "76", + "engineFrame": "77", + "worldTime": { + "numerator": "162873046875", + "denominator": "128" + }, + "mask": 20, + "frame": "9eb66851792fce5daf4f13d2db560445cc824cc5ded6498acf7406bdb41c692f", + "memory": "c6abf076e455984df387194fcb6a576af3fbdc2798a83b4c4bcf82c7a392fa00", + "wram": "bae05a83c6b576e97b97a948e8b33383b3c839e8656f1a08c46e76225b7d833c", + "audio": { + "firstSample": "60273", + "frames": 804, + "digest": "b54181adce480b2b8aab95ac9d87194ab5ed8c9503b093d20c73226b947b2644", + "discontinuity": false + }, + "state": null + }, + { + "index": 78, + "op": "advance", + "boundary": "77", + "engineFrame": "78", + "worldTime": { + "numerator": "660064453125", + "denominator": "512" + }, + "mask": 20, + "frame": "8f19aa8bd0bdbe67a990d40012572411c0afbbefa63f41ca9832977ea5546095", + "memory": "648f1e11ce55415b8fa6f29d2d47b0a1a9fc9acbbcec4d1e839b610de1fc9d07", + "wram": "15a97ba1c7a266110fe273d277857af115e037eee1839c321a33b7572fd29033", + "audio": { + "firstSample": "61077", + "frames": 804, + "digest": "4270810d1077e482ed828374858afd72330e29edae89f271785c5ae9bfba1b03", + "discontinuity": false + }, + "state": null + }, + { + "index": 79, + "op": "advance", + "boundary": "78", + "engineFrame": "79", + "worldTime": { + "numerator": "334318359375", + "denominator": "256" + }, + "mask": 20, + "frame": "ba1656c2c20fd461a15a422031b4708584ed391a44a771379f462fa0cf9a34ee", + "memory": "60b0f6b38ddc0addde4ec2ed32a6be810fc2b06b90214dc85aa8a9ed45d6a8d3", + "wram": "1bfb81ddc750ff932e7abbb00d697ae978088179f910d56af9bb105d44b8cb7f", + "audio": { + "firstSample": "61881", + "frames": 803, + "digest": "d7961c8d954250a46fa7489322fec8374f9dd89f80785f8b7139cad0c123416d", + "discontinuity": false + }, + "state": null + }, + { + "index": 80, + "op": "advance", + "boundary": "79", + "engineFrame": "80", + "worldTime": { + "numerator": "677208984375", + "denominator": "512" + }, + "mask": 20, + "frame": "0a2037e89376b7a5989b04e4c2fabcd80cb3452eb5be9c589258455b0095e253", + "memory": "da78d6565d9b5e249de2ae3ed3b87ba2171e8aa822323d0c2c3bfb51a45555a4", + "wram": "993d3c2a0a9279e30a5f90c34a58c04f242898712569ee1104f655e024e5440c", + "audio": { + "firstSample": "62684", + "frames": 804, + "digest": "ccaaed0253befbde98e63209d4023ee1b61bd1abf0d599ede4ca7ba1720990b4", + "discontinuity": false + }, + "state": null + }, + { + "index": 81, + "op": "advance", + "boundary": "80", + "engineFrame": "81", + "worldTime": { + "numerator": "42861328125", + "denominator": "32" + }, + "mask": 20, + "frame": "62285807ba56f3d33805d75acd53fba78005f7f2a47b52195c99d5a97bb6d88a", + "memory": "ecc8dfb02e1b61df188cfdac51ab6d71bbd7c2d5301f868ec334269e652986b0", + "wram": "e68eb2211c9c184148e9f655ccfdfc10cde1a8c23dfeede9c43a85df277a9d27", + "audio": { + "firstSample": "63488", + "frames": 804, + "digest": "d7fba9fba28c84d0290ecb814fd092247d601aac95c4f8c8e356f74aa763f114", + "discontinuity": false + }, + "state": null + }, + { + "index": 82, + "op": "advance", + "boundary": "81", + "engineFrame": "82", + "worldTime": { + "numerator": "694353515625", + "denominator": "512" + }, + "mask": 20, + "frame": "ae38a20fe906437541241276c612fb4ce067be783f02ca4ab32252c0de4d1d76", + "memory": "337d763e3dfb080ca0d5f8d6a93db841443eb33e17a18fc951e7ebde495abb2a", + "wram": "c08b1a05d9138ea71788add2071e1d8d4e2e2461bc6d1eae451f0e96d966ba2b", + "audio": { + "firstSample": "64292", + "frames": 803, + "digest": "ebae567257556b6710677dcaeba474b6c1e782ba81206a0f320c4cf48f708811", + "discontinuity": false + }, + "state": null + }, + { + "index": 83, + "op": "advance", + "boundary": "82", + "engineFrame": "83", + "worldTime": { + "numerator": "351462890625", + "denominator": "256" + }, + "mask": 20, + "frame": "60a8c224d4b27f0a444413b3b3df048da39b792378b125dabd1aad6875c2a167", + "memory": "69d7f4289fca72bf18d372aea4c54a2e9292da7abf8974c473cf61a2dd4391ea", + "wram": "466867c2dded8e78e68cb354e35e0ba624622f57464c932676268544551d5ecc", + "audio": { + "firstSample": "65095", + "frames": 804, + "digest": "ff276fa90c7bacd71f3952ac45b7334d51446d9f486207965313dcada9664a8a", + "discontinuity": false + }, + "state": null + }, + { + "index": 84, + "op": "advance", + "boundary": "83", + "engineFrame": "84", + "worldTime": { + "numerator": "711498046875", + "denominator": "512" + }, + "mask": 20, + "frame": "2e932f1dbb6e50bc5a2066087a9aa13a9d3f5b5d12ad57a670493881a30a1631", + "memory": "e2ca76243bd003afc9ff34f9e6190c6b84ca88067a57c39a75416bf53819757c", + "wram": "568a7415214043f00a59f4b9046cee3a5b4e7730f6be02c0adc1ce93a517f5ca", + "audio": { + "firstSample": "65899", + "frames": 804, + "digest": "aefac76e15751791e4f33013e36d9441ea5ad303987aaa2e08658add0acc23ba", + "discontinuity": false + }, + "state": null + }, + { + "index": 85, + "op": "advance", + "boundary": "84", + "engineFrame": "85", + "worldTime": { + "numerator": "180017578125", + "denominator": "128" + }, + "mask": 20, + "frame": "8fff969b08bf57e097cffb8f5432e2f19aed168812905b6dea868720c8f38728", + "memory": "252fb9357c1428bd0d7f3f51745e99efba716996404b5b863ca702c944da3f38", + "wram": "2c22c48f4d47705dc072c2f70b158a9260c6a3772b33ca347ba39c6790782b8c", + "audio": { + "firstSample": "66703", + "frames": 803, + "digest": "a204face53ae2a8e36400fd5c72917e82c3fe91bf10d65fade03f3d9b350fd7c", + "discontinuity": false + }, + "state": null + }, + { + "index": 86, + "op": "advance", + "boundary": "85", + "engineFrame": "86", + "worldTime": { + "numerator": "728642578125", + "denominator": "512" + }, + "mask": 20, + "frame": "97959e848da5f9cf084b147986a65e58cc8f53746a7c9ca85738ebe3ef46d2d8", + "memory": "696e70bc7b8beffb34e10dd8ba8e265a4bc9bbe7bd2f5946042b2ef4cd3e6b99", + "wram": "b4efcc1054310f917cb0238ad7e79ac2f1450f07ce8ad216875682d2c3151f0b", + "audio": { + "firstSample": "67506", + "frames": 804, + "digest": "2c45d37b81da5b1d653e2096b98522cef6fa293aaa13b99ab0bfe3916f7a60e2", + "discontinuity": false + }, + "state": null + }, + { + "index": 87, + "op": "advance", + "boundary": "86", + "engineFrame": "87", + "worldTime": { + "numerator": "368607421875", + "denominator": "256" + }, + "mask": 20, + "frame": "ab054f1211fc9cd7156ae7ca53d59f33ce5086d33a8cd964adfd0e8fb356f287", + "memory": "d4cb195d8e2bef02be972ac03cfaadab85e6ac2db711bd541b7af7dd59c837b1", + "wram": "1fabe0679663fe3afed28e186126606dfd310d51c22a7070f55cd4941724a1fe", + "audio": { + "firstSample": "68310", + "frames": 804, + "digest": "9623758ae4668323d9330e48548413c01f1cf75cae1678d82ea688a1013f2946", + "discontinuity": false + }, + "state": null + }, + { + "index": 88, + "op": "advance", + "boundary": "87", + "engineFrame": "88", + "worldTime": { + "numerator": "745787109375", + "denominator": "512" + }, + "mask": 1, + "frame": "1efe9b02b9dc66a69207c7e8c2529c4d2127ab9fd4e09e16c8c9c1656c2a3d27", + "memory": "76e5fe26ae4f904f54df70b740fc1954b7209518a80263e0e403820388f650fe", + "wram": "9573a5ef1e3ceb8066909e10810d47b32a7a611d81b9d4c845c965ee1b18d1c7", + "audio": { + "firstSample": "69114", + "frames": 803, + "digest": "aaf200e1e6fcf00c270aad5b7fb53afce36fcb27b62a396f4cf04bbc2b59250c", + "discontinuity": false + }, + "state": null + }, + { + "index": 89, + "op": "advance", + "boundary": "88", + "engineFrame": "89", + "worldTime": { + "numerator": "94294921875", + "denominator": "64" + }, + "mask": 1, + "frame": "bd2a22aa0f38308dd76e14102fc987dc85fc9a8e24569c6511313fa96295bca4", + "memory": "3a1c409456ca98b99a05ae6fbd33b01593191e48ff06a99e38dd57d3ffa28f11", + "wram": "20b68949965c022d450a0543c15ed56a5f71243d1a4958070afea7d1832a662e", + "audio": { + "firstSample": "69917", + "frames": 804, + "digest": "eea21ff75b390ec28306eb65f9f59acf7cb721812f96f4b150ea00b3ded492c0", + "discontinuity": false + }, + "state": null + }, + { + "index": 90, + "op": "advance", + "boundary": "89", + "engineFrame": "90", + "worldTime": { + "numerator": "762931640625", + "denominator": "512" + }, + "mask": 1, + "frame": "64f577029bc0a1662682f3aaebd6a38c50293b23f67c45c15eb51f3141158860", + "memory": "1be4e63892f827f2e4af84330e1eb2884ff7109f616a68089f61091731112b2e", + "wram": "9e3df7942d9ab22092b212c2b8a120111120bcbb9776f4d5d132470982dc1969", + "audio": { + "firstSample": "70721", + "frames": 803, + "digest": "e88b09017a673add6c12ca5e252342423cb67e9fd714a3ad51d520be40c092e8", + "discontinuity": false + }, + "state": null + }, + { + "index": 91, + "op": "advance", + "boundary": "90", + "engineFrame": "91", + "worldTime": { + "numerator": "385751953125", + "denominator": "256" + }, + "mask": 1, + "frame": "c47ad1b65520de092657d1d9f430db280c734c9233812eb9572b25f94196bd66", + "memory": "e142e7ec244eb0b9556a4f40c2902d181fb2915cf2cff870f6b52f85500b50d1", + "wram": "31a922f6a8eae12a21de93eae820d1882858895978f73c38e3ae054159877c3e", + "audio": { + "firstSample": "71524", + "frames": 804, + "digest": "48f74f86221d5498af12557c8287865f972e4e57e3396f12de286655f5c458de", + "discontinuity": false + }, + "state": null + }, + { + "index": 92, + "op": "advance", + "boundary": "91", + "engineFrame": "92", + "worldTime": { + "numerator": "780076171875", + "denominator": "512" + }, + "mask": 1, + "frame": "b3932485be7c2a61d3d30e1d8a0f68ce3ced806dc20e2f6c0457dc595264d3cf", + "memory": "66fdb61a6af5eec2d8810dac27ae8bd863e3ef3ec4930257e3c6b7c7a8ca4a31", + "wram": "f3fc8a77841f77675a1dfcdd952629eadfa59c4a0111170272da632492eef3dd", + "audio": { + "firstSample": "72328", + "frames": 804, + "digest": "688a260c694075061aa034e89d0c59b05520858ddf7d8b8874c4928246a83c2a", + "discontinuity": false + }, + "state": null + }, + { + "index": 93, + "op": "rollback", + "boundary": "91", + "engineFrame": "92", + "worldTime": { + "numerator": "780076171875", + "denominator": "512" + }, + "mask": null, + "frame": "64768d7167e34d306ba9083bb1dc7e65e6123b634079787faa19d0ef3798de86", + "memory": "66278bc8057194b81bf22fad68280b50e5035a4d8a0c5233cb8f80d172fac2d9", + "wram": "fd666c21dabe652d5a961e8b85ff4c93367d5519f588d860fbb4ba1ccf549ea4", + "audio": null, + "state": null + }, + { + "index": 94, + "op": "advance", + "boundary": "92", + "engineFrame": "93", + "worldTime": { + "numerator": "197162109375", + "denominator": "128" + }, + "mask": 1, + "frame": "a050ca382016f826839cbe4c25040e24c8c225a254da33b943c7c92f6e4fc037", + "memory": "5d275d54f384b0e8d6c156b6aa0e739927ff4d5f4ed5db5d00edb6e519987231", + "wram": "00f25d551cb2d5eaa17851ecad457e19b5933308f447ad6d52f5c3c65cf97c81", + "audio": { + "firstSample": "73132", + "frames": 803, + "digest": "c512fd3b011093e7e63eba2b6731b070c4db7f705dde422f8dceeccc8e0a2122", + "discontinuity": true + }, + "state": null + }, + { + "index": 95, + "op": "advance", + "boundary": "93", + "engineFrame": "94", + "worldTime": { + "numerator": "797220703125", + "denominator": "512" + }, + "mask": 1, + "frame": "d8139b0db41c1f39c72be87e25a23b40472057aa93c737a3f8f66b269952fa1d", + "memory": "406c977effc02283c4d167cc3baf1433d2c485cbfb68aa58a24b70b746e7f3b6", + "wram": "5270455eb61d0ada3eaf41e3f6624614c49cc65c3fe8057953902e1935974b93", + "audio": { + "firstSample": "73935", + "frames": 804, + "digest": "ef1e16b1ed6dff5e22c0134f0789f2fbc298d0483a7b3ff2f42eb764390a6249", + "discontinuity": false + }, + "state": null + }, + { + "index": 96, + "op": "advance", + "boundary": "94", + "engineFrame": "95", + "worldTime": { + "numerator": "402896484375", + "denominator": "256" + }, + "mask": 1, + "frame": "9bbefd79b32433a4e8b0428da0459326afe7efdf010d3ced5d5a17d14d180fa0", + "memory": "f9329f7f5c8acfc9c63e7093fe8ba6eae6cbb41614b443e9614d321583ce9d82", + "wram": "1b43d2faf5682a9a74c185b96ae1a3e8cb8c4f55de26572171b97c0eb680b3c8", + "audio": { + "firstSample": "74739", + "frames": 804, + "digest": "090b5ac661f87c6b9cdc88071bd97193db757a8a58df086edd63ac04f45a8eed", + "discontinuity": false + }, + "state": null + }, + { + "index": 97, + "op": "advance", + "boundary": "95", + "engineFrame": "96", + "worldTime": { + "numerator": "814365234375", + "denominator": "512" + }, + "mask": 2, + "frame": "13edd4761d31e910ae1c9c7b7bc9050074d5bb82ae02f0ae4d7ebd8e3d4f88c1", + "memory": "45ef81b1e29cbb26f62558a400ab69940971febdb196d0e04bbb8171de5715f5", + "wram": "432819e20364e12af5f53f48feeaa144540f82d299b15fd785b4a7027253ff13", + "audio": { + "firstSample": "75543", + "frames": 803, + "digest": "d85d6796c3870b7a485a464bbe9a74e8b92a5c4f9fd3a238d57ff594d9353996", + "discontinuity": false + }, + "state": null + }, + { + "index": 98, + "op": "advance", + "boundary": "96", + "engineFrame": "97", + "worldTime": { + "numerator": "25716796875", + "denominator": "16" + }, + "mask": 2, + "frame": "05e1b148120b5aff1b54bb9bca27b5a9a54ccf18ba01e0a13e70b40ec74edcc3", + "memory": "72aa2ed99abbdc493657b1d7828d7cae0c006ce038fdb74c0c9d15c0d671534a", + "wram": "a0c7e35457b8acbeb32ecb963a09104d624915eaacf18958c5d5fecc9ca6eee2", + "audio": { + "firstSample": "76346", + "frames": 804, + "digest": "8df95a14944c844c3e3c17cce8274fa89174740bec9b63d397791c7388a50e8f", + "discontinuity": false + }, + "state": null + }, + { + "index": 99, + "op": "advance", + "boundary": "97", + "engineFrame": "98", + "worldTime": { + "numerator": "831509765625", + "denominator": "512" + }, + "mask": 2, + "frame": "11930e74f515e54416d1b06fed058fb8a945b1d83f17770dd9a117612b097ac1", + "memory": "8375151d48e84336c1c6b611815b39f11423a7005cbf43c44096475043239c41", + "wram": "99ec77578a5c0b4aaab2edc2f4c04b392b88d4943fb66f60dcb9e843e9e4f94f", + "audio": { + "firstSample": "77150", + "frames": 804, + "digest": "fec5f924386ee95a7415623f1add3a400ef368af26f391a0157f2282100bce67", + "discontinuity": false + }, + "state": null + }, + { + "index": 100, + "op": "advance", + "boundary": "98", + "engineFrame": "99", + "worldTime": { + "numerator": "420041015625", + "denominator": "256" + }, + "mask": 2, + "frame": "f3a9b39efd9da389c8c4670f8c9417adb7134e1203dec8c31698ec9c8b0725da", + "memory": "6677b64d777e6f32eda1021d921a42d6cf732654f65efb50417f9a612540e28b", + "wram": "c3a2d9ec0203289d78bc18143dbcb879a13996f87355364473d04e7e976051d0", + "audio": { + "firstSample": "77954", + "frames": 803, + "digest": "33ecb3b830725fe0c9e2be763d11a6ef43ed140ca7a1c15cd51d2bd21b54fca3", + "discontinuity": false + }, + "state": null + }, + { + "index": 101, + "op": "advance", + "boundary": "99", + "engineFrame": "100", + "worldTime": { + "numerator": "848654296875", + "denominator": "512" + }, + "mask": 2, + "frame": "297ec4e8d6bb142ca1afb7e84e0966c183286c82e896bffe769fe4759bad9bd6", + "memory": "5d70214b207a2fc6ff4ebefb444354aeddc93106f6c8445da3d3297d636dd3f5", + "wram": "5a9deb34b6a73eb49245b091dcf79ea351cab2068272841ad044c77913b3867d", + "audio": { + "firstSample": "78757", + "frames": 804, + "digest": "bd1587e1ec6ed5634fd939c4324a895c1b2633958d16837ade9e64a0c5bd1884", + "discontinuity": false + }, + "state": null + }, + { + "index": 102, + "op": "advance", + "boundary": "100", + "engineFrame": "101", + "worldTime": { + "numerator": "214306640625", + "denominator": "128" + }, + "mask": 2, + "frame": "9b4a0ceba85861be44628384b3a20a449ef5a444b9d5635d9f36f534484b1369", + "memory": "022a211088d454bfbce043ab96fd4fa4ca7315af6f9b062ed6da563b67c942c3", + "wram": "78c6093b304f15c8201f37114348baefbc54808939c0f5268232e291541b0295", + "audio": { + "firstSample": "79561", + "frames": 803, + "digest": "6428acc97d8a7dc3247f28bbebb46d5490f51533ab1234f6ea85ac753fe98383", + "discontinuity": false + }, + "state": null + }, + { + "index": 103, + "op": "advance", + "boundary": "101", + "engineFrame": "102", + "worldTime": { + "numerator": "865798828125", + "denominator": "512" + }, + "mask": 2, + "frame": "79125cfff561c5d7ecc107d2477e80f1b2fe6dae15a9f2723ba339869eae9866", + "memory": "a324936006022c915029f2d135a9c6b3e1c05c14870637045da6dc4d7fb36c16", + "wram": "efd42aac00968f22f1034de5539d966ccc0ea102baadd3c037cd7d729f847dd5", + "audio": { + "firstSample": "80364", + "frames": 804, + "digest": "7b9544cb038bc8c4094408d94b2809237942809411ec2e12e9add722c12ee0a4", + "discontinuity": false + }, + "state": null + }, + { + "index": 104, + "op": "advance", + "boundary": "102", + "engineFrame": "103", + "worldTime": { + "numerator": "437185546875", + "denominator": "256" + }, + "mask": 2, + "frame": "1a6dbc6daaad597c3b0e3b7776dc2e4198a1df4e6a344376a97b14bf290366e2", + "memory": "2d4904fafe23818baa196edf49576a87cae333a277edbcf167fa0287e3b029f5", + "wram": "14ed197c70ca361faf758f655373e0a96ceddaf1cb50d96af75a148b893968e5", + "audio": { + "firstSample": "81168", + "frames": 804, + "digest": "0c73f234e5ffc390a725402e19fa675ee3012776d75407dbfd0be849f52a8be6", + "discontinuity": false + }, + "state": null + }, + { + "index": 105, + "op": "advance", + "boundary": "103", + "engineFrame": "104", + "worldTime": { + "numerator": "882943359375", + "denominator": "512" + }, + "mask": 2, + "frame": "6a3acc16cdbe2c78dfea0d0bb1a4bbd12e1c7eb9e23ce44dffb524662a329972", + "memory": "589763e10d843e7303eaba1ac2ac2f234d3c51d06652e9ad886a84bc36b24ae1", + "wram": "6b6932a48ac08ff524df4c1e220920f7725a24bdbdac387e5b4d076e21bf4924", + "audio": { + "firstSample": "81972", + "frames": 803, + "digest": "ecadea8ff12d1ee90b7d4b0d89002bedde69b75b9a472492457b38223f201829", + "discontinuity": false + }, + "state": null + }, + { + "index": 106, + "op": "advance", + "boundary": "104", + "engineFrame": "105", + "worldTime": { + "numerator": "111439453125", + "denominator": "64" + }, + "mask": 2, + "frame": "d92786aebd34ea7c95d581feb55571b0841165df66e68e3e046e24b4d0af02e0", + "memory": "7db1b193501843a11d3160a939ad0d5842859f612eeda0d088add4ad0367b184", + "wram": "2a481482f2fc57000619bb93d0b9d468de30f8356249da9bb89ee47b7f399d96", + "audio": { + "firstSample": "82775", + "frames": 804, + "digest": "75bc8dfb5d00b0910538123b0d0d4e96cbefa6b1e66630d69390faec7ddcf6c5", + "discontinuity": false + }, + "state": null + }, + { + "index": 107, + "op": "advance", + "boundary": "105", + "engineFrame": "106", + "worldTime": { + "numerator": "900087890625", + "denominator": "512" + }, + "mask": 2, + "frame": "4ccd7cbe5d64fb10b904ce3d13b951bec9b603d02ff9df414d6aaa0e38ec936e", + "memory": "1988a18765fbb07694b9f3f46272e4a59416c4a6f293c90aa18711af07ff412b", + "wram": "54f0d9527cf9b5d6d3cd0013690bf5c2e661fe5179bd3852ea52a1825fd6bcf9", + "audio": { + "firstSample": "83579", + "frames": 804, + "digest": "e87ca8faf6a461ac1b6e0d72e52ac6aa3cabfc2ff53bdf40d0efcc8695016bd0", + "discontinuity": false + }, + "state": null + }, + { + "index": 108, + "op": "advance", + "boundary": "106", + "engineFrame": "107", + "worldTime": { + "numerator": "454330078125", + "denominator": "256" + }, + "mask": 2, + "frame": "cceb4a06c70ab88f3c26612b867d23916adbb6bc4eee4e1946dbddda31485c4a", + "memory": "81e36bf108b4cc4b9e964fc5f48b74fc33e7e85c28b637336eea085291b9046c", + "wram": "041dddc5d9a79fe68f9a1d26e34f6fcb9aa697beae42025d03f73a1d5c223482", + "audio": { + "firstSample": "84383", + "frames": 803, + "digest": "5cb6ac13eae15a9096f60e0d51ac5de4f2b87a48196ace3b45e335f9029d4d96", + "discontinuity": false + }, + "state": null + }, + { + "index": 109, + "op": "advance", + "boundary": "107", + "engineFrame": "108", + "worldTime": { + "numerator": "917232421875", + "denominator": "512" + }, + "mask": 2, + "frame": "187b7fa1af9f93756b1fd218095aae84db62b8f59d11826843a30c61971b646e", + "memory": "3ef3f23cfa39cb640ae1992f963329cb0a14e84fbe392bd0b9dadc91d1ebc6d8", + "wram": "996d2b1506bc23aaca250af34150396376d4ba5592a0781cd68070265b134fb7", + "audio": { + "firstSample": "85186", + "frames": 804, + "digest": "f914ca15059e46ebf92f889b9955e076d35b70c447870b0984782ee9937d4f05", + "discontinuity": false + }, + "state": null + }, + { + "index": 110, + "op": "advance", + "boundary": "108", + "engineFrame": "109", + "worldTime": { + "numerator": "231451171875", + "denominator": "128" + }, + "mask": 0, + "frame": "4dd179e5822678033fab2e35fa8b4bc0f3b581c54a42d7e8f6eb270fd7634f45", + "memory": "46cdad61b11ab57b31c70127d426999cdaa8bb2eb3f6569c490ec310cf79cba2", + "wram": "ab651131088f592d62dcf426c4a7f1f85219ff4c4471dd4c72f6c3fc2c1ce7cf", + "audio": { + "firstSample": "85990", + "frames": 804, + "digest": "898aa6ba07d05b63e3cc9da9722bc6949890db422980a8382491304e572b30dd", + "discontinuity": false + }, + "state": null + }, + { + "index": 111, + "op": "advance", + "boundary": "109", + "engineFrame": "110", + "worldTime": { + "numerator": "934376953125", + "denominator": "512" + }, + "mask": 0, + "frame": "473ac086638974777ee5288fcbaaff865b9f493805bc183ee95ea8cff55ea758", + "memory": "24488e509013a8aa2eac1cd7baff5367df14eca39cad87cf21ea4a57be10bdad", + "wram": "c1b67ded2a74f6e2154f0b9fc47ec451aa743c82642b5af11605adb6bcdd815c", + "audio": { + "firstSample": "86794", + "frames": 803, + "digest": "f12ffa021a8f9acf48ebcd521be053348fc4466337ff5fc5ac8d7afefb81944e", + "discontinuity": false + }, + "state": null + }, + { + "index": 112, + "op": "advance", + "boundary": "110", + "engineFrame": "111", + "worldTime": { + "numerator": "471474609375", + "denominator": "256" + }, + "mask": 0, + "frame": "88da2958f9061fd1a4f5f89bd6545dcf0096162361168c1c420ea26ab9f33f34", + "memory": "b900d2cfed0ff71cdc41f5e6600ce1f7609cc5ae79404abd9a2d52e1614d969e", + "wram": "866a7ffece680753602470757c6adde2f3c3dc460398dcddd03053c38003bb66", + "audio": { + "firstSample": "87597", + "frames": 804, + "digest": "0b6dd0dec19a72d7737acbac1d154a16a595c1b346f0ce0c5bc9940a44b7b465", + "discontinuity": false + }, + "state": null + }, + { + "index": 113, + "op": "advance", + "boundary": "111", + "engineFrame": "112", + "worldTime": { + "numerator": "951521484375", + "denominator": "512" + }, + "mask": 0, + "frame": "292d6d4254750b04c6390442c59a2582956c66fae1597966aa62f7348d76693c", + "memory": "62ea644b9b68538060534b32b3a6fd3f9ade8017722acd8e5fdc926a7a286c6c", + "wram": "d1bd4acd3eadf4c127b0d91f180f2918315df0d7625817123564e4a4fe8b74c6", + "audio": { + "firstSample": "88401", + "frames": 804, + "digest": "a6a22229bb9f61d4aff285768d59ba0eb3eb024b6a612a97cb2993b9bede4b5a", + "discontinuity": false + }, + "state": null + }, + { + "index": 114, + "op": "advance", + "boundary": "112", + "engineFrame": "113", + "worldTime": { + "numerator": "60005859375", + "denominator": "32" + }, + "mask": 0, + "frame": "58dbe732d569dffe051a1059d1a606f4ccfefee87de30b8c86229795dc0aa681", + "memory": "c095af2ccc854f7c050306a9733c95d62cfbca99a38b1a12ced9a39a605dc872", + "wram": "a91e24f9c002b0ef7788b7c75eabb30d8ef9a83821c67319e9de39cdfb4eacaf", + "audio": { + "firstSample": "89205", + "frames": 803, + "digest": "ddf3023b99991e3ff7b5bb10b1bfb1bb58ec2179d110ade3bc8f85f65d72ba72", + "discontinuity": false + }, + "state": null + }, + { + "index": 115, + "op": "advance", + "boundary": "113", + "engineFrame": "114", + "worldTime": { + "numerator": "968666015625", + "denominator": "512" + }, + "mask": 0, + "frame": "40adbd462bbcbf282a88aa01d88064dbc59a13f35a5873bb1d66101e08fc766c", + "memory": "5a2830a59b11be9ec183471fd88ce6c05f2d7b23f7031a7d1be6b1ac603e8241", + "wram": "daceffaeebf7a3a7a1084359a7203a15f83e5492a2b90bad53a0c941aba052ec", + "audio": { + "firstSample": "90008", + "frames": 804, + "digest": "fb7f140cc458322595aa889ebf2c66da4ec1ec7d9982ecf8bae0157a653416b1", + "discontinuity": false + }, + "state": null + }, + { + "index": 116, + "op": "advance", + "boundary": "114", + "engineFrame": "115", + "worldTime": { + "numerator": "488619140625", + "denominator": "256" + }, + "mask": 0, + "frame": "9fd6d39a48df49b2d2aff8cfde1c9ca8a91e5cbb62792697d6539cb38d470061", + "memory": "749ad85004dbb8cc4e8776c56f95acd33b5d91b9fc72c49f11e1e13cceced2fc", + "wram": "fda291bec9f491040968e66085e941a9cf065996291b6a4253bc7e56ef21957f", + "audio": { + "firstSample": "90812", + "frames": 804, + "digest": "9538e50079a78e5ab5e8e3647df96914dd295204008d0dfabc6d776c57f3f6ad", + "discontinuity": false + }, + "state": null + }, + { + "index": 117, + "op": "advance", + "boundary": "115", + "engineFrame": "116", + "worldTime": { + "numerator": "985810546875", + "denominator": "512" + }, + "mask": 0, + "frame": "66a67f956f7b92865c88f7c97585644218aa5f98bbad8a78936a0c9a2f4003de", + "memory": "1aadf4922874d5cd4f2f6666732f06392313c1af28a978abfb78eceaaefbe2fc", + "wram": "38627e02917c67466329d172898416c01b05fc41928a66f9967ee1a669f3e524", + "audio": { + "firstSample": "91616", + "frames": 803, + "digest": "4f3f1acb7757ceb681c4942a1d5a8dd158bd262d8659f700c018898839415958", + "discontinuity": false + }, + "state": null + }, + { + "index": 118, + "op": "advance", + "boundary": "116", + "engineFrame": "117", + "worldTime": { + "numerator": "248595703125", + "denominator": "128" + }, + "mask": 0, + "frame": "884e653fee8f8fc4ff945b85d00a5a5a6d719287d1c3f059c05936ef8ba7f401", + "memory": "7c5ab7f0497b9e9f5603ff22b258bfd41455bc7ccc0ddabc5dc099ea983c3919", + "wram": "fa815cba37acde7bfac485c07b84e6f5ca1b720832ec1f3f2a4f0d20066b5a04", + "audio": { + "firstSample": "92419", + "frames": 804, + "digest": "c779eea20a736bd766f2c1269116ec98ac6adfb9d839a48a62227f08dd82b850", + "discontinuity": false + }, + "state": null + }, + { + "index": 119, + "op": "advance", + "boundary": "117", + "engineFrame": "118", + "worldTime": { + "numerator": "1002955078125", + "denominator": "512" + }, + "mask": 4, + "frame": "7ae87833a076ba0a75acc854385758ecaa3ef8eb65d4648af4ec9e841df7a8b3", + "memory": "ad0a2ddaa3fc6bc7f53fe7bcb877fb03618fec32f6ccc19d78ab460801a0efaf", + "wram": "28877bcd41f0ac192984d53268a61c58c23b7469878a4323547391df45e103b8", + "audio": { + "firstSample": "93223", + "frames": 803, + "digest": "147320f1d9dc1668c59f0e3160991d5079d0a38c769a5c01595e4e7b5a957043", + "discontinuity": false + }, + "state": null + }, + { + "index": 120, + "op": "advance", + "boundary": "118", + "engineFrame": "119", + "worldTime": { + "numerator": "505763671875", + "denominator": "256" + }, + "mask": 4, + "frame": "91625c79cf8417f0c8271748eebec4259f395b3aaed9b111c57f55c64bfe2188", + "memory": "34b4226a620f1bb69b306981ff13ed7898d37993923a69d5e50c625b84aaf988", + "wram": "bcc7ef9c4b855090a40b1716bab837eebb2b81b54b3e219bad57463ba4ae6495", + "audio": { + "firstSample": "94026", + "frames": 804, + "digest": "0ae6ab43cd26a8e6f172dc7659e2099fc53c32fa26612b1294876de8b1242653", + "discontinuity": false + }, + "state": null + }, + { + "index": 121, + "op": "advance", + "boundary": "119", + "engineFrame": "120", + "worldTime": { + "numerator": "1020099609375", + "denominator": "512" + }, + "mask": 4, + "frame": "0ed96aa8f9e282b0fdb37d0e43c904c4db48b83de64d95647cac0ed3cc801668", + "memory": "bb0fbc55125ae076f7b1cf6f283703d842803228be28b4e013c1ebdf490ab5df", + "wram": "bae99940100bcfcec1d6108b9a5d4495f953c6abbf375028776ec0b06e1c0018", + "audio": { + "firstSample": "94830", + "frames": 804, + "digest": "9342022d42c2ac06e68caec11e2f4803e5da0c0fe20ddbd8cf45253fad74f828", + "discontinuity": false + }, + "state": null + }, + { + "index": 122, + "op": "advance", + "boundary": "120", + "engineFrame": "121", + "worldTime": { + "numerator": "128583984375", + "denominator": "64" + }, + "mask": 4, + "frame": "ce8d99fc9faa68c2cf164ed4ecb8da6296b14cf3c85b34b2567e55bde44802aa", + "memory": "06f9f0d37c08fd0af59eaadabc88fb054f077b724baf692fbb25717094688fbe", + "wram": "def66f2f3a293b2c0b6eac202448d4f7ee4b1bb89b17428a26e18f2feca9180c", + "audio": { + "firstSample": "95634", + "frames": 803, + "digest": "850498ccb014cdb07b05659fa1cb89359bc67b5d5420db5710775e8bfeab7bf4", + "discontinuity": false + }, + "state": null + }, + { + "index": 123, + "op": "advance", + "boundary": "121", + "engineFrame": "122", + "worldTime": { + "numerator": "1037244140625", + "denominator": "512" + }, + "mask": 4, + "frame": "4753fc53f7c1eea686729673e2f56105bfe210e3fa47cd6f269c530a4f2e5265", + "memory": "60066202a87c5e543afc4d730eb36b06824ba9886cc0911cd59e5caeb84224f4", + "wram": "66378d77566d831f0f71472062bee6362359d67221e981586cfb5b2f5958dba6", + "audio": { + "firstSample": "96437", + "frames": 804, + "digest": "0a11e1e89b67579d928ed8bc9e773470dd31bfa5bd3e81f103a3c4d36c3b45e7", + "discontinuity": false + }, + "state": null + }, + { + "index": 124, + "op": "capture", + "boundary": "121", + "engineFrame": "122", + "worldTime": { + "numerator": "1037244140625", + "denominator": "512" + }, + "mask": null, + "frame": "4753fc53f7c1eea686729673e2f56105bfe210e3fa47cd6f269c530a4f2e5265", + "memory": "60066202a87c5e543afc4d730eb36b06824ba9886cc0911cd59e5caeb84224f4", + "wram": "66378d77566d831f0f71472062bee6362359d67221e981586cfb5b2f5958dba6", + "audio": null, + "state": "25d098571f764336fe0f3a8e63438e749596f53a4065ccc6071868802172bd9d" + }, + { + "index": 125, + "op": "restore", + "boundary": "121", + "engineFrame": "122", + "worldTime": { + "numerator": "1037244140625", + "denominator": "512" + }, + "mask": null, + "frame": "4753fc53f7c1eea686729673e2f56105bfe210e3fa47cd6f269c530a4f2e5265", + "memory": "60066202a87c5e543afc4d730eb36b06824ba9886cc0911cd59e5caeb84224f4", + "wram": "66378d77566d831f0f71472062bee6362359d67221e981586cfb5b2f5958dba6", + "audio": null, + "state": null + }, + { + "index": 126, + "op": "advance", + "boundary": "122", + "engineFrame": "123", + "worldTime": { + "numerator": "522908203125", + "denominator": "256" + }, + "mask": 4, + "frame": "cb83fd5fd54c4c80cc18d5c2ccb4256a6a0ceda285a98d3871044dc34a735d02", + "memory": "b9e2927f347f7a653c8226c002449eaf1167d9d1ab04ab31fdd50d4d664b7210", + "wram": "efee7a7a0f3badf16b7fce7ae11d8999de39b686d6f0ad56986c5696d68b9285", + "audio": { + "firstSample": "97241", + "frames": 803, + "digest": "79fdfe1e50a31e055889aab577f10352f1d0e0d33b2e44f388237abd7011ee01", + "discontinuity": true + }, + "state": null + }, + { + "index": 127, + "op": "advance", + "boundary": "123", + "engineFrame": "124", + "worldTime": { + "numerator": "1054388671875", + "denominator": "512" + }, + "mask": 4, + "frame": "9c7f2f6e72b663645ba38d633eab081b71a3e25e8b3ba4750b05f3c3da64a37c", + "memory": "24c94fa2cccea7f91de010d38bf18c50ca1a74347be7867e47fcdcf1c060b924", + "wram": "90c56df68c8c7ce34e761b95ea70ac2d931085cdf7bac66d8c649e581c094d5a", + "audio": { + "firstSample": "98044", + "frames": 804, + "digest": "2f3a0352d53bdbcd707e26a6ecd69349f3c8387d3ed373fe08d520737e91e3e2", + "discontinuity": false + }, + "state": null + }, + { + "index": 128, + "op": "advance", + "boundary": "124", + "engineFrame": "125", + "worldTime": { + "numerator": "265740234375", + "denominator": "128" + }, + "mask": 4, + "frame": "a6bd164c63f378de1e421153d18cad8eeeaef9f9037a18c2bfb9813638461b00", + "memory": "b080c5bb1bbad35f911e3bd103b475540b2f7777fc070cc4238df603b0239987", + "wram": "b526aa6e8b5774928791f5ee651c47412be7343691cff1fab0cfcbc6fe2172fe", + "audio": { + "firstSample": "98848", + "frames": 803, + "digest": "1d84ceb7c06c5eeabdd2818c5c884e1d0076dc8c93fdc8b9a8f72568489f789a", + "discontinuity": false + }, + "state": null + }, + { + "index": 129, + "op": "advance", + "boundary": "125", + "engineFrame": "126", + "worldTime": { + "numerator": "1071533203125", + "denominator": "512" + }, + "mask": 4, + "frame": "3a4f7fae899e298447aafdd2842706333528140cf3feaa8736cad9b3a53b43bf", + "memory": "4915fef2c12017f5c95e09c3550484ce2ca352e97e6ec10a870850c2eb12f527", + "wram": "ee25aba1d64aabbc320a783b7c93f23a08806f04c08f53a7591ddab256714281", + "audio": { + "firstSample": "99651", + "frames": 804, + "digest": "ae20f5812643041835dc71a6cdfc06d56f2ceb87b31ba9ff62f83cc1bbc6e9a4", + "discontinuity": false + }, + "state": null + }, + { + "index": 130, + "op": "advance", + "boundary": "126", + "engineFrame": "127", + "worldTime": { + "numerator": "540052734375", + "denominator": "256" + }, + "mask": 4, + "frame": "cff49c018fabdabb8bf8865b115318be45c8cd4d2fbaed86c5d9d9840fd2ba3a", + "memory": "780e1ee6126ce6c300aa0e9932a23b81e9d67c989978a90b5beca64fae82ace6", + "wram": "6cd75b8ef8ebfabd2e93d403e54f8134b6107cea1ab64ce60347d832ac0b7764", + "audio": { + "firstSample": "100455", + "frames": 804, + "digest": "7b963d935ee4da11a9c09f23a79f1cc0d543b3cd3e3a2a892d15b89cd4b2dca1", + "discontinuity": false + }, + "state": null + }, + { + "index": 131, + "op": "advance", + "boundary": "127", + "engineFrame": "128", + "worldTime": { + "numerator": "1088677734375", + "denominator": "512" + }, + "mask": 4, + "frame": "8b8df5c47f9c25ebd8f6bf0dfe862821aeebc120652aef6b505bcf5b12304d6c", + "memory": "da79d60bc6233781673eabd3cc37f1677ee145cfa400cfa7fa5414de6759efa2", + "wram": "5ae362e5ae73633924bc0c5886234eb7834070c677f4f827030e5c876adb8d1b", + "audio": { + "firstSample": "101259", + "frames": 803, + "digest": "7076517dedcb038afd6a0a80350e75d45a12dc01ffe85f8bf9c56f2810dbbe08", + "discontinuity": false + }, + "state": null + }, + { + "index": 132, + "op": "advance", + "boundary": "128", + "engineFrame": "129", + "worldTime": { + "numerator": "8572265625", + "denominator": "4" + }, + "mask": 4, + "frame": "d4b48bc9ead761594d5f194f26efb73aa047d400e49e5a02f7ef7cf5bf78e9ec", + "memory": "d99d84c191755f22eec4d869e6adcb7a692f5f0b43a0c12186d10edc87b65caa", + "wram": "9a37c09bda87e6e5dcdd19cc31ed951c0978cd103eb7a6270846039228740bcf", + "audio": { + "firstSample": "102062", + "frames": 804, + "digest": "365532c5e1b451b1412059796b0ba6d17c6e6f16a6d57400afdef0f51e78120f", + "discontinuity": false + }, + "state": null + }, + { + "index": 133, + "op": "advance", + "boundary": "129", + "engineFrame": "130", + "worldTime": { + "numerator": "1105822265625", + "denominator": "512" + }, + "mask": 17, + "frame": "d1072a80db98b52d16e09b4b56e313edd7ca705f605ff30e6447fc7ff22ab6ca", + "memory": "6acfe50e334267044a88cd6231e6962f302f5af469fe5a061862fac822f6d0cf", + "wram": "5f6863ef1fc87d1bbb6fb1f918f230ed9530db669537aa9dcdac078da5710230", + "audio": { + "firstSample": "102866", + "frames": 804, + "digest": "00eb1d89368d2551ddd4aab61e2d7b28301bb7ebd58ab5963b27277ae696f0c4", + "discontinuity": false + }, + "state": null + }, + { + "index": 134, + "op": "advance", + "boundary": "130", + "engineFrame": "131", + "worldTime": { + "numerator": "557197265625", + "denominator": "256" + }, + "mask": 17, + "frame": "d22d55daaa8422af5b73ea5f2fcaa3cc78375641005fdd2d807e117ba1fd3c99", + "memory": "cb67b28e16261bbd6d3715ff55e087f32bac22ca3dda393383e5c0d86ce5b867", + "wram": "d32fe3bc98d5c8c22b70285b03cf723768fe34af0fa7017808ad770187169807", + "audio": { + "firstSample": "103670", + "frames": 803, + "digest": "1f108ce3fac8d7c6574cf259edf5f0580cab4e21bea034a22415adfd38760304", + "discontinuity": false + }, + "state": null + }, + { + "index": 135, + "op": "advance", + "boundary": "131", + "engineFrame": "132", + "worldTime": { + "numerator": "1122966796875", + "denominator": "512" + }, + "mask": 17, + "frame": "52420f37551bea49cbcb7af3733f51c365a0f6a2709cdc4d191a6b7e07b7dfdb", + "memory": "1696e63ce1517f719e74276bbedbd9e2168154bf8caea31630480b45a52306c6", + "wram": "04fd47f1b438fc8138f7345d686182ea5a62ccff2a215bc0b55181cbaf98a8c8", + "audio": { + "firstSample": "104473", + "frames": 804, + "digest": "1a071ecc5b7dd1aabd2b8091298c04cef6ad41b3db3d11b5fb9445a2ad03b4c5", + "discontinuity": false + }, + "state": null + }, + { + "index": 136, + "op": "advance", + "boundary": "132", + "engineFrame": "133", + "worldTime": { + "numerator": "282884765625", + "denominator": "128" + }, + "mask": 17, + "frame": "767a91003b2c8d0258535db504b4416f9fbd9300d195cf9f9266de30a7335da3", + "memory": "c7ac89fb696a6b1225c3179946c2c2512d642bf6df3e258264217f15f7c85201", + "wram": "7f770b4708eb1e8eb5a339997baaf316d49d9304e2b2408ac36e2f96c5f576a4", + "audio": { + "firstSample": "105277", + "frames": 804, + "digest": "9f556750e92fce6542ffc3159eb3f392b08d861007df56378e7381f79a258b18", + "discontinuity": false + }, + "state": null + }, + { + "index": 137, + "op": "advance", + "boundary": "133", + "engineFrame": "134", + "worldTime": { + "numerator": "1140111328125", + "denominator": "512" + }, + "mask": 17, + "frame": "1fe46f585daf0da15f0e886aad88c813d5f545593bdc580a10d15301abf11073", + "memory": "3f202ef9017ddbd716ced4e2611ae8ea6192b07daffca8d34fa1d0072b291867", + "wram": "5c11076edc0cc49fd818de8d9de2b0d144ea587473cedc20217bf4e7ac3c9abc", + "audio": { + "firstSample": "106081", + "frames": 803, + "digest": "397e493aecf9893ef4c5b2d742a75673b5708f62087443601c80eeb27e5af5be", + "discontinuity": false + }, + "state": null + }, + { + "index": 138, + "op": "advance", + "boundary": "134", + "engineFrame": "135", + "worldTime": { + "numerator": "574341796875", + "denominator": "256" + }, + "mask": 17, + "frame": "ab863e28a688c4be1bf003ee87a75b5358ff4e9bf3626c7a1efcb7caea81d7b8", + "memory": "cd71feffaabe063bab943798bdfdb9b8505123758abe66d170548c2a8299b91b", + "wram": "3f8a2ad5312e1b1e43e0e33c5ac52a98625e2aac91cdd8d8cc0e20742e551175", + "audio": { + "firstSample": "106884", + "frames": 804, + "digest": "c73245fcc8d75d47dbb3f9feb4822f1d10162c67395678e39a330373f24ecc05", + "discontinuity": false + }, + "state": null + }, + { + "index": 139, + "op": "advance", + "boundary": "135", + "engineFrame": "136", + "worldTime": { + "numerator": "1157255859375", + "denominator": "512" + }, + "mask": 17, + "frame": "92bacdddb791da4b6ee8cff9cfb0e2bf33cbede33e809d003cb06f408ed3c457", + "memory": "a23963f85fe0bf2b58495f2b7ace744cffb3025ce6f5b687266b142d432b090e", + "wram": "abc9000f1470627d75cddddf6209d5cc2f9e41f7378f0c40f8f9a79961ed29ea", + "audio": { + "firstSample": "107688", + "frames": 804, + "digest": "ba1561d9104f5d99f0805626a87b85cc627758b53ca6b66be74775126d5e6271", + "discontinuity": false + }, + "state": null + }, + { + "index": 140, + "op": "advance", + "boundary": "136", + "engineFrame": "137", + "worldTime": { + "numerator": "145728515625", + "denominator": "64" + }, + "mask": 17, + "frame": "5d93b95a0338362e1142ad3d43e8650deb1fb5622d4b1ed0a78d508b54f35f6d", + "memory": "1acee75dea546407ad9dd9c88ee15dce201a0abc808084fd7356897bd2122fcb", + "wram": "fa95563ded3400c9428dd8469b3ebd9deeab38b7a506d15a2873741c66fedf46", + "audio": { + "firstSample": "108492", + "frames": 803, + "digest": "4c6dbbbbf091c76201302c2ad1a7c10138aca4cc9fd0c0660218abd7d1a241cf", + "discontinuity": false + }, + "state": null + }, + { + "index": 141, + "op": "advance", + "boundary": "137", + "engineFrame": "138", + "worldTime": { + "numerator": "1174400390625", + "denominator": "512" + }, + "mask": 17, + "frame": "144301124eaebc8c750a252227dd759f39fe199f58a0ba6c60f0f1e03302303b", + "memory": "b5e9c24b88615f3429ea771e45c745e1fd5083c2331254613d1f569589635660", + "wram": "0fd6a7aecc16e7da4a903ab34d58394dcf4ba12814d15b1064d407a0cf63cb52", + "audio": { + "firstSample": "109295", + "frames": 804, + "digest": "62d6189671d988589d38d1d00a420f34945e585652c60b50d603e941dfb7be89", + "discontinuity": false + }, + "state": null + }, + { + "index": 142, + "op": "advance", + "boundary": "138", + "engineFrame": "139", + "worldTime": { + "numerator": "591486328125", + "denominator": "256" + }, + "mask": 17, + "frame": "ae89e6e64586e6d7b0405aef8ea2d833767955f94b21897b92563c4c1a46370a", + "memory": "d24a09c20ee0932e1381ae027eaaa53c888681ca5c3ff1a02006e4fcfa9d5c94", + "wram": "45bbe99dabb8a24d016d29451a418c483f94c6df07036b312789553b5bd6199d", + "audio": { + "firstSample": "110099", + "frames": 803, + "digest": "ca77cebd9e97cf47c7ba6a055bf28889eedbc59703acc3caee24530cc88f4f97", + "discontinuity": false + }, + "state": null + }, + { + "index": 143, + "op": "advance", + "boundary": "139", + "engineFrame": "140", + "worldTime": { + "numerator": "1191544921875", + "denominator": "512" + }, + "mask": 17, + "frame": "b11d93574717d72faaeb3b80e8d1fe5fa70f7737a3227b7921febf159f741000", + "memory": "f1de501158161fc64330bec17573d70de0f4d251b9bb67dfbec2b012b26a739d", + "wram": "2a330d848a68a8dd84ee4bc6e24eca4ed26d1746b1a8780819cefdf9130efb6e", + "audio": { + "firstSample": "110902", + "frames": 804, + "digest": "fb13b5f1e4d68c7937a7d03a3a1c8a6ef6a8716b7494fc5756fe451fcff43683", + "discontinuity": false + }, + "state": null + }, + { + "index": 144, + "op": "advance", + "boundary": "140", + "engineFrame": "141", + "worldTime": { + "numerator": "300029296875", + "denominator": "128" + }, + "mask": 17, + "frame": "9c8ada350809adeef48a8b10eec0ac9f0af64473318a2eaca88ccd718380e978", + "memory": "1a9698e443d9f4ec612ea71fbf4138da5e0ce2613d18cd793108c2c43916b868", + "wram": "d71b6b6035536775860c68e7638f7ecae9f824e4a539d5eece04aa47144443ae", + "audio": { + "firstSample": "111706", + "frames": 804, + "digest": "d8ed6168b92a52fa05a9593b33ef84dd2bd4aa5288e0e71bc95046bcb4152217", + "discontinuity": false + }, + "state": null + }, + { + "index": 145, + "op": "advance", + "boundary": "141", + "engineFrame": "142", + "worldTime": { + "numerator": "1208689453125", + "denominator": "512" + }, + "mask": 17, + "frame": "235e61ea550863f9d4e6b30ac32e9075dab7db69995642f95e2eb274a5d8f353", + "memory": "dfa2f612b5756afcb6224d4fe8fd07598891be13b3bf7aaa1a1449b58f6f926f", + "wram": "b6d28f9010f8c77f9cab83a8166c2eaf8337ad45138ef8482a46cd545dc716aa", + "audio": { + "firstSample": "112510", + "frames": 803, + "digest": "9af77ad3c5eb5297b9857aa4c7469f42e5ffd51916adccf13fe249a630f7901d", + "discontinuity": false + }, + "state": null + }, + { + "index": 146, + "op": "advance", + "boundary": "142", + "engineFrame": "143", + "worldTime": { + "numerator": "608630859375", + "denominator": "256" + }, + "mask": 17, + "frame": "512bcf2fbe031cbf38159f98ccdec0b56fda9ede8dbf8fc5459b571bc1c9e7e6", + "memory": "75ba86269f997844ca52096aed5e57b9bc9fd2f91e54d07c4898e2f182656fa8", + "wram": "248c6690584c7531f05aa9c6c8d3712436b2b2bb377b54471c621183e7a4be8b", + "audio": { + "firstSample": "113313", + "frames": 804, + "digest": "0f84a0dd4b6ae35ccd8efbe0ab4631650c2627db753c3d5d01c4748e2c81c7b8", + "discontinuity": false + }, + "state": null + }, + { + "index": 147, + "op": "advance", + "boundary": "143", + "engineFrame": "144", + "worldTime": { + "numerator": "1225833984375", + "denominator": "512" + }, + "mask": 17, + "frame": "1852caaabc7c4a244d78885be7d1eb35e87bee7d75991940244b8f15df56ad88", + "memory": "a0babf0722d5ff56e0a7fb6c5f5fc958dbcfb0375bbe19ac4abf13ab8aa41a73", + "wram": "7647d57084bec91c9abe4c19470c161e7490d5fee6838d12cb388fac6e566c19", + "audio": { + "firstSample": "114117", + "frames": 804, + "digest": "eb145960195216290ce25018a5b54fc1044fc73ff12ad10bc59cb61f321163e1", + "discontinuity": false + }, + "state": null + }, + { + "index": 148, + "op": "advance", + "boundary": "144", + "engineFrame": "145", + "worldTime": { + "numerator": "77150390625", + "denominator": "32" + }, + "mask": 17, + "frame": "c9c70ec1f20817ac74a1155aba06eb180f7fe874cc19a95de7f8bee5b4169fe7", + "memory": "c99d1a1dc1e763559e1f43b01b59e11d53c34b325be58d48daf55d25992f8235", + "wram": "399e066c6c0b7fe5c06f597aadbfc153a67d4da218874a6cfdb5e2555b5e4771", + "audio": { + "firstSample": "114921", + "frames": 803, + "digest": "76e1b8a9a06987efc59202bda1b215c6a64306be5606ba3e76569a61045da502", + "discontinuity": false + }, + "state": null + }, + { + "index": 149, + "op": "advance", + "boundary": "145", + "engineFrame": "146", + "worldTime": { + "numerator": "1242978515625", + "denominator": "512" + }, + "mask": 17, + "frame": "ce98a8837fbfd123efa1d89679901dc605c8ae58885004a1e00f6c9550cf6c46", + "memory": "fadb92dcd55ed4232021c4f2aa9a092443611b307cd4fc51bc9c03699b0593cb", + "wram": "662c86fc41aa3294b3ce426b13f2c8d4cda493db3cc57b3915fbf72160f4894f", + "audio": { + "firstSample": "115724", + "frames": 804, + "digest": "d1364ccfee9372a56f440f9f60f81a6dacb0e1abab8041e3bad5c9b57589f24e", + "discontinuity": false + }, + "state": null + }, + { + "index": 150, + "op": "advance", + "boundary": "146", + "engineFrame": "147", + "worldTime": { + "numerator": "625775390625", + "denominator": "256" + }, + "mask": 17, + "frame": "a7086cbef2215382fc0f102e90ad6f993a5ad26ce8064d9483c34287b604bfba", + "memory": "d154bb2f494bd2dcf459a40c24ea19c8e84a3b56f40a06732c6935a0c3405cf1", + "wram": "f1e3274affb20eee09d68b9d661e248e934cea04e6ca83d8e9665f6769eb7b7e", + "audio": { + "firstSample": "116528", + "frames": 804, + "digest": "f5cbb65ab9497a44f7413f06045f03758427e5635a530238f359ebc5ff0e2654", + "discontinuity": false + }, + "state": null + }, + { + "index": 151, + "op": "advance", + "boundary": "147", + "engineFrame": "148", + "worldTime": { + "numerator": "1260123046875", + "denominator": "512" + }, + "mask": 17, + "frame": "3d67728cc436ae35ce5ee0c58c6e3cb44f0d78f97f5631776dee137434870193", + "memory": "aa6acd39fd26fa063a23346a3380e436b7a54ee31066edcc847bd75b95610423", + "wram": "164c401651b19cde741b0b693c559721c3d4588416c34ca058544be58f2e869d", + "audio": { + "firstSample": "117332", + "frames": 803, + "digest": "cc13ae2e50319b7f7cf199a03c3fbae80c5fb391fb57383b0292a234862e2028", + "discontinuity": false + }, + "state": null + }, + { + "index": 152, + "op": "advance", + "boundary": "148", + "engineFrame": "149", + "worldTime": { + "numerator": "317173828125", + "denominator": "128" + }, + "mask": 17, + "frame": "8c873a220dd0595035c8e2f78c08a078fb0a344972f91f66ac7632880e7435b8", + "memory": "38965ad00affad5f5a22a2117f51eaf65153c38edc66b70e6a782f511ed3080a", + "wram": "24a228956b643b29178d518bbbdb2eeba5fa64ca730e53db1cb77229a6b80f18", + "audio": { + "firstSample": "118135", + "frames": 804, + "digest": "b7532f2c14a68bbce8c8ab792dc96415bf92296c0c80ec55f0b2da7010e3a66a", + "discontinuity": false + }, + "state": null + }, + { + "index": 153, + "op": "advance", + "boundary": "149", + "engineFrame": "150", + "worldTime": { + "numerator": "1277267578125", + "denominator": "512" + }, + "mask": 17, + "frame": "56be3ce3506612fdcd666c55f0567c54679c53733d0359d4538814ab93766e9e", + "memory": "414650543c0d1f85e99a073d6293c5b621683333150246829d3abb156b960d8c", + "wram": "d32fc85cfd57d8826877709e392692ec6403f49bee89bcc9229451aabaf17b54", + "audio": { + "firstSample": "118939", + "frames": 804, + "digest": "fa0ee9720cda97ee03b5359db9a002f0bbfc0339e602f0d1713e3f643ec18c4e", + "discontinuity": false + }, + "state": null + }, + { + "index": 154, + "op": "advance", + "boundary": "150", + "engineFrame": "151", + "worldTime": { + "numerator": "642919921875", + "denominator": "256" + }, + "mask": 17, + "frame": "5ea5e0f43635435fac0db17de68914e2b20ed665f03b2322679d20e3dd680a01", + "memory": "ca2577b8f7fb3a548f5e514b310f0e57f28fd8375920f40fb9da675716da55aa", + "wram": "7db42a4799ca665a4517bae2887198f8ab28b7b53a047029b67d0993d163916f", + "audio": { + "firstSample": "119743", + "frames": 803, + "digest": "16edb44154e45724d73f10f2387895f1117bf35e79de2c2f18be22ae666c19cf", + "discontinuity": false + }, + "state": null + }, + { + "index": 155, + "op": "advance", + "boundary": "151", + "engineFrame": "152", + "worldTime": { + "numerator": "1294412109375", + "denominator": "512" + }, + "mask": 32, + "frame": "4e352ebb684dad61e5a44acc1af45a6db5a457f08847d0e5a9fcfab272f898d1", + "memory": "de44819dbfa41bbbc3306a8b96dba9d9e5783217b0fae24d372636cf7de49cf7", + "wram": "e768e38afd8f69c68e7b9967bcf16c5a92cc63c5afc349278057d6983c20e369", + "audio": { + "firstSample": "120546", + "frames": 804, + "digest": "6d422f3c0f34718b66c8cbebac62b48b37691f4848567a8db8cb86d2931b6ede", + "discontinuity": false + }, + "state": null + }, + { + "index": 156, + "op": "rollback", + "boundary": "151", + "engineFrame": "152", + "worldTime": { + "numerator": "1294412109375", + "denominator": "512" + }, + "mask": null, + "frame": "64768d7167e34d306ba9083bb1dc7e65e6123b634079787faa19d0ef3798de86", + "memory": "66278bc8057194b81bf22fad68280b50e5035a4d8a0c5233cb8f80d172fac2d9", + "wram": "fd666c21dabe652d5a961e8b85ff4c93367d5519f588d860fbb4ba1ccf549ea4", + "audio": null, + "state": null + }, + { + "index": 157, + "op": "advance", + "boundary": "152", + "engineFrame": "153", + "worldTime": { + "numerator": "162873046875", + "denominator": "64" + }, + "mask": 32, + "frame": "753c140971ee4e9a32a1520a665ef9b0f9f7e1fa169df19d2f1b056d306aa456", + "memory": "8645ee2aee752ec082f115b3b0c2d8d9dd88817c023a04ffd5d4b067e7c0b790", + "wram": "8ed70c3d6a69e080cf326a85e21af3d33dabb1b48bbfea89ee9e63136e35fa1a", + "audio": { + "firstSample": "121350", + "frames": 803, + "digest": "aecf4827e2035a6d56371df636cd43fd5130ed0b3e8051a788941fc9763ce142", + "discontinuity": true + }, + "state": null + }, + { + "index": 158, + "op": "advance", + "boundary": "153", + "engineFrame": "154", + "worldTime": { + "numerator": "1311556640625", + "denominator": "512" + }, + "mask": 32, + "frame": "22f1be54f37f199dcaeec1060e2e09e3a22fd5164699bc053ea0920ae7ada08c", + "memory": "48a3cd447e083e7c0f56b1d9aaf4cb79d535fc5c2b32c2ded1daa3b8b6f830fa", + "wram": "cf90552f0e41f35efe50a321cd34868f55178c0618318ad8b147307700b85947", + "audio": { + "firstSample": "122153", + "frames": 804, + "digest": "2a812dfb115c16689fbbb658dd9e59eaa09a01ffd1c2b5673f8646453c53001c", + "discontinuity": false + }, + "state": null + }, + { + "index": 159, + "op": "advance", + "boundary": "154", + "engineFrame": "155", + "worldTime": { + "numerator": "660064453125", + "denominator": "256" + }, + "mask": 32, + "frame": "48d2bb3924667d51dab00774d733c87e71f5116ac97a25a3c8f918a1864045a6", + "memory": "d9554b2815015fb713f2f6114c04e9d85f3e9e71e211a939c814fb642b1c1c32", + "wram": "310f01c088dba3ad815660043bd9258ef49eec536988870fde71dae14a279ca1", + "audio": { + "firstSample": "122957", + "frames": 804, + "digest": "c3c7a8dbd207153974809031d3b3d3b613cb8c199c86f77a9a354e19318c27d8", + "discontinuity": false + }, + "state": null + }, + { + "index": 160, + "op": "advance", + "boundary": "155", + "engineFrame": "156", + "worldTime": { + "numerator": "1328701171875", + "denominator": "512" + }, + "mask": 32, + "frame": "656fdd04a80de28316c851dac094ef299232c26ca0e2262b0665cf1aa024ee15", + "memory": "36ef29cc840bd61d42df8e489392af64be85bdcbe32681e669d7523429254867", + "wram": "80bffa19b111cb702883eec1480718895117c14fb84a8f82cf1981dfc53c3abd", + "audio": { + "firstSample": "123761", + "frames": 803, + "digest": "0eecda99c7411659e67f73e1e8aa50e041a0138be8e6b2a6a0ffb9645f107ec6", + "discontinuity": false + }, + "state": null + }, + { + "index": 161, + "op": "advance", + "boundary": "156", + "engineFrame": "157", + "worldTime": { + "numerator": "334318359375", + "denominator": "128" + }, + "mask": 32, + "frame": "e1963ddc2736e66231b0ecc309e1d2becdabb34723181ac9856be2ab24c4c41e", + "memory": "c3a2cced361cef15f59fe3c9d622483911ea4ecd94637394e960395430a1487c", + "wram": "6e1859a7671e677868a0366b4bd7eb527edb0ecbd9befff509e7cc638bd1ba29", + "audio": { + "firstSample": "124564", + "frames": 804, + "digest": "5ec744ab5757901c40783e2aa896063febf7391a9d56102dfd6b653832c3ba43", + "discontinuity": false + }, + "state": null + }, + { + "index": 162, + "op": "advance", + "boundary": "157", + "engineFrame": "158", + "worldTime": { + "numerator": "1345845703125", + "denominator": "512" + }, + "mask": 32, + "frame": "858ad41eeb5588db26891ef3d4e9ae896fc05c7dfe0c7115bbf91d886afff4e6", + "memory": "49c6b7be04543ffa3f08b9281ce09f5195ddc515b791c41cd6b97475b80272c4", + "wram": "9a1444f58a03ff2b0d992daade02bef2437323d67f0bd305cd3849835a7b310e", + "audio": { + "firstSample": "125368", + "frames": 804, + "digest": "11b12292d21f365203da8b3b9c793850130320a10500a29ec16fc245adc26d50", + "discontinuity": false + }, + "state": null + }, + { + "index": 163, + "op": "advance", + "boundary": "158", + "engineFrame": "159", + "worldTime": { + "numerator": "677208984375", + "denominator": "256" + }, + "mask": 32, + "frame": "3f2b3e1bf955431affb925d5189b1ac826546fba973d4934a6f288b3de55dd1c", + "memory": "08cd222cfcc4cdc854e9be99d1645c07148e92f7e0630e16c3284ce29c13ce1e", + "wram": "41c2ec7fa6f02c25ebb7b5e977732161bbd66106621783d7fc77a7d1bf29c5df", + "audio": { + "firstSample": "126172", + "frames": 803, + "digest": "8747077774b224a8f49926f28cd5c6991c4724a77a0e77f51e399d838b42aba6", + "discontinuity": false + }, + "state": null + }, + { + "index": 164, + "op": "advance", + "boundary": "159", + "engineFrame": "160", + "worldTime": { + "numerator": "1362990234375", + "denominator": "512" + }, + "mask": 32, + "frame": "3b9cf500bdc56a25d6fdcfb9ff23956b2e21a7bf1434fdb84ea3a080176bbeda", + "memory": "04acab946005caf77fd89d258ce2f3c240b3e1509d5e64ecbde8230a883e9b2b", + "wram": "8dc22eb8d28728267804426c31e30e498d4544de7532180afe575a52d940d40d", + "audio": { + "firstSample": "126975", + "frames": 804, + "digest": "8d5db9a5f9f9ca252c0a45a9595e39091696d03509650d657f59120981e48bd0", + "discontinuity": false + }, + "state": null + }, + { + "index": 165, + "op": "advance", + "boundary": "160", + "engineFrame": "161", + "worldTime": { + "numerator": "42861328125", + "denominator": "16" + }, + "mask": 32, + "frame": "838c3852e2722710c38cc5cd0c2548d6fdf239639c8153543cfe89db85e2fd6d", + "memory": "58df7aaa6badccdea21abae9abe872ab6eaf5dd286e9f17550c930b5bee227a2", + "wram": "81045e99cf5b1f048a0a8b03ce5130a874ef0b6abc434f250c6bb15f01075e9e", + "audio": { + "firstSample": "127779", + "frames": 804, + "digest": "2b845cf30ea40244a43fef5b760068e9ce088df2a30b59049620532ab2abd2d6", + "discontinuity": false + }, + "state": null + }, + { + "index": 166, + "op": "advance", + "boundary": "161", + "engineFrame": "162", + "worldTime": { + "numerator": "1380134765625", + "denominator": "512" + }, + "mask": 32, + "frame": "6790e130d466b993be26933ec3557bbbd8ed9c5f3ac839248b43d30943535844", + "memory": "727fcdf8a7ab533f483e9ac824cfe23f905b88cb50dbfbd131f4cac127bb3167", + "wram": "047dfc8fcc0863eb747dc285a68077036f1bf16e3cb46fb2fcd365968aa35f4b", + "audio": { + "firstSample": "128583", + "frames": 803, + "digest": "d5c945227a1bd3915460da453ab67dd14357d6cacb607ed9775c964b7f656995", + "discontinuity": false + }, + "state": null + }, + { + "index": 167, + "op": "advance", + "boundary": "162", + "engineFrame": "163", + "worldTime": { + "numerator": "694353515625", + "denominator": "256" + }, + "mask": 32, + "frame": "c89ca281fc5391c04a1c95b7017be6f7ab9adc8144fe28fc602b414229e2eb89", + "memory": "488c33664a92658149b85ccd329227c61c09203da7b1b385a46953028746d83c", + "wram": "1d3bc2c0411dec7ae3307e439f6f354d18251ad74a34c1cbd2f78c84c722dfcf", + "audio": { + "firstSample": "129386", + "frames": 804, + "digest": "e226b22af55b34585c1c9b20515c538f3321c9e76d94f3c69135608b57a8cb5a", + "discontinuity": false + }, + "state": null + }, + { + "index": 168, + "op": "advance", + "boundary": "163", + "engineFrame": "164", + "worldTime": { + "numerator": "1397279296875", + "denominator": "512" + }, + "mask": 32, + "frame": "776f611745ae470495c5af28b16885b291f329af636df20705613af8902e6ac5", + "memory": "21054f82a206af8f00dfcf302434e0de9b1041b0e641195fdd86e09f5a3f062a", + "wram": "c625e96526a82a12c54f1d8608384b72d9fb077d7e15ebd2292be9f4e7fb9663", + "audio": { + "firstSample": "130190", + "frames": 804, + "digest": "7cc762a2142a99f673c6c6cc4e9ce8a6248d7c9bc900d74573b6a37a6951c107", + "discontinuity": false + }, + "state": null + }, + { + "index": 169, + "op": "advance", + "boundary": "164", + "engineFrame": "165", + "worldTime": { + "numerator": "351462890625", + "denominator": "128" + }, + "mask": 32, + "frame": "7ca327d262c35979d4f59df433605ea1d38af54c2520bbdb55b018e59aa1a370", + "memory": "2d0c4a5d72f06cf764dabda932756ecf8d547cbc88420d0eacdcdb232c3b2f29", + "wram": "ca815a6b85a1ff5ecc12e2c6278a376f7fe4139d6076180aafd2c33eb5d3044d", + "audio": { + "firstSample": "130994", + "frames": 803, + "digest": "b0aa78a6da307538099dd4ab6d19a90b18bccfc491172ba4c81d3715e1d04410", + "discontinuity": false + }, + "state": null + }, + { + "index": 170, + "op": "advance", + "boundary": "165", + "engineFrame": "166", + "worldTime": { + "numerator": "1414423828125", + "denominator": "512" + }, + "mask": 0, + "frame": "da9f31833723501e8f9b7e49e9ff20f3f29fb868299c56c8665a48f11ddf541b", + "memory": "d729a9c6f96171980e112315a94e057dbe81a2cd35f6f6a99667d124238836ab", + "wram": "6712dc8ac2aefc58789966ebef9da93eb8dad099aa8f944ce15a45d376ff1570", + "audio": { + "firstSample": "131797", + "frames": 804, + "digest": "4e3462f327c1b237d0de7b8819ef878419006542431cae779b823b1d38e598b5", + "discontinuity": false + }, + "state": null + }, + { + "index": 171, + "op": "advance", + "boundary": "166", + "engineFrame": "167", + "worldTime": { + "numerator": "711498046875", + "denominator": "256" + }, + "mask": 0, + "frame": "dcceb4875a447ac7cc594aa55c3c5d32ecfd7ac0cad4d99978dda00509911c6c", + "memory": "54ac81daf92d314f344de3d1306253a3fd49c8b7c89a114fbddbd46ba3a9e381", + "wram": "0f6f1dd14ce27852c4d4e46b250d230ab6aba2a40bd196180d3866e097317d48", + "audio": { + "firstSample": "132601", + "frames": 804, + "digest": "9882003fedcf44fd9852523f1d2f1d156c9a28de655e0861ee783ae336e36580", + "discontinuity": false + }, + "state": null + }, + { + "index": 172, + "op": "advance", + "boundary": "167", + "engineFrame": "168", + "worldTime": { + "numerator": "1431568359375", + "denominator": "512" + }, + "mask": 0, + "frame": "ac1a88b5ade80700b0bcee43bfd4f6aacdd146af6893fb8f86564cb6716688a7", + "memory": "c8b4e901acfafebe73eac834cbee7bc01e3bd56ab9e8fd511cbd25904bf6aeca", + "wram": "9698529419254ffeb37f26fe46de10c7afa41103d839d118c472eb6d6463ec3b", + "audio": { + "firstSample": "133405", + "frames": 803, + "digest": "d3e372d5394db2fdcaaf80cabe8a1f3c79f95ce2f56eeab07253f060e8a73afe", + "discontinuity": false + }, + "state": null + }, + { + "index": 173, + "op": "advance", + "boundary": "168", + "engineFrame": "169", + "worldTime": { + "numerator": "180017578125", + "denominator": "64" + }, + "mask": 0, + "frame": "b30c33051b4ab4f4d7f29222a290a680b53f752dd05000a72ec738319de33967", + "memory": "8b1aad5aed49f774279f5a3edf34ddcd5f9c14813f69dd26b000ee8d69fd2325", + "wram": "87cb8e7bbca4c18337a07277b31c68ae464d0bec5877844cccbef8aa81029c5d", + "audio": { + "firstSample": "134208", + "frames": 804, + "digest": "1e9dce77279255e5abe55f1c2be73ae20b7df97b5e8efd0b1bdd2885c23cd82a", + "discontinuity": false + }, + "state": null + }, + { + "index": 174, + "op": "advance", + "boundary": "169", + "engineFrame": "170", + "worldTime": { + "numerator": "1448712890625", + "denominator": "512" + }, + "mask": 0, + "frame": "04a24628cb2b0daf4fa5a3a72a121e025ee9b99cf5039a45bc399825e5f2f939", + "memory": "59f81c705a47aa3386ebd9c7a18ed7d9cdeb138b9125fd825d7ed782d262ae73", + "wram": "ec7bd0f711173e3da9f1c272c6e4115ef642446dfc0968c9b58891fca96a1021", + "audio": { + "firstSample": "135012", + "frames": 803, + "digest": "0ab60937e0902c0f1d7232b68056d84169714659e588e1745df1ab064f8e3bcd", + "discontinuity": false + }, + "state": null + }, + { + "index": 175, + "op": "advance", + "boundary": "170", + "engineFrame": "171", + "worldTime": { + "numerator": "728642578125", + "denominator": "256" + }, + "mask": 0, + "frame": "5615f00a2f8b8ac91b235854acef4b261c3207da0bbf1af65083ed0c38b511cd", + "memory": "686d4dce8ccb8cfcdc2804abb962f4eecb8494eb33a873da36395f44716e70df", + "wram": "630859191a19f572b45760cf52cfd45f1677d49828aae359a57b42172abb4032", + "audio": { + "firstSample": "135815", + "frames": 804, + "digest": "050beae5ab7efb7786f1163bf535e74d867454b29fd45610cfacc01881eea6d3", + "discontinuity": false + }, + "state": null + }, + { + "index": 176, + "op": "advance", + "boundary": "171", + "engineFrame": "172", + "worldTime": { + "numerator": "1465857421875", + "denominator": "512" + }, + "mask": 0, + "frame": "642d0e87ee3004c8f640ef7663de5169f1670ecb11d121b86d299a79622e009a", + "memory": "c0bf574b85a694db0d355ee84f66432391900dd101efba4f6f4ffe704d9e7cfe", + "wram": "09662f60776c325917920b68df31ae5f93c4511fb7eb06492dac41e507c82630", + "audio": { + "firstSample": "136619", + "frames": 804, + "digest": "5d1615579fe81ca872ec7f0f50f539beffd07418d97eae47a96a295554633e1d", + "discontinuity": false + }, + "state": null + }, + { + "index": 177, + "op": "advance", + "boundary": "172", + "engineFrame": "173", + "worldTime": { + "numerator": "368607421875", + "denominator": "128" + }, + "mask": 0, + "frame": "8d4b7fdc73357fc7195f9492d8b26f6ef6155cb0c136953b9dde66459d318e4f", + "memory": "8d705e14f720b04677ceac8c8814571580fa63590bfd1793367e53ffe1e7dba3", + "wram": "7f8cd2cf7dfe0fb6f8d072c604c790132f4c52cfe666da904b7ac400e61accff", + "audio": { + "firstSample": "137423", + "frames": 804, + "digest": "bd4c9b8407847f7a45c0b7368f72782052b7e0a05fc5c339b2699abc177d8f01", + "discontinuity": false + }, + "state": null + }, + { + "index": 178, + "op": "advance", + "boundary": "173", + "engineFrame": "174", + "worldTime": { + "numerator": "1483001953125", + "denominator": "512" + }, + "mask": 0, + "frame": "137dd530a6480a8d62682affd3534dc615852ccdfc84c7cb892c3fa3e042fecb", + "memory": "b2c838f396b360bb5bf5b1bfe062c0d3db974985ceeabb5daac38773e278d29b", + "wram": "5ecfa57889df577d5ba12a0937f58a2e9d33bd8b8c51f7a32dc65d9b22309964", + "audio": { + "firstSample": "138227", + "frames": 803, + "digest": "019a5679e4b2fd1107d920c2b65355de9eba5a34075ef5583dd8bf410ad86bf6", + "discontinuity": false + }, + "state": null + }, + { + "index": 179, + "op": "advance", + "boundary": "174", + "engineFrame": "175", + "worldTime": { + "numerator": "745787109375", + "denominator": "256" + }, + "mask": 0, + "frame": "2ca3ed99830800a8b597eed9b4b24706f46afcfc26c37fd3320c26d24cbd0a84", + "memory": "9d7698233b4c23d4300689b48b6887522e4587cdf82a4259956ea9977619aab6", + "wram": "7bc3b1bd9860bda60f8fbad1a3d06b406f057ae9cdbb4fcfbe2fe9ac2f8fc535", + "audio": { + "firstSample": "139030", + "frames": 804, + "digest": "586a84eefaf6239eabd6597e623cfc7af93f78b52033f47bba584dce9bd5af3e", + "discontinuity": false + }, + "state": null + }, + { + "index": 180, + "op": "advance", + "boundary": "175", + "engineFrame": "176", + "worldTime": { + "numerator": "1500146484375", + "denominator": "512" + }, + "mask": 0, + "frame": "1c0c3bf36035f19167719a3f9cdf99919c6e0a4c988b865b0d7903ec1dda5bf3", + "memory": "9ff32adc99b128b1af716186d6ebdb539f5ff51d2ecd91c1d3552bfd9fd621f6", + "wram": "bad793a7731fae5935bcc45ab23f7b507c360723a54d2805d75a2f94ded14a45", + "audio": { + "firstSample": "139834", + "frames": 804, + "digest": "bd89219b6722406878a24ca42aca1beeb451c8ec1d64fa5ec2819fdcffb1cbdf", + "discontinuity": false + }, + "state": null + }, + { + "index": 181, + "op": "advance", + "boundary": "176", + "engineFrame": "177", + "worldTime": { + "numerator": "94294921875", + "denominator": "32" + }, + "mask": 0, + "frame": "d3e5d0dc16a361c78a2193305fb8ad61bf302e9eeb031b443b07e68be910b259", + "memory": "0f062a1315d20e7ba55be1cd83651c372e1d70c57e37507726593daf66ef0da9", + "wram": "fde24867a82dd20e3c0f276d3c331f2c385418866f7132e11c876fdf263fe381", + "audio": { + "firstSample": "140638", + "frames": 803, + "digest": "4504e975319194bee04c05f1794199909b502dd92afc49f9924e2ade75fe978f", + "discontinuity": false + }, + "state": null + }, + { + "index": 182, + "op": "advance", + "boundary": "177", + "engineFrame": "178", + "worldTime": { + "numerator": "1517291015625", + "denominator": "512" + }, + "mask": 0, + "frame": "e8fa5ebd8ce0b4bf35fee136518bb7394627f0557e7fc81ff236c60922ad9745", + "memory": "941667e580f69cd0d9699607cb73123cbe094dbcc9f104717f45b6c1f447fdd1", + "wram": "a1c0417ea338897f845eb9a069ee5c39f57d80d25684581b61edca01917f2147", + "audio": { + "firstSample": "141441", + "frames": 804, + "digest": "7da2184f72a64c59e7c6de97c000b7e9661a3d96cb550b182625a17821e92d26", + "discontinuity": false + }, + "state": null + }, + { + "index": 183, + "op": "advance", + "boundary": "178", + "engineFrame": "179", + "worldTime": { + "numerator": "762931640625", + "denominator": "256" + }, + "mask": 0, + "frame": "07ce9fd3dc974d48760f07fa4561bb5440ef969a7e538300c169b457594a0153", + "memory": "5cf65d88375d712f74adff452201ce57801baa3bac4cb4edc44bb6044ba5582e", + "wram": "0983485f650d1e6c2bc9654dbe475a7ae5d90e5d8608cf37692e20b88fa7433d", + "audio": { + "firstSample": "142245", + "frames": 803, + "digest": "48f54fa9559aa50e1ecfccd6fd731787ff352ea4424e35241137d744d89c8e8c", + "discontinuity": false + }, + "state": null + }, + { + "index": 184, + "op": "advance", + "boundary": "179", + "engineFrame": "180", + "worldTime": { + "numerator": "1534435546875", + "denominator": "512" + }, + "mask": 0, + "frame": "53a6da17e11a4439ef47ded75f059af8155f07511dc9d369cd93c456221dd4e4", + "memory": "cf707277a3bf1197b4939af1e09632a5d0d0c2eac702f575588a0f32aebc4e30", + "wram": "71aa010e693ce96ead3ca7176f8efb11fac9cf7d4ec8e7eac9c744642af0abf3", + "audio": { + "firstSample": "143048", + "frames": 804, + "digest": "f344f760f85a65e922f430bc4de48adf201dc8231a367cf9722d8a2b1000dc2b", + "discontinuity": false + }, + "state": null + }, + { + "index": 185, + "op": "advance", + "boundary": "180", + "engineFrame": "181", + "worldTime": { + "numerator": "385751953125", + "denominator": "128" + }, + "mask": 8, + "frame": "3520cd7e27556968aee9ecee57df8b1a5bbcbed90626d563e0150dfaecc85965", + "memory": "47a7c1c73558024fcd2bccfa387fe7ae4e39df3c88954b23a927dcaa1173a762", + "wram": "98faf9f58a802c3b07a444119f261a9d84c9fe5f7d8b86bb7064dcf997b6c690", + "audio": { + "firstSample": "143852", + "frames": 804, + "digest": "9a6915c6c2fa7a982ddfff2087821e1d9f8d2556af0cb7c9639dafc7099fd585", + "discontinuity": false + }, + "state": null + }, + { + "index": 186, + "op": "advance", + "boundary": "181", + "engineFrame": "182", + "worldTime": { + "numerator": "1551580078125", + "denominator": "512" + }, + "mask": 8, + "frame": "53a50210db831d20c781fc40e822559e99ac1839423c7214739fe646edaa833e", + "memory": "44db19229a81262032cd3fca559f922029fde50864b9214456e71bca824f92f6", + "wram": "eb8eb48fd3f1c0a93ca5f06d190cd2eae33a46d5df33d927245d55509cedf217", + "audio": { + "firstSample": "144656", + "frames": 803, + "digest": "96b093d5bf6168add9b2c7629fd036703da9ef4fc579eca2bc2f083b6e1199b0", + "discontinuity": false + }, + "state": null + }, + { + "index": 187, + "op": "save-slot", + "boundary": "181", + "engineFrame": "182", + "worldTime": { + "numerator": "1551580078125", + "denominator": "512" + }, + "mask": null, + "frame": "53a50210db831d20c781fc40e822559e99ac1839423c7214739fe646edaa833e", + "memory": "44db19229a81262032cd3fca559f922029fde50864b9214456e71bca824f92f6", + "wram": "eb8eb48fd3f1c0a93ca5f06d190cd2eae33a46d5df33d927245d55509cedf217", + "audio": null, + "state": "eceb68ba5c8c6ba1ba4833766a468bdef834dec57d8795aa4d329a53b97cedbc" + }, + { + "index": 188, + "op": "rollback", + "boundary": "181", + "engineFrame": "182", + "worldTime": { + "numerator": "1551580078125", + "denominator": "512" + }, + "mask": null, + "frame": "53a50210db831d20c781fc40e822559e99ac1839423c7214739fe646edaa833e", + "memory": "44db19229a81262032cd3fca559f922029fde50864b9214456e71bca824f92f6", + "wram": "eb8eb48fd3f1c0a93ca5f06d190cd2eae33a46d5df33d927245d55509cedf217", + "audio": null, + "state": null + }, + { + "index": 189, + "op": "advance", + "boundary": "182", + "engineFrame": "183", + "worldTime": { + "numerator": "780076171875", + "denominator": "256" + }, + "mask": 8, + "frame": "548df337e7d6185a9c2537b48bd42ef9ede7cb25b3ae8d1c9ad6cbe082ee717f", + "memory": "f8630fbacd8c6311a069f69942dbed095f9710c555c1ec9ac55d7f9f08eb360e", + "wram": "a82ebb24578ecce93955f87a0f240f3b41bd1d1b52700b935c95d8d2b6f697bc", + "audio": { + "firstSample": "145459", + "frames": 804, + "digest": "9e55cd8d2ceff3608f32eab1ba9df5186885ebf7d3859cd1b2acabdc2903a107", + "discontinuity": true + }, + "state": null + }, + { + "index": 190, + "op": "advance", + "boundary": "183", + "engineFrame": "184", + "worldTime": { + "numerator": "1568724609375", + "denominator": "512" + }, + "mask": 8, + "frame": "13058c26459c4909c8dcb7645083d61675a520ae26461d9d183abefdc0a9282d", + "memory": "db51f934e261be89caf50389fb3d4cd01ceeb3bde6f0e7b39d69321a896c85fc", + "wram": "8a3cd7bc86943ad99084b1fe420c7c81623a4b051886d8fe38d64d87f517e62d", + "audio": { + "firstSample": "146263", + "frames": 804, + "digest": "821e77f45560567a2bf7dd4d5d54aa8d6c2bbc38300cb6940481afa5b5c23b18", + "discontinuity": false + }, + "state": null + }, + { + "index": 191, + "op": "advance", + "boundary": "184", + "engineFrame": "185", + "worldTime": { + "numerator": "197162109375", + "denominator": "64" + }, + "mask": 8, + "frame": "b4a8d96dc16dcfc6ac7cae71e43b96863117177577abf7cb2f72dbc0e81364c7", + "memory": "048aee733aa6ad9b885dc8ff8111cb06630e9e9b3fea74b4b6a7767af16f2cdd", + "wram": "2a916fbdfb4cb5f94299eac4e04a70c1183231df65cb7dfa207b312ff451c66e", + "audio": { + "firstSample": "147067", + "frames": 803, + "digest": "cb2c6e8d7afbffd00e713825a2b25db15aaeb31b9e8e0cfda794880c5c333316", + "discontinuity": false + }, + "state": null + }, + { + "index": 192, + "op": "advance", + "boundary": "185", + "engineFrame": "186", + "worldTime": { + "numerator": "1585869140625", + "denominator": "512" + }, + "mask": 8, + "frame": "c40d9409de1693dec77fb788f2ed6b5b5d5e24954e82feab6b69becbe14179cd", + "memory": "200880bc20bf4244e8384ff889bfdb16f9f9d9c70c3828648e563d1be3d3e587", + "wram": "9af982ef521366e4cb33d5f0a85354963075716ca3228421455ac74ac853c31f", + "audio": { + "firstSample": "147870", + "frames": 804, + "digest": "98ddb8e2f2293c198a8d3a82aed6ffa0a07bfc156eb7c865d71d407493f29cc7", + "discontinuity": false + }, + "state": null + }, + { + "index": 193, + "op": "advance", + "boundary": "186", + "engineFrame": "187", + "worldTime": { + "numerator": "797220703125", + "denominator": "256" + }, + "mask": 8, + "frame": "70688798b946e301195645495b30f225f73e51301de3e3ced9422ffa901345cb", + "memory": "7c0a729ce7b730628f0d82a82752f6d35baadf9f3e86560ec5c7747c283a6e6e", + "wram": "49e92231dd03bb89472789b84086421d7e5efa22e51de87e28038103b234db35", + "audio": { + "firstSample": "148674", + "frames": 803, + "digest": "5b63691641c288c4b4e1af275fadecbec79a2fbb90699165b4c5ff41bc2b81ae", + "discontinuity": false + }, + "state": null + }, + { + "index": 194, + "op": "advance", + "boundary": "187", + "engineFrame": "188", + "worldTime": { + "numerator": "1603013671875", + "denominator": "512" + }, + "mask": 8, + "frame": "39801c72df6d19efd63feba9f39675256fc41761e5122e7cef14ab716b7dba22", + "memory": "2c33158bebf61d1e019a11c39c4c0c2234f7b7ad2fdbbbadcb21f99ee64dac00", + "wram": "69092e9a8ede10457018edd9386313214db5d4329c2c6de54132fec346a253ca", + "audio": { + "firstSample": "149477", + "frames": 804, + "digest": "bce9da5622ee111f529451e576cc6aac704a7c36c0e878c081592561cf7cb6af", + "discontinuity": false + }, + "state": null + }, + { + "index": 195, + "op": "advance", + "boundary": "188", + "engineFrame": "189", + "worldTime": { + "numerator": "402896484375", + "denominator": "128" + }, + "mask": 8, + "frame": "b3fa87634c5a8810a0952c5cc141fa02d21b28344fb7286b24a76b17b70b97c0", + "memory": "72e2a6e5a8dfec5dc45d63744d1d400ddc18abb2475597c5f37f717dfac62e0f", + "wram": "187c1441e67c64c4bfd62ba6bd12491d0fc4bf86d3b8d033fbd64d07de99b08a", + "audio": { + "firstSample": "150281", + "frames": 804, + "digest": "7c75b7c7ea056a3fd1dc03ad7242bbd23132b7d064a92f5f20fc4008122911d0", + "discontinuity": false + }, + "state": null + }, + { + "index": 196, + "op": "advance", + "boundary": "189", + "engineFrame": "190", + "worldTime": { + "numerator": "1620158203125", + "denominator": "512" + }, + "mask": 8, + "frame": "4259a86dece8fba61c9fdecbd72961ea9c1b0bbee17022e3386324cf4310e486", + "memory": "3e92ebb4a94f9e4998e339807dbf0a509e255e8c7d999e530fb060d495082bd8", + "wram": "ba18f7c0c8cda7412e64952bf30c574736efa10c3235fa684d3d3b03c39ab2b2", + "audio": { + "firstSample": "151085", + "frames": 803, + "digest": "6d957c5877d6c729a8b8719b07b89d685c6cf2e04e904f533948bcecf9177078", + "discontinuity": false + }, + "state": null + }, + { + "index": 197, + "op": "advance", + "boundary": "190", + "engineFrame": "191", + "worldTime": { + "numerator": "814365234375", + "denominator": "256" + }, + "mask": 8, + "frame": "0578f3afea601bb050a32076fb626b0349ccbf10b5a6144abf10ee09105a1ce6", + "memory": "0a18f23693e4dd8df07fbcb4eac8c0a0dfcce26ef8b7809ce8db34abd6cef35c", + "wram": "bbeebd23e2004f74a024b609b198cc596e9c8b650e2bd0e6991dfeaad50ae888", + "audio": { + "firstSample": "151888", + "frames": 804, + "digest": "138998cbde95cd69b46055142871473f32b98b2ed5a8fc374548ff2aa25c7efc", + "discontinuity": false + }, + "state": null + }, + { + "index": 198, + "op": "advance", + "boundary": "191", + "engineFrame": "192", + "worldTime": { + "numerator": "1637302734375", + "denominator": "512" + }, + "mask": 8, + "frame": "0e7819724dd54c89f90fd85deaa891fb82d2edd325e0c23018ca73d3095b4435", + "memory": "cd02f2ed251f2fa629495481b598a3f81f49216b6fc5b06f354beb8fa99dff28", + "wram": "eae713cf0222ca2cfaceeb77f44fb52d7012ad9884b0545d2b97d81761fe7e31", + "audio": { + "firstSample": "152692", + "frames": 804, + "digest": "fd0489e2ba31a5688f493b284028dd26988831713931065a1cdb509070432cfe", + "discontinuity": false + }, + "state": null + }, + { + "index": 199, + "op": "advance", + "boundary": "192", + "engineFrame": "193", + "worldTime": { + "numerator": "25716796875", + "denominator": "8" + }, + "mask": 8, + "frame": "156ba76c4775c10937039ec74ab181b32747e56811b8faf4448672f0ac505a6b", + "memory": "c33c7260620895f90b48e555d45624bf587f1c5f04f73efc6587ed13d4d04382", + "wram": "1662fd2ee13b06b8dac9c2efaed2fe78ede441815257c13719ddd3a98e17ee55", + "audio": { + "firstSample": "153496", + "frames": 803, + "digest": "f212a656a54587bca013728f3f075e7dd99c1475632d99cc91c492edaf8206af", + "discontinuity": false + }, + "state": null + }, + { + "index": 200, + "op": "advance", + "boundary": "193", + "engineFrame": "194", + "worldTime": { + "numerator": "1654447265625", + "denominator": "512" + }, + "mask": 8, + "frame": "0904f8f1d625c12cf0532f0bc6bd412158660918df7466436397b458587a4f9b", + "memory": "8823f9d32b2352673d833616511db008f92f406a8a4164bd238880f8d3223e58", + "wram": "ada336e932af820388833209a489f19508ff1ad8633b5e63080f7bacff11de6b", + "audio": { + "firstSample": "154299", + "frames": 804, + "digest": "1e1a23140d851144eb2197e8fb718aa30b24c84f74b7b3eed329bb4ff98b7b18", + "discontinuity": false + }, + "state": null + }, + { + "index": 201, + "op": "advance", + "boundary": "194", + "engineFrame": "195", + "worldTime": { + "numerator": "831509765625", + "denominator": "256" + }, + "mask": 8, + "frame": "ece1e3d022b097fdea91d62eb879f06e156a2a613c462473e2a1da35dcf1d332", + "memory": "88178ea295bc8ae93aa268fb6f2e77e16cb389dfe28edf4d84739d9da5fd0a35", + "wram": "e7a3d8c2a08456067412f40e658ccd42ca53f5b988cfcb2b7855b42d11f60abe", + "audio": { + "firstSample": "155103", + "frames": 804, + "digest": "831e5583a013b9a53c10eff9c25619f54b93bca68bd67802abdc8bd4912316c3", + "discontinuity": false + }, + "state": null + }, + { + "index": 202, + "op": "advance", + "boundary": "195", + "engineFrame": "196", + "worldTime": { + "numerator": "1671591796875", + "denominator": "512" + }, + "mask": 8, + "frame": "12df6484dcb1804ae862f4337129ef5af0a4ca4a8468e4a49dee65f35b123dbf", + "memory": "6c2a891e46aaa8c2fe733d9efb3008ef4dfb50ca16526913bee7db3987375d1b", + "wram": "650104c4e26c0ce5a5c661f41c49cc76690317fa90fbb7f2f778ab77aaa10b30", + "audio": { + "firstSample": "155907", + "frames": 803, + "digest": "6bff3890191119aa9405c8ecf1d349cd88c857574e6650ccf7e93d33cf743546", + "discontinuity": false + }, + "state": null + }, + { + "index": 203, + "op": "advance", + "boundary": "196", + "engineFrame": "197", + "worldTime": { + "numerator": "420041015625", + "denominator": "128" + }, + "mask": 8, + "frame": "ee7c3ce7e021086feb4773ff45e8fb9b2feb1b3d5e90333fb0d9981b4ea306f1", + "memory": "807646a17789fc13ed011d175687539ef37c815365cc683c722b187679b9a466", + "wram": "16affdc887ae6ab3226b048e038746bf378971fbbce90618f8b41c1147eb6b03", + "audio": { + "firstSample": "156710", + "frames": 804, + "digest": "e9b97afd48acb089c7d9b2e9a8018e45c47edb95cc8135e669ea748c8addbb57", + "discontinuity": false + }, + "state": null + }, + { + "index": 204, + "op": "advance", + "boundary": "197", + "engineFrame": "198", + "worldTime": { + "numerator": "1688736328125", + "denominator": "512" + }, + "mask": 8, + "frame": "26f0b75df6674e3df6fd62d29dd4dc55752e3b05fdbbfc5850cab3e28cb96285", + "memory": "e14bcd233397bed95fa2b7d2e6a7d39ccee7418c6de6bfe77ac8ef600291b6c3", + "wram": "768b97568ed2c11c2cd36150a874927e427bc55396e84149bde0832dfb88b46e", + "audio": { + "firstSample": "157514", + "frames": 804, + "digest": "eb4d5565ac86c1b9780bcdc6448a666c36992797fb0750258a1c0514499e69ca", + "discontinuity": false + }, + "state": null + }, + { + "index": 205, + "op": "advance", + "boundary": "198", + "engineFrame": "199", + "worldTime": { + "numerator": "848654296875", + "denominator": "256" + }, + "mask": 8, + "frame": "070b78b62de183d7270e8dd5d609cac5baa25cf7990f7fc786b8f4069374fd66", + "memory": "b43ad218e2e9c1cceb207c7453b300330f03e33bfa8b2607fe4a814c74fc22bc", + "wram": "1bd9f0184b38eee91b4a980a8eca84958b4373fca904c989a08ddc5049848afb", + "audio": { + "firstSample": "158318", + "frames": 803, + "digest": "d88a090c40810c09f5f1fb51b2181d7522aad06a875e464b53f153aa38047083", + "discontinuity": false + }, + "state": null + }, + { + "index": 206, + "op": "advance", + "boundary": "199", + "engineFrame": "200", + "worldTime": { + "numerator": "1705880859375", + "denominator": "512" + }, + "mask": 1, + "frame": "9acd3e040056d43fe1f1ef83417bc5fab487235db5011b1b4dc5e2ddd8ef5738", + "memory": "000560f1252b7b6271ab9f1abbaef0d435ce8fd672270c5e479e4cbeb9023ae4", + "wram": "c596d5ba664d46aceaf1dceb162523db94ead09a325480277a6332924b6f89e6", + "audio": { + "firstSample": "159121", + "frames": 804, + "digest": "1fa9e1d0e23b93cc774082b8f8da4ba0d1fd8392083b5c69a0a797fa2ace726a", + "discontinuity": false + }, + "state": null + }, + { + "index": 207, + "op": "advance", + "boundary": "200", + "engineFrame": "201", + "worldTime": { + "numerator": "214306640625", + "denominator": "64" + }, + "mask": 1, + "frame": "8d5950e22b3cc0730f9e06fb61fbed0be0f4189abec6304eaf22511e2be586fa", + "memory": "1d56a4a449da0e5ce1a6fb070ca4269f7b551013a8ef6c60f91abda515cf85a8", + "wram": "ad90606b6e2214b92f19b681779a5f4bc0a1980cfe7f13785a82f0e5e646735b", + "audio": { + "firstSample": "159925", + "frames": 804, + "digest": "4a6f59bf2088c1318a135f804e3e65a53582278afe57352fa8bf5e14b3cff39d", + "discontinuity": false + }, + "state": null + }, + { + "index": 208, + "op": "advance", + "boundary": "201", + "engineFrame": "202", + "worldTime": { + "numerator": "1723025390625", + "denominator": "512" + }, + "mask": 1, + "frame": "91b83e3540d1d45ad18df668cd082ba5cb0b8dec5bdc93be129497ef7b9037a3", + "memory": "428aa464ca87ce9e644b806d6af150aded749c0cac7cde5a3840380c47a767d7", + "wram": "baae0d745a85483dd09b35539e3fbe411ec3b71c553ea85991e6c01f0eccf1df", + "audio": { + "firstSample": "160729", + "frames": 803, + "digest": "73edc1fc4e89e8cabb94be970bc9ba00ef52fcf107a094063bb6ce6d1d91261e", + "discontinuity": false + }, + "state": null + }, + { + "index": 209, + "op": "advance", + "boundary": "202", + "engineFrame": "203", + "worldTime": { + "numerator": "865798828125", + "denominator": "256" + }, + "mask": 1, + "frame": "074e2a99fe0958f3ed098775329a4da4fef1d0c0d753a3139204899c864e911e", + "memory": "5707051431a9d4cbe3cebcc137cf0e7b51dc119590baf70acfda9baf080c60f9", + "wram": "dbda4bd3ece56b9f40fefa8319bf1ea0e98bc3b82cbef28972550c7808f1e80d", + "audio": { + "firstSample": "161532", + "frames": 804, + "digest": "8fd7227d0f3eb97163b040f6947904fa1878196ee2505f895fdffab9f511cc47", + "discontinuity": false + }, + "state": null + }, + { + "index": 210, + "op": "advance", + "boundary": "203", + "engineFrame": "204", + "worldTime": { + "numerator": "1740169921875", + "denominator": "512" + }, + "mask": 1, + "frame": "6f13c04473521a0fc23c2f373da8eea8e9917198d448d3b51c9febf6ac2ec172", + "memory": "c146cbb3694d9221dffb988f78145034dea01f3511dd2034ef16d50c744f0a41", + "wram": "f0170356ccf561cf2fa6a3f968f685908494577245fcbe7151c1c7721f0d2259", + "audio": { + "firstSample": "162336", + "frames": 804, + "digest": "c12673f832858a901c3456983c239f92ded85d481dd97fe3fa1531882c7f2573", + "discontinuity": false + }, + "state": null + }, + { + "index": 211, + "op": "advance", + "boundary": "204", + "engineFrame": "205", + "worldTime": { + "numerator": "437185546875", + "denominator": "128" + }, + "mask": 8, + "frame": "57d6df661171ac464e878f0637cf8d9d0505dc4a965cbee3d3d6047442262edb", + "memory": "82d7a1ea3e7eca7d0634e7d11f2979bdbd5e9bb3cdccab9728efa9a22ede85ac", + "wram": "60a2bd0ffedc0ba67b66707c1b59d97722c2acfad565478b40933542ddf35695", + "audio": { + "firstSample": "163140", + "frames": 803, + "digest": "9747a18d3e8d252d58f3093a56202d94f0e34c5d49a223559f107f0a8be45fee", + "discontinuity": false + }, + "state": null + }, + { + "index": 212, + "op": "advance", + "boundary": "205", + "engineFrame": "206", + "worldTime": { + "numerator": "1757314453125", + "denominator": "512" + }, + "mask": 8, + "frame": "6cba02dbf825145cc07806d2dc3ade17e6b088647f99936b9a909560e9cf7647", + "memory": "1845abc6768dfde671a64bbe37fd85ceedf3a6b61fdf6a0b15e1b9ecbdd57c65", + "wram": "c1fb67f1b975243ead0203e119035aa4e8af9f7011623cd79c87e6a477c3c239", + "audio": { + "firstSample": "163943", + "frames": 804, + "digest": "b00cbeef1cd8df726f8e9b4c0360636479ab1a27574ffecd084fc28a2299ba81", + "discontinuity": false + }, + "state": null + }, + { + "index": 213, + "op": "advance", + "boundary": "206", + "engineFrame": "207", + "worldTime": { + "numerator": "882943359375", + "denominator": "256" + }, + "mask": 8, + "frame": "2924ff348e30d714820a2ebb9c22048a956a352ef60bbbbf4c7f274844494737", + "memory": "49198c5f47523e4db41aff0fe9233fd4f213f5cd065aa5855f50d3bc9aa8579e", + "wram": "4bd5fb590562145197c0e507bc9afceac842990ed7bbf165ff066f56a3d114f5", + "audio": { + "firstSample": "164747", + "frames": 804, + "digest": "da18fca7f1634592903fbfa24a6825ae449a6fec733f8ff373833e151a103a1d", + "discontinuity": false + }, + "state": null + }, + { + "index": 214, + "op": "advance", + "boundary": "207", + "engineFrame": "208", + "worldTime": { + "numerator": "1774458984375", + "denominator": "512" + }, + "mask": 8, + "frame": "dcafa4cd7c189c8f04b910f4ee20134c8af34f1bc31981e1eb0d3b398791861a", + "memory": "98dadb7805c696bd98a76c955bf69cd4de840baf84ac2b1d8495b8dd6de0438e", + "wram": "37120708b99fe73d33afa7c7c502ba395486b8c2ef596a3f8b9548c31596b889", + "audio": { + "firstSample": "165551", + "frames": 803, + "digest": "c297e697cfa91c814f00771f56febed08ee389b830139c36112849a097241933", + "discontinuity": false + }, + "state": null + }, + { + "index": 215, + "op": "advance", + "boundary": "208", + "engineFrame": "209", + "worldTime": { + "numerator": "111439453125", + "denominator": "32" + }, + "mask": 8, + "frame": "5b8dc52d943d4f8aa8923102ae1c13065d605e07d4802b8fa54eb94ecffb5652", + "memory": "ca14135628fd8d8798ebff254855d7a88ea23372b530c8f9f0cf6170894ee0e8", + "wram": "2e0ed8f605a733ae2e72d938141caf56e81054f2c1a3e823cd93ecb0c4109748", + "audio": { + "firstSample": "166354", + "frames": 804, + "digest": "39937480b66da113de6d4f750bb5ffa9b74fb9a21d544e3afd677a54520250de", + "discontinuity": false + }, + "state": null + }, + { + "index": 216, + "op": "advance", + "boundary": "209", + "engineFrame": "210", + "worldTime": { + "numerator": "1791603515625", + "denominator": "512" + }, + "mask": 8, + "frame": "9d703c7edd72a2229a2b743b56ec9bbec2cfdd6b12749aabf39ebb8c8f426b65", + "memory": "362ee108ced284d77ce8005403cd93c3036b0c40409e145d32f807242547fc04", + "wram": "51bbddaaa741b3549d15426326738991e5b3b70eda73c9bfd86270ac9e0c0421", + "audio": { + "firstSample": "167158", + "frames": 804, + "digest": "80b1c90f11c7a209ebe76d769abb468849b90eba284428bd37d9e14d79316e9b", + "discontinuity": false + }, + "state": null + }, + { + "index": 217, + "op": "advance", + "boundary": "210", + "engineFrame": "211", + "worldTime": { + "numerator": "900087890625", + "denominator": "256" + }, + "mask": 8, + "frame": "bae7a850b57436877d832fce14a91c157b45565494db416b177053a5fc7bb307", + "memory": "0f8a8f809066a011dedc85e1d13df740cee66e362499acf7425ebc5a029c9e5f", + "wram": "b3425b7786cd55dfec7e0a1de7bbb9bd6731093adea7fe41471181a31339576a", + "audio": { + "firstSample": "167962", + "frames": 803, + "digest": "ad89f1cb7fe3fc36bf3f9617073d852a815c5ee1ef1b8a98fdc7a2ff1c6cb127", + "discontinuity": false + }, + "state": null + }, + { + "index": 218, + "op": "advance", + "boundary": "211", + "engineFrame": "212", + "worldTime": { + "numerator": "1808748046875", + "denominator": "512" + }, + "mask": 8, + "frame": "e68dc063f6e0a89b1b17d58c6e0db3d2feafb17128fb0c391a8def1968d367ad", + "memory": "126435b5cb3a43bf7837abdd73beb90e87d7da5181f9f75c251cffa774a993e4", + "wram": "968cbb1c2395ba97cf0132b738ff64eb8a526d5eccdfa7321255268ffed69e07", + "audio": { + "firstSample": "168765", + "frames": 804, + "digest": "357f34515b9739bc2a37673012eececc3081677ca828b279108dde21687541cc", + "discontinuity": false + }, + "state": null + }, + { + "index": 219, + "op": "advance", + "boundary": "212", + "engineFrame": "213", + "worldTime": { + "numerator": "454330078125", + "denominator": "128" + }, + "mask": 8, + "frame": "07d6b8fd7e97c484c25b8fa15e627b2c98efdab11a9a0749808d493d142e93f1", + "memory": "af4ce5509c7c16cf9f230582e876c56f12d140ddeff640335bb73ef4b26f5112", + "wram": "1f157737327429e63a3efd39bfb776b31e948791ed92ac73be297d7aa67e0d0b", + "audio": { + "firstSample": "169569", + "frames": 804, + "digest": "78ff3b9ec9b2af746fd911882857d5569904208f2f99ee3edc2168206c12bc45", + "discontinuity": false + }, + "state": null + }, + { + "index": 220, + "op": "advance", + "boundary": "213", + "engineFrame": "214", + "worldTime": { + "numerator": "1825892578125", + "denominator": "512" + }, + "mask": 8, + "frame": "52f14f58fc744bdc0933caa91267ad63a33b70be09df5556a55bbf6488961f22", + "memory": "4ba2cd5499c4f37cf2dd2dd643cd3ee73983ab2187d5cd1e96e554936046fefa", + "wram": "c13b0cd5619e195dc391b475c1e160122b668bb33777664131afc650af2844cd", + "audio": { + "firstSample": "170373", + "frames": 803, + "digest": "52cbe558c8cd29b90ac9b4771ee1b45a5069279a70c2f1061e42787b337a36b4", + "discontinuity": false + }, + "state": null + }, + { + "index": 221, + "op": "advance", + "boundary": "214", + "engineFrame": "215", + "worldTime": { + "numerator": "917232421875", + "denominator": "256" + }, + "mask": 8, + "frame": "7c3593bf3fbe546145a4a91d40857b0e89bcda6051ebfe6efd17b48c2af685b8", + "memory": "b34f82939bbca32caa73c3c53d140d5751ff278826baa5a51754f74bdae4f375", + "wram": "b8a252b8900d7c2447f8e9d4d3ba6a577237dcd2b013981746a7dd263033957f", + "audio": { + "firstSample": "171176", + "frames": 804, + "digest": "46a52103cb3eef1a48e4790cce247b5d06dad07f7b26ef7a1304c1f0cc00cc15", + "discontinuity": false + }, + "state": null + }, + { + "index": 222, + "op": "advance", + "boundary": "215", + "engineFrame": "216", + "worldTime": { + "numerator": "1843037109375", + "denominator": "512" + }, + "mask": 8, + "frame": "3417b86f160ff0097576a0ce6979bc618d4e41b7e58f386cd6b491bd946ac48c", + "memory": "40872ece17ecfaefa1d14c8cef3fbf2940e388f03d76f40d840544eb30fb26ed", + "wram": "9ce4abdbdb579cd2801e75e03705691e3225f94a19b956afdfa742f0394c3154", + "audio": { + "firstSample": "171980", + "frames": 803, + "digest": "51d4a66cdd3fa8211a5d67d1e5cb8ee6333acec4b4c91fe2b7d01712135ff8f3", + "discontinuity": false + }, + "state": null + }, + { + "index": 223, + "op": "advance", + "boundary": "216", + "engineFrame": "217", + "worldTime": { + "numerator": "231451171875", + "denominator": "64" + }, + "mask": 8, + "frame": "96bab8734c98ff2fe825c654f99156cd95f852fc1caf342c4aef051a3ec14257", + "memory": "5aa562c2c0045d7ad3e2461563b5a5d39e58857ad9a321188c8efeb78d25612b", + "wram": "b9c4811fa190e9e3e2ac3ad6d1dd995d6cc63b4a0e6ec39c93d4156620adaf2b", + "audio": { + "firstSample": "172783", + "frames": 804, + "digest": "78ec1d9692b2d5cfe19e16b564e1cf9b34f189018fac1e91ba3979e0d397d212", + "discontinuity": false + }, + "state": null + }, + { + "index": 224, + "op": "advance", + "boundary": "217", + "engineFrame": "218", + "worldTime": { + "numerator": "1860181640625", + "denominator": "512" + }, + "mask": 8, + "frame": "2e5be93785f5459d3a67da26b4c97b2a7485c6b3f6e238d15d29c0c97102b68f", + "memory": "dce2f4c6e996282de9e6aa307c3b997a0c80fe9a53fcf2ac001ac2610c1d8816", + "wram": "364907dee8ac984fe8278064ad7d0fc0a0e3d97705bffbc18bedf24f8c41b91a", + "audio": { + "firstSample": "173587", + "frames": 804, + "digest": "2430e425ae288d9b0caff3d5378f747d9b141a44153972e61bf4f99cf099216f", + "discontinuity": false + }, + "state": null + }, + { + "index": 225, + "op": "advance", + "boundary": "218", + "engineFrame": "219", + "worldTime": { + "numerator": "934376953125", + "denominator": "256" + }, + "mask": 8, + "frame": "e8c911372daba1b8377be98ed4c238414627ad8e3387a61f207db85ec38085df", + "memory": "1109cf126c416c51489177ab590d52466a1da9d9b7c9c7d38934378f0ecfc6bc", + "wram": "d13fd05b034e300516600b1afc3dbb97430ea0ed85a953818f2999ebf5f06159", + "audio": { + "firstSample": "174391", + "frames": 803, + "digest": "093cb74db3fd5cac12b0fc383474518f20424c555a62deb90f5fc5db5fdd3d43", + "discontinuity": false + }, + "state": null + }, + { + "index": 226, + "op": "advance", + "boundary": "219", + "engineFrame": "220", + "worldTime": { + "numerator": "1877326171875", + "denominator": "512" + }, + "mask": 8, + "frame": "4ff2d73ab463610decf56c5ab38cf31f9e190fe5bc0da1fe678f82dde5a2d785", + "memory": "6ae3ce75983b2fec28f7231a3e2b69a5cc364fbd07a8abbfd860ba3d23e9b6a1", + "wram": "b672393631b1a59ec2d3aaedbb563768b70740da8564e47d34ec758ef06a917c", + "audio": { + "firstSample": "175194", + "frames": 804, + "digest": "db67338441c1d47572e54512236c38af964499a271b55a73f7b92a2b79fcd0c9", + "discontinuity": false + }, + "state": null + }, + { + "index": 227, + "op": "advance", + "boundary": "220", + "engineFrame": "221", + "worldTime": { + "numerator": "471474609375", + "denominator": "128" + }, + "mask": 8, + "frame": "abc90ba2d5a5471e6f6f80ce4f93cde6ca3d96dab73c80849bdc75e7651b5a55", + "memory": "8141e28c550aedc5eb3801dde7ff34d3e29661d1fac7c201514bb0a4ca1b4452", + "wram": "108b03e3174aa54b23abaca97509ae0f8db49cf3c2831fd883f900be29d0cf64", + "audio": { + "firstSample": "175998", + "frames": 804, + "digest": "229e46b29e48a23e6161faa45b47cfd8f37ac9974e2ad0df03a3cb75fb0ee592", + "discontinuity": false + }, + "state": null + }, + { + "index": 228, + "op": "advance", + "boundary": "221", + "engineFrame": "222", + "worldTime": { + "numerator": "1894470703125", + "denominator": "512" + }, + "mask": 8, + "frame": "6cbc4ced50947d45172bf9f2e6e8e312b8a1b13459d3e96e2aff699bc8695d79", + "memory": "cad432c960c77bda92f99896042304d0c5008f832b5fb32794dc930fe58cf722", + "wram": "0d2b3b8dbaa5230131cca87ed55c3995f403544d0f4eac6f866ad2891dd75110", + "audio": { + "firstSample": "176802", + "frames": 803, + "digest": "f5309aed3895dfaaa04f3b7b473a3f3fc8f6fe30684f0a3398450abefb7424c4", + "discontinuity": false + }, + "state": null + }, + { + "index": 229, + "op": "advance", + "boundary": "222", + "engineFrame": "223", + "worldTime": { + "numerator": "951521484375", + "denominator": "256" + }, + "mask": 8, + "frame": "68eb1f49572f2225bac13f5c2509c6bbf9bbff622322a7d518f4655cde4415d8", + "memory": "ebd4f46249168fdf0327d749b8d3b515b8b97156eebd97a03c60b27fb0cb3b96", + "wram": "0767b53465401e5f91e86a7c14210a4bbbb821c40a234e767cf4f170f8420456", + "audio": { + "firstSample": "177605", + "frames": 804, + "digest": "31619ea327219af52629fb51bf128eb65ef42661e4b7d2eea191efc8f3d5b347", + "discontinuity": false + }, + "state": null + }, + { + "index": 230, + "op": "advance", + "boundary": "223", + "engineFrame": "224", + "worldTime": { + "numerator": "1911615234375", + "denominator": "512" + }, + "mask": 8, + "frame": "2b825f6a37dbaa90752a2590fe23dec97b779e2b264996c3a096cb3738bf2a00", + "memory": "a63d0082486d0d81145b62baf92096e072c20684bbeb1dde288ba0d599ccb7cc", + "wram": "b9103097929e71c6211077ba7efde39776c3824ae3ac4e95c135a29b45cb240b", + "audio": { + "firstSample": "178409", + "frames": 804, + "digest": "43ec1876f340c1afe463844b9dbc5e1b2ceff067aab8aab93cf4421fca2fe3ae", + "discontinuity": false + }, + "state": null + }, + { + "index": 231, + "op": "advance", + "boundary": "224", + "engineFrame": "225", + "worldTime": { + "numerator": "60005859375", + "denominator": "16" + }, + "mask": 1, + "frame": "44868a9fab3aa5f1d64ea98bdc59bb3a97e4e74d35bd9ecedf2d10c3e9cc24dc", + "memory": "8d782f479f6fbd2e214d666ea24373d15e66714dd9f8e9ef785f4ecf81f03070", + "wram": "257ae63d75a13ea9c7568ba61d88747d790e122ee4d5656c10adb81ba18979b9", + "audio": { + "firstSample": "179213", + "frames": 803, + "digest": "1c25f7cc4d44a719d37a9f50448b0b2536321b7b0a096e006917c0411f650825", + "discontinuity": false + }, + "state": null + }, + { + "index": 232, + "op": "advance", + "boundary": "225", + "engineFrame": "226", + "worldTime": { + "numerator": "1928759765625", + "denominator": "512" + }, + "mask": 1, + "frame": "4a6b0b8f1651f2b995fb3341775b7c19413d619067a1106e27cd836fe63215a7", + "memory": "84a0b79747c4ea05c11bb3d2ee741541618686851c72068d4b8d410a745a5cbd", + "wram": "c69a64737dbc7e5f120a21b1ff2753894cfed0caf289212ab05a4bd1b7f31e90", + "audio": { + "firstSample": "180016", + "frames": 804, + "digest": "45704fe8ebbd203812a55333ac9b96077ebba5dc497cac377754c1fd4384f26c", + "discontinuity": false + }, + "state": null + }, + { + "index": 233, + "op": "advance", + "boundary": "226", + "engineFrame": "227", + "worldTime": { + "numerator": "968666015625", + "denominator": "256" + }, + "mask": 1, + "frame": "1c66ad5994268f84439344a38fb56ce6b0c607c50dccac42b75af23fb6746982", + "memory": "6aab844e5401355cf4c21c6f08a70ef1142063c55d6bdc85bf0f18dcf98402db", + "wram": "2fc8aa8a856e17120c7edd70ad2197baef472b61bd474eb1cbe6b6e3ff921e2a", + "audio": { + "firstSample": "180820", + "frames": 803, + "digest": "cee59c93553a44aefc5d50a1fb86fb56a23d87f68ed333434cc8010a15840c1a", + "discontinuity": false + }, + "state": null + }, + { + "index": 234, + "op": "advance", + "boundary": "227", + "engineFrame": "228", + "worldTime": { + "numerator": "1945904296875", + "denominator": "512" + }, + "mask": 1, + "frame": "117c3284f558d98cc13268a44246e8056776f273777fc7585b3d3be68148bc08", + "memory": "530eb559a7979893d15fcf43fd6c58ebafa7e2afcc41a07090010d16486a0820", + "wram": "96613217eec68543765ee18bcd3900ac89b2a31ff681efcf1fba24471195c157", + "audio": { + "firstSample": "181623", + "frames": 804, + "digest": "225810db5c0c0cb9eba08027d481ed70da6dec4dc0d5c5a357a4ebe796ab52e1", + "discontinuity": false + }, + "state": null + }, + { + "index": 235, + "op": "advance", + "boundary": "228", + "engineFrame": "229", + "worldTime": { + "numerator": "488619140625", + "denominator": "128" + }, + "mask": 1, + "frame": "55d3f0e40df508cb2b276d69e14819f2ee715dfc215dd452caac2f3fd1bab7f3", + "memory": "f2633184f9c2fdddff8f312e58e0c42d0a184873962583a4c2f864b283aabf15", + "wram": "03b63a57c24174c5f57fe73bc3fadb8319864cdcf775f784347256647a27b225", + "audio": { + "firstSample": "182427", + "frames": 804, + "digest": "3a06e2cda33e4ef9ee5bcde97bc5dc00f6921463ae4c0014976d8bd2fa9f5443", + "discontinuity": false + }, + "state": null + }, + { + "index": 236, + "op": "advance", + "boundary": "229", + "engineFrame": "230", + "worldTime": { + "numerator": "1963048828125", + "denominator": "512" + }, + "mask": 1, + "frame": "156a5367bd9d102d2e5a7a4d5a0ba713bb306b24db99d281d8285334f9dfb8f9", + "memory": "cfa6b8dd8b2f10a25ee36e6ce59ff98885f3c505a0a821f5cef81533f7740681", + "wram": "6aa9c4f2fe72c2addb985c04c63530884b689d5e34865a65e4cfbf905e8010ff", + "audio": { + "firstSample": "183231", + "frames": 803, + "digest": "9041427190941643394de42da12ec97baa5c4a12b567e8810dd447ea41bf86ab", + "discontinuity": false + }, + "state": null + }, + { + "index": 237, + "op": "advance", + "boundary": "230", + "engineFrame": "231", + "worldTime": { + "numerator": "985810546875", + "denominator": "256" + }, + "mask": 1, + "frame": "07cdcf90c8d7df6db86c75969bfc8ac0c4ce677d76d9aad6bf53a601b284dca0", + "memory": "1abfacecc764edfb9b822311f1da469b4c22ab9763f3dd3e7f415082c0c632df", + "wram": "dfbed1886a0382f5b6c7f2ef06662a9666793095bca815c350c7a90213b6f0f9", + "audio": { + "firstSample": "184034", + "frames": 804, + "digest": "ca6ca5ca4dea7c3449a6a327af8fb7ea7991bd549d3b244c1dd023362cc3a56c", + "discontinuity": false + }, + "state": null + }, + { + "index": 238, + "op": "advance", + "boundary": "231", + "engineFrame": "232", + "worldTime": { + "numerator": "1980193359375", + "denominator": "512" + }, + "mask": 1, + "frame": "3b72039392ba6f02876cbf434c22db0dcbb2a858695c0e05540a97302132c739", + "memory": "88bfd0bf79911212fa5503adffb965176abda30d5675afade30d3188d74a85a3", + "wram": "955b0c56c5a562493e37eaf581db116ca4e2b57f88ded65e619b7916a2b7f082", + "audio": { + "firstSample": "184838", + "frames": 804, + "digest": "ede04638634c936d1996249e790249934663f0b3235be679511db30218cb78aa", + "discontinuity": false + }, + "state": null + }, + { + "index": 239, + "op": "advance", + "boundary": "232", + "engineFrame": "233", + "worldTime": { + "numerator": "248595703125", + "denominator": "64" + }, + "mask": 1, + "frame": "ac9d0d530d12fb871d5c5718e035cfc46c528d134a2026235a578bc67b590390", + "memory": "256f5492f278b84d3d698aa797f964f603656111d7866ea40d249658efadba69", + "wram": "0f6cdbdc254134c98da7de674d37f8a7cc361d195a2fc1e661fd6133e41b54bd", + "audio": { + "firstSample": "185642", + "frames": 803, + "digest": "9afd24f3a993fae8e194e89d268010ea821929ff60ac3ca2f1f361d54fe1e2d9", + "discontinuity": false + }, + "state": null + }, + { + "index": 240, + "op": "advance", + "boundary": "233", + "engineFrame": "234", + "worldTime": { + "numerator": "1997337890625", + "denominator": "512" + }, + "mask": 1, + "frame": "2ffff14f93c6629ae9e9319e54b65a08c1a3d8ba04d69f2b5153fc2746e6fcc9", + "memory": "8865f65ccd0cc1a89f28b0d50e9f3f3b88b143efa0aa1b46d5a18a87a718c8cf", + "wram": "91078469ab75ffcbcec9cf8dc3e64776d92680355226b123391a222de8009d2f", + "audio": { + "firstSample": "186445", + "frames": 804, + "digest": "c4a17a49b2953746b49170db533c0cf5f20bb91486716420f9f7abd176b2551c", + "discontinuity": false + }, + "state": null + }, + { + "index": 241, + "op": "advance", + "boundary": "234", + "engineFrame": "235", + "worldTime": { + "numerator": "1002955078125", + "denominator": "256" + }, + "mask": 1, + "frame": "8bc0766900ca93bf0fca0b42ca8b064e1bc4338fdb8bcd869161f75923013452", + "memory": "9a8482272ba07c3b401cb8c00aa967fdae4bdb4dafb1e97b4246e669e209f917", + "wram": "985cef65ab9bdf1d5e1f15212a02e997a19dc1b962f792fd5a345f5948ed6b97", + "audio": { + "firstSample": "187249", + "frames": 804, + "digest": "21b149830c8692d22e6950c95ea415160f79418215697a9471a4cbd30e23321f", + "discontinuity": false + }, + "state": null + }, + { + "index": 242, + "op": "advance", + "boundary": "235", + "engineFrame": "236", + "worldTime": { + "numerator": "2014482421875", + "denominator": "512" + }, + "mask": 1, + "frame": "21a440c21fd380cf0042b654859d49e6d1f5c4a07baad75dce602bde572fb3ec", + "memory": "79bc6fd3c85640255f9554b7a8d69e8495c44e2d9b8aaeaf167ab5afee0c200f", + "wram": "8e6a6ccaf60f5d936365f85c93cddea592498c3a092970594f166e62ebe90b8e", + "audio": { + "firstSample": "188053", + "frames": 803, + "digest": "d3757bc2d306bc0d42ac773d42177a9ab3734dda0c812024121e333d92dc7a1b", + "discontinuity": false + }, + "state": null + }, + { + "index": 243, + "op": "advance", + "boundary": "236", + "engineFrame": "237", + "worldTime": { + "numerator": "505763671875", + "denominator": "128" + }, + "mask": 1, + "frame": "2c2f98b57a3e88cceaac5c4a68fd103edc98b51efcd39403e22b86ac8f2c2edf", + "memory": "98438dc2d47e4a744dcfed3c379ea98c0de162fa868c167109ab68af10b90c71", + "wram": "63e0af376d6a1a777bac6fb85340bf9cec1974e5d0efaa8f1ddc4c8353d01845", + "audio": { + "firstSample": "188856", + "frames": 804, + "digest": "0496951b6a6f152e0294307fb752b981bceb3b8b823d8de2ef1e842b06e997ed", + "discontinuity": false + }, + "state": null + }, + { + "index": 244, + "op": "advance", + "boundary": "237", + "engineFrame": "238", + "worldTime": { + "numerator": "2031626953125", + "denominator": "512" + }, + "mask": 1, + "frame": "5d9b77421e31cca94f089a76a25d1c2c24ec41eb40138b0ef3eb664976fea216", + "memory": "1e7b26e6a7106c859e3930bca3c3d496aec4e53ab44e527bd3933a11d2c597fa", + "wram": "082f6e49f3a33ae0bcd2ca0d957b7c151b5f19833225f02ce7f72334b322636e", + "audio": { + "firstSample": "189660", + "frames": 804, + "digest": "51a70ceadee657639c9d4f89f7c2684ed54ccd6f7c9176ccc6dd2126b1953611", + "discontinuity": false + }, + "state": null + }, + { + "index": 245, + "op": "advance", + "boundary": "238", + "engineFrame": "239", + "worldTime": { + "numerator": "1020099609375", + "denominator": "256" + }, + "mask": 1, + "frame": "3c0ad627bd3b9c21199b03341f4153eaf2309e0a672c703cdfe108afe9415b9e", + "memory": "79d6e06bc9fcd8f9ee2eec1c95de41df329a68c554e02791f13e69f1356589a2", + "wram": "4c504f444d0e4120279d7307f1f1b94235c99f1ba700bd0d67a3d920c64b8cdb", + "audio": { + "firstSample": "190464", + "frames": 803, + "digest": "40ad8f7090f296163ad39a52ecc221868b69c97db369490cf15297d6787aa6c3", + "discontinuity": false + }, + "state": null + }, + { + "index": 246, + "op": "advance", + "boundary": "239", + "engineFrame": "240", + "worldTime": { + "numerator": "2048771484375", + "denominator": "512" + }, + "mask": 1, + "frame": "f4d236c0185298ae2898aeb56b879a4fa452824fc3e9186ed9bfdc7b38f7d2f7", + "memory": "f82a0a3e90ed2326940fb7cec04e3d740e4c7df1d27f5b977f025b3e75fa848a", + "wram": "1f2d58cf5b760af0010d94520650c3319a2cd201fbb09443dc7dab71e50f50c0", + "audio": { + "firstSample": "191267", + "frames": 804, + "digest": "d0fec4462e6dd7e42e371225b7372ddbe55a44d38e78ecf4534c22a0a61c3204", + "discontinuity": false + }, + "state": null + }, + { + "index": 247, + "op": "advance", + "boundary": "240", + "engineFrame": "241", + "worldTime": { + "numerator": "128583984375", + "denominator": "32" + }, + "mask": 1, + "frame": "3c0ad627bd3b9c21199b03341f4153eaf2309e0a672c703cdfe108afe9415b9e", + "memory": "8517f61e302a0fd6d2a51cefde32fa7781eb547927ca1362c839a6394a2730ff", + "wram": "d34426d040a0162851e78b564935a8470b647bc1b270e580d0194bec028e1eb9", + "audio": { + "firstSample": "192071", + "frames": 804, + "digest": "7707656b2b52437a2e2ef4a3ddd8d7d0f66a32282802a57af5ef7fdb6bafb084", + "discontinuity": false + }, + "state": null + } + ] +} diff --git a/services/flysim/crates/fly-session/tests/legacy_env.rs b/services/flysim/crates/fly-session/tests/legacy_env.rs new file mode 100644 index 0000000..938c485 --- /dev/null +++ b/services/flysim/crates/fly-session/tests/legacy_env.rs @@ -0,0 +1,634 @@ +//! ENV-01: the Game Boy compatibility environment worker against the emulator driven directly the +//! way flysim drives it, in every execution mode, plus its refusals. +//! +//! Without a cartridge the toy cartridge runs (our own program, assembled by the harness), and +//! its records are the committed goldens. With `FLY_ROM` (rom-env) the real cartridge runs from a +//! `FLYSIM01` checkpoint; with `FLY_ENV01_TRACE_DIR` the service's own `FLY_TRACE`s are replayed. +//! Each ROM job prints `skipped: ...` and passes when its inputs are not installed. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use fly_session::launcher::ExecutionMode; +use fly_session::legacy_env::{self, BackendConfig, WorldState}; +use fly_session::legacy_env_parity::{ + self as parity, EnvRig, EnvScript, EnvStart, FlyTrace, button_walk, compare, golden_json, + run_direct, run_on_worker, scripted, toy_cart, toy_script, +}; +use fly_session::types::*; +use fly_session_types::extensions::{ + METHOD_RESTORE_SLOT, METHOD_SAVE_SLOT, RestoreSlotParams, SLOTS_CAPABILITY, SaveSlotParams, +}; +use serde_json::{Value, json}; + +macro_rules! all_modes { + ($($name:ident),* $(,)?) => { + mod in_process { + $( + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn $name() { + super::$name(fly_session::launcher::ExecutionMode::InProcess).await + } + )* + } + mod thread { + $( + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn $name() { + super::$name(fly_session::launcher::ExecutionMode::Thread).await + } + )* + } + mod process { + $( + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn $name() { + super::$name(fly_session::launcher::ExecutionMode::Process).await + } + )* + } + }; +} + +struct Toy { + _dir: tempfile::TempDir, + path: PathBuf, + rom: Arc>, + backend: BackendConfig, +} + +/// The toy cartridge in a temporary file (outside the checkout), with its backend configuration. +fn toy(variant: u8) -> Toy { + let dir = tempfile::tempdir().expect("tempdir"); + let rom = toy_cart::rom(variant); + let path = dir.path().join("toy.cart"); + std::fs::write(&path, &rom).expect("write the toy cartridge"); + let backend = BackendConfig::legacy(&digest_of_bytes(&rom)); + Toy { + _dir: dir, + path, + rom: Arc::new(rom), + backend, + } +} + +async fn rig( + mode: ExecutionMode, + path: &Path, + backend: &BackendConfig, +) -> (tempfile::TempDir, EnvRig) { + let dir = tempfile::tempdir().expect("tempdir"); + let rig = EnvRig::start(dir.path(), mode, path, backend.clone()) + .await + .expect("the rig starts"); + (dir, rig) +} + +// ------------------------------------------------------------------------------------------- +// The toy cartridge: the harness's own inputs reach frames, memory and audio + +#[test] +fn the_toy_cartridge_turns_every_input_into_frames_memory_and_audio() { + let toy = toy(0); + let script = |mask: u8| EnvScript { + name: "one".into(), + start: EnvStart::Fresh, + ops: (0..30).map(|_| parity::EnvOp::Advance(mask)).collect(), + }; + let quiet = run_direct(toy.rom.clone(), &toy.backend, &script(0)).unwrap(); + let pressed = run_direct( + toy.rom.clone(), + &toy.backend, + &script(flybrain_gb::emulator::buttons::A), + ) + .unwrap(); + let last = |r: &[parity::EnvRecord]| r.last().unwrap().clone(); + assert_ne!( + last(&quiet).frame, + last(&pressed).frame, + "the pad reaches the screen" + ); + assert_ne!( + last(&quiet).memory, + last(&pressed).memory, + "the pad reaches memory" + ); + assert_ne!( + last(&quiet).audio.unwrap().digest, + last(&pressed).audio.unwrap().digest, + "and the APU" + ); + // Frames move with no input at all (the scroll follows the frame count). + assert_ne!(quiet[5].frame, quiet[6].frame); + // O[0] is after the one-frame scaffold, and carries no audio. + assert_eq!(quiet[0].engine_frame, 1); + assert_eq!(quiet[0].boundary, 0); + assert!(quiet[0].audio.is_none()); + // ~804 stereo frames per Game Boy frame at 48 kHz, contiguous. + let a = quiet[1].audio.clone().unwrap(); + let b = quiet[2].audio.clone().unwrap(); + assert!((790..=820).contains(&a.frames), "{}", a.frames); + assert_eq!(b.first_sample, a.first_sample + a.frames); + // A variant is another cartridge. + assert_ne!(toy_cart::rom(0), toy_cart::rom(1)); +} + +// ------------------------------------------------------------------------------------------- +// Goldens and parity in every mode + +async fn the_toy_golden_holds(mode: ExecutionMode) { + let toy = toy(0); + let script = toy_script(); + let direct = + run_direct(toy.rom.clone(), &toy.backend, &script).expect("the direct reference runs"); + let (_dir, mut rig) = rig(mode, &toy.path, &toy.backend).await; + let worker = run_on_worker(&mut rig, &script) + .await + .expect("the worker runs the script"); + rig.stop().await; + compare(&direct, &worker).expect("the worker is the emulator driven directly"); + + let golden = golden_json(&script, &worker); + let path = parity::toy_golden_path(); + if std::env::var_os("FLY_UPDATE_FIXTURES").is_some() && mode == ExecutionMode::InProcess { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let text = serde_json::to_string_pretty(&golden).unwrap() + "\n"; + std::fs::write(&path, text).unwrap(); + } + let committed: Value = + serde_json::from_str(&std::fs::read_to_string(&path).expect("the golden is committed")) + .unwrap(); + let (want, got) = ( + committed["records"].as_array().unwrap(), + golden["records"].as_array().unwrap(), + ); + for (i, (w, g)) in want.iter().zip(got).enumerate() { + assert_eq!( + w, + g, + "{}: record {i} differs from the golden (FLY_UPDATE_FIXTURES=1 rewrites it)", + mode.label() + ); + } + assert_eq!( + committed, + golden, + "{} differs from the golden", + mode.label() + ); + + // The script exercised every path, and the records show them. + let ops: Vec<&str> = worker.iter().map(|r| r.op).collect(); + for op in [ + "initialize", + "advance", + "save-slot", + "rollback", + "capture", + "restore", + ] { + assert!(ops.contains(&op), "no {op}"); + } + // A rollback lands on the slot's frame and memory, at the same boundary, with the next chunk a + // discontinuity; a restore lands on the captured world. + for (i, r) in worker.iter().enumerate() { + match r.op { + "rollback" => { + assert_eq!(r.boundary, worker[i - 1].boundary); + assert!(r.audio.is_none()); + let next = worker[i + 1..].iter().find(|n| n.op == "advance").unwrap(); + assert!(next.audio.as_ref().unwrap().discontinuity); + } + "restore" => { + let capture = &worker[i - 1]; + assert_eq!(capture.op, "capture"); + assert_eq!( + (r.frame.as_str(), r.memory.as_str()), + (capture.frame.as_str(), capture.memory.as_str()) + ); + } + "advance" => assert_eq!(r.engine_frame, r.boundary + 1), + _ => {} + } + } +} + +// ------------------------------------------------------------------------------------------- +// Refusals + +fn code(result: Result) -> ErrorCode { + match result { + Ok(reply) => reply.result().expect_err("the worker refused").code, + Err(e) => e.code, + } +} + +async fn refusals(mode: ExecutionMode) { + let other = toy(1); + let toy = toy(0); + let (_dir, rig) = rig(mode, &toy.path, &toy.backend).await; + + let mut driver = rig.driver(); + // Another backend configuration -- another scaffold, another slot set -- is another profile. + for tweak in [ + |b: &mut BackendConfig| b.setup_frames = 0, + |b: &mut BackendConfig| b.slots = vec![id("best"), id("spare")], + |b: &mut BackendConfig| b.audio_sample_rate = 44_100, + ] { + let mut params = driver.initialize_params(); + let mut backend = toy.backend.clone(); + tweak(&mut backend); + params.backend_config = backend.asset_ref(); + let refused = driver + .call_raw( + "Environment.Initialize", + Some(driver.scope()), + params.to_json(), + &[], + ) + .await; + assert_eq!(code(refused), ErrorCode::IncompatibleState); + } + // Two ports, or a port the composition does not declare. + let mut params = driver.initialize_params(); + params.port_bindings = vec![(id("p2"), id("fly"))]; + assert_eq!( + code( + driver + .call_raw( + "Environment.Initialize", + Some(driver.scope()), + params.to_json(), + &[] + ) + .await + ), + ErrorCode::IdentityMismatch + ); + // Nothing moved: the right configuration still initializes. + let first = driver + .initialize() + .await + .expect("the declared configuration initializes"); + assert_eq!(first.engine_frame, 1); + + // An incomplete joypad batch, a batch for another port, an axis. + let scope = driver.scope(); + let mut bad = driver.advance_params(0); + bad.controls[0].buttons.pop(); + assert_eq!( + code( + driver + .call_raw( + "Environment.Advance", + Some(scope.clone()), + bad.to_json(), + &[] + ) + .await + ), + ErrorCode::InvalidArgument + ); + let mut bad = driver.advance_params(0); + bad.controls[0].port_id = id("p2"); + assert_eq!( + code( + driver + .call_raw( + "Environment.Advance", + Some(scope.clone()), + bad.to_json(), + &[] + ) + .await + ), + ErrorCode::InvalidArgument + ); + driver.advance(0).await.expect("a complete batch advances"); + + // A slot the composition does not declare; a slot never saved. + let save = SaveSlotParams { + slot_id: id("spare"), + }; + assert_eq!( + code( + driver + .call_raw(METHOD_SAVE_SLOT, Some(driver.scope()), save.to_json(), &[]) + .await + ), + ErrorCode::InvalidArgument + ); + let mut next = driver.scope(); + next.epoch = id("e9"); + let restore = driver.restore_slot_params(&id("best")); + assert_eq!( + code( + driver + .call_raw( + METHOD_RESTORE_SLOT, + Some(next.clone()), + restore.to_json(), + &[] + ) + .await + ), + ErrorCode::InvalidPhase + ); + // A rollback that does not change epoch. + assert_eq!( + code( + driver + .call_raw( + METHOD_RESTORE_SLOT, + Some(driver.scope()), + restore.to_json(), + &[] + ) + .await + ), + ErrorCode::InvalidArgument + ); + + // A duplicate RestoreSlot replays the cached reply; it does not roll back twice. + driver.save_slot(&id("best")).await.unwrap(); + driver + .advance(flybrain_gb::emulator::buttons::A) + .await + .unwrap(); + let request = RestoreSlotParams { + slot_id: id("best"), + prior_epoch: id("e1"), + policy: "legacy-ratchet-rollback-v1".into(), + }; + let scope_e2 = scope_at("legacy", "e2", driver.boundary()); + let once = driver + .call_raw( + METHOD_RESTORE_SLOT, + Some(scope_e2.clone()), + request.to_json(), + &[], + ) + .await + .unwrap(); + let again = driver + .retry_raw( + once.request_id.clone(), + METHOD_RESTORE_SLOT, + Some(scope_e2.clone()), + request.to_json(), + &[], + ) + .await + .unwrap(); + assert_eq!( + once.result().unwrap(), + again.result().unwrap(), + "the duplicate replays" + ); + // The old epoch is gone. + let stale = driver.advance_params(0); + assert_eq!( + code( + driver + .call_raw( + "Environment.Advance", + Some(driver.scope()), + stale.to_json(), + &[] + ) + .await + ), + ErrorCode::StaleEpoch + ); + + // The rolled-back world is the driver's once it moves to the new epoch. + driver.bump_epoch(); + driver + .capture() + .await + .expect("the world captures at (e2, k)"); + rig.stop().await; + + // The cartridge on disk is not the one the configuration names: wrong ROM. + let (_dir2, rig) = rig_with(mode, &other.path, &toy.backend).await; + let mut driver = rig.driver(); + let refused = driver + .call_raw( + "Environment.Initialize", + Some(driver.scope()), + driver.initialize_params().to_json(), + &[], + ) + .await; + assert_eq!(code(refused), ErrorCode::IncompatibleState); + // And a legacy checkpoint of another cartridge does not stage. + let mut state = world_of(&toy).await; + state.rom_digest = other.backend.rom_digest.clone(); + let source = scope_at("legacy", "legacy", state.boundary); + let payload = driver.payload_of(&state, source.clone()).await.unwrap(); + let staged = driver + .call_raw( + "State.StageRestore", + Some(scope_at("legacy", "e2", state.boundary)), + json!({ + "checkpointId": payload.result.checkpoint_id, + "sourceScope": source.to_json(), + "compatibilityDigest": payload.result.compatibility_digest, + "payload": payload.artifact.reference().to_json(), + }), + &[("payload", &payload.artifact)], + ) + .await; + assert_eq!(code(staged), ErrorCode::IncompatibleState); + let _ = rig.stop().await; + + // A launch configuration that is not the legacy scaffold refuses to initialize at all. + let mut two = toy.backend.clone(); + two.setup_frames = 2; + let (_dir3, rig) = rig_with(mode, &toy.path, &two).await; + let mut driver = rig.driver(); + let refused = driver + .call_raw( + "Environment.Initialize", + Some(driver.scope()), + driver.initialize_params().to_json(), + &[], + ) + .await; + assert_eq!(code(refused), ErrorCode::IncompatibleState); + rig.stop().await; +} + +async fn rig_with( + mode: ExecutionMode, + path: &Path, + backend: &BackendConfig, +) -> (tempfile::TempDir, EnvRig) { + rig(mode, path, backend).await +} + +/// A world of the toy cartridge at a few frames in, as data. +async fn world_of(toy: &Toy) -> WorldState { + let script = EnvScript { + name: "w".into(), + start: EnvStart::Fresh, + ops: vec![parity::EnvOp::Advance(0); 3], + }; + let (mut direct, _) = + parity::DirectEmulator::fresh(toy.rom.clone(), toy.backend.clone()).unwrap(); + for op in &script.ops { + if let parity::EnvOp::Advance(m) = op { + direct.advance(*m).unwrap(); + } + } + direct.state().unwrap() +} + +/// The image read leaves the emulator exactly as the frame left it: the exported state after the +/// read is byte for byte the state before it, and the next frame is the frame an unread emulator +/// draws. An unguarded 64K read changes the export (binjgb syncs OAM/VRAM/timer/STAT/LY on read), +/// which this also shows, so the guard is not vacuous. +#[test] +fn the_memory_image_leaves_the_emulator_as_it_found_it() { + use flybrain_gb::emulator::Emulator; + let rom = toy_cart::rom(0); + let boot = || { + let mut e = Emulator::new(&rom, 48_000, 4_096).unwrap(); + for m in [0u8, 1, 1, 16, 0] { + e.set_buttons(m); + e.run_frame().unwrap(); + let _ = e.take_audio_u8(); + } + e + }; + let mut read = boot(); + let unread = boot(); + let before = read.export_state().unwrap(); + let image = legacy_env::memory_image(&mut read).unwrap(); + assert_eq!(image.len(), 65_536); + assert_eq!( + read.export_state().unwrap(), + before, + "the guarded read is neutral" + ); + for (address, byte) in image.iter().enumerate() { + assert_eq!( + *byte, + unread.read_uncached(address as u16), + "byte {address:04x} is fly_gb_read_mem's" + ); + } + let mut fresh = boot(); + let _: Vec = (0..=u16::MAX).map(|a| fresh.read_uncached(a)).collect(); + assert_ne!( + fresh.export_state().unwrap(), + before, + "an unguarded read is not neutral" + ); + let mut unread = boot(); + for e in [&mut read, &mut unread] { + e.set_buttons(32); + e.run_frame().unwrap(); + } + assert_eq!(read.framebuffer(), unread.framebuffer()); + assert_eq!(read.export_state().unwrap(), unread.export_state().unwrap()); +} + +#[test] +fn the_worker_advertises_the_slots_extension() { + assert!(legacy_env::capabilities().contains(&id(SLOTS_CAPABILITY))); + assert!(legacy_env::capabilities().contains(&id("checkpoint-v1"))); +} + +// ------------------------------------------------------------------------------------------- +// The real cartridge (rom-env) + +fn rom_inputs() -> Option<(PathBuf, Arc>, BackendConfig)> { + let path = PathBuf::from(std::env::var_os("FLY_ROM")?); + let rom = std::fs::read(&path).ok()?; + let backend = BackendConfig::legacy(&digest_of_bytes(&rom)); + Some((path, Arc::new(rom), backend)) +} + +/// The real cartridge from the row-58 checkpoint (`FLY_DOOR_CHECKPOINT`): a 480-frame button walk +/// with slot saves, rollbacks (the first onto the checkpoint's own ratchet slot's successor) and +/// a restart, direct against the worker, frame by frame. +async fn rom_checkpoint_parity(mode: ExecutionMode) { + let (Some((path, rom, backend)), Some(checkpoint)) = + (rom_inputs(), std::env::var_os("FLY_DOOR_CHECKPOINT")) + else { + eprintln!("skipped: FLY_ROM or FLY_DOOR_CHECKPOINT is not set"); + return; + }; + let bytes = Arc::new(std::fs::read(checkpoint).expect("the checkpoint reads")); + let mut script = scripted( + "rom-row58-480", + EnvStart::Flysim01(bytes), + &button_walk(480, 58), + ); + // The checkpoint's ratchet slot is restored with the world: roll back onto it first. + script + .ops + .insert(3, parity::EnvOp::Rollback(id(legacy_env::DEFAULT_SLOT))); + let direct = run_direct(rom.clone(), &backend, &script).expect("direct"); + let (_dir, mut rig) = rig(mode, &path, &backend).await; + let worker = run_on_worker(&mut rig, &script).await.expect("worker"); + rig.stop().await; + compare(&direct, &worker).expect("the worker is the emulator driven directly"); + eprintln!( + "{}: {} records identical, last {}", + mode.label(), + worker.len(), + worker.last().unwrap().row() + ); +} + +/// FND-01's traces of the running service (`FLY_ENV01_TRACE_DIR`: `.trace.jsonl` with its +/// start `.checkpoint`, or the row-58 checkpoint for `r58`): every transition's frame and +/// WRAM digest, and every slot save's state digest, reproduced by the worker. +async fn service_trace_replay(mode: ExecutionMode) { + let (Some((path, rom, backend)), Some(dir)) = + (rom_inputs(), std::env::var_os("FLY_ENV01_TRACE_DIR")) + else { + eprintln!("skipped: FLY_ROM or FLY_ENV01_TRACE_DIR is not set"); + return; + }; + let dir = PathBuf::from(dir); + let limit = std::env::var("FLY_ENV01_TRACE_LIMIT") + .ok() + .and_then(|n| n.parse().ok()); + for name in ["rollback", "climb", "r58"] { + let trace_path = dir.join(format!("{name}.trace.jsonl")); + let checkpoint = if name == "r58" { + std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from) + } else { + Some(dir.join(format!("{name}.checkpoint"))) + }; + let Some(checkpoint) = checkpoint.filter(|c| c.is_file() && trace_path.is_file()) else { + eprintln!("skipped: {name} trace or checkpoint missing"); + continue; + }; + let trace = FlyTrace::read(&trace_path, limit).expect("the trace reads"); + let script = trace.script(name, Arc::new(std::fs::read(&checkpoint).unwrap())); + let (_dir, mut rig) = rig(mode, &path, &backend).await; + let worker = run_on_worker(&mut rig, &script).await.expect("worker"); + rig.stop().await; + let compared = trace + .check(&worker) + .unwrap_or_else(|e| panic!("{name}: {e}")); + let actions: usize = trace.frames.iter().map(|f| f.actions.len()).sum(); + eprintln!( + "{}: {name}: {} transitions, {actions} boundary actions, {compared} values equal the service's", + mode.label(), + trace.frames.len() + ); + let _ = &rom; + } +} + +all_modes!( + the_toy_golden_holds, + refusals, + rom_checkpoint_parity, + service_trace_replay +); From 931fa01a8c8d659734e86a409b0ea2a2cf914e5e Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:16:22 +0000 Subject: [PATCH 13/26] docs: ENV-01 status and the 2026-09-29 amendments (guarded image read, FLYSIM01 boundary, names) --- .../session-framework/implementation.md | 54 +++++++++++++++++++ .../session-framework/legacy-gameboy-v1.md | 9 ++++ 2 files changed, 63 insertions(+) diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index a11fa4c..93800da 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -213,6 +213,60 @@ the frame order maps one to one (section 4), the legacy clock equals the rationa (section 3), and the fingerprint and compatibility string are embedded unchanged (sections 2 and 12). The acceptance criteria below stand. +**2026-09-29: built on `port/env-01` (off main `9f2345d`).** `fly-session::legacy_env` is the +environment worker (`LegacyGameboyEnvironment`), launched by `Launcher::launch_legacy_environment` +and the `legacy-environment` subcommand in all three execution modes. It makes exactly the emulator +calls flysim's `LegacyFrame` makes, in the same order: `Environment.Initialize` runs the one-frame +setup scaffold with no button down (O[0] has `engineFrame` "1", no audio chunk); +`Environment.Advance` takes one complete `gameboy-joypad-v1` batch for the one port, runs one frame +and returns the `lcd` view, the `apu` chunk as `f32le` (`sample / 255`, unfiltered) and the +`gameboy-memory-inspection-v1` image; `Environment.SaveSlot` / `RestoreSlot` are +`gameboy-slots-v1` (a restore imports, releases the pad, shows the slot's frame, runs no frame and +moves to the new epoch at the same boundary); `State.Capture` / `StageRestore` / `ActivateRestore` +carry every slot and stage on a stopped replacement emulator. The joypad is the only write into a +running game. The coordinator now refuses `episodeRequest.kind = "rollback"` (task failure, epoch +fenced) unless the composition declares `legacy-ratchet-rollback-v1` +(`Coordinator::declare_rollback_policy`); with the policy declared it still pauses at the boundary, +because the rollback sequence is TASK-01's. Parity (`tests/legacy_env.rs`, harness +`legacy_env_parity`): records equal to the emulator driven directly, frame by frame (view, 64 KiB +image, WRAM, audio chunk, slot and capture state digests), in-process, thread and process, on a +toy cartridge the harness assembles (committed golden `fixtures/legacy-env/toy-cart.golden.json`) +and, with rom-env, on the real cartridge from the row-58 checkpoint; and the service's own +`FLY_TRACE`s (FND-01's harness; `FLY_ENV01_TRACE_DIR`) replayed through the worker reproduce every +recorded frame, WRAM and slot-state digest, including a ratchet slot save and a rollback. Not in +this slice: the shim's bulk read (MEM-01, behind the one seam `legacy_env::memory_image`), the +coordinator's save/rollback/`Agent.Rollback` sequence and the executor (TASK-01), and assembling +the FLYSIM01 export from the three halves (STATE-02; the world's half is +`Flysim01World::{manifest_entries, chunks}`). + +**Amendment, 2026-09-29 (ENV-01).** Four readings the contract left open, fixed by this slice: + +- *The image read is not state-neutral, so it is guarded.* `emulator_read_mem` of OAM, VRAM, + `FF01`/`FF02`, `FF04`-`FF06`, `IF`, `STAT` or `LY` runs binjgb's lazy synchronisation, and + `export_state` afterwards differs (never, over 17,398 replayed frames, a frame or WRAM). The + legacy loop reads none of these between a frame and the ratchet's capture, so an unguarded image + would make every slot and capture differ from the service's bytes. The worker reads the image + between `export_state` and `import_state` of the same bytes, which leaves the emulator exactly as + the frame left it; `legacy-gameboy-v1` section 8's proof ("export before and after, compare") + therefore fails for a plain 65,536-read loop and holds for the guarded one. MEM-01's bulk read + must keep that guard (or equivalent). +- *A `FLYSIM01` world starts at `k = emulatorFrame - setupFrames`.* The legacy file has no + boundary, world clock or audio position. The frame counter advances once per transition and + never across a rollback, so `engineFrame = k + 1` from a fresh start on; `worldTime` is + `k x stepDuration` and the audio position is that time's sample at the configured rate, rounded + down. The first chunk after the restore marks the discontinuity. The ratchet's one slot is the + composition's first declared slot (`best`). +- *Names.* The image travels as the attachment `inspection.memory`; the audio stream is `apu`; + the port is `p1`. `backendConfig` is the canonical JSON of `gameboy-backend-config-v1` + `{form, romDigest, portId, slots, audio {sampleRate, channels, bufferFrames}, setupFrames, view, + controllerSchema, inspectionSchema}`; `Environment.Initialize` naming any other document, and a + cartridge on disk that is not `romDigest`, are refused `INCOMPATIBLE_STATE` with nothing mutated. + The capture payload is flybrain-core's envelope with magic `FLYENV01`, and its participant + compatibility uses the state format `fly-gb-env-v1`. +- *`legacy-transient-reset` for the world is empty.* Everything the environment holds is restored: + emulator, frame on screen, joypad, frame counter, slots, clock and audio position. The reset + applies to the executor, the agent's readout transient and the task's transient observations. + **Implement:** binjgb environment, task-local memory inspector and identity/existing action adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash semantics. diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 163934e..197e74d 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -214,6 +214,15 @@ interface GameboyMemoryInspection { FLYSIM01's `ratchet_game` and `ratchet_frame` are today. A slot save due at a boundary completes before any `State.Capture` or FLYSIM01 export at that boundary (section 16). +**Amendment, 2026-09-29 (ENV-01).** Two consequences of building this section, recorded in the +[implementation guide](implementation.md) ENV-01 entry: the memory image cannot be taken with a +plain loop of `emulator_read_mem`, because reading OAM, VRAM, the serial and timer registers, +`IF`, `STAT` or `LY` advances binjgb's lazy synchronisation and changes what `export_state` writes +-- the environment reads it between an export and an import of the same bytes, so slots and +captures stay byte for byte the legacy loop's; and a `FLYSIM01` world is restored at boundary +`emulatorFrame - 1`, its world time and audio position derived from that boundary, with the +ratchet's snapshot as the slot `best`. + ## 10. Executor `pokered-macros-v1` The Pokémon Red task (reward adapter, ladder, ratchet ledger) and its action executor (the From 563afb18f0ab94f1020959463d168f4b9978f170 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 14:26:07 +0000 Subject: [PATCH 14/26] tests: the legacy agent worker checked against FND-01's FLY_TRACE of the running legacy frame FLY_TRACE carries digests, not the frames or the {boot, bound, location} context, so it checks a worker rather than drives one. legacy_parity gains read_frame_trace and check_against_trace (ticks, clock, exact remainder, rates digest, spike-set digest, decision; the script held to the trace's sugar, frames, rewards and rollback), RestoredSource, and AgentDriver::seed_from_legacy_state for a worker started from a FLYSIM01 agent state. flysim/tests/agent_trace_parity.rs runs LegacyFrame on the ROM with the trace on, records the missing inputs, and checks the direct reference and the worker in-process, on a thread and as a process: toy raw from power-on (FLY_ROM), and gameboy-legacy-fafb-v783-v1 macros mode from a stream checkpoint with sugar and a ratchet rollback (FLY_AGENT01_FAFB=1). fly-session is a flysim dev-dependency only. A FLYSIM01 import starts learning.updates at the legacy plasticity.updates (legacy_reinforcements): starting at zero broke changed <= updates on the live checkpoint. --- services/flysim/Cargo.lock | 1 + .../crates/fly-session/src/legacy_parity.rs | 497 +++++++++++++++++- .../crates/fly-session/tests/legacy_agent.rs | 180 ++++++- services/flysim/crates/flysim/Cargo.toml | 3 + .../crates/flysim/tests/agent_trace_parity.rs | 422 +++++++++++++++ 5 files changed, 1084 insertions(+), 19 deletions(-) create mode 100644 services/flysim/crates/flysim/tests/agent_trace_parity.rs diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index f0f4a3f..90899cb 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -502,6 +502,7 @@ dependencies = [ "anyhow", "axum", "clap", + "fly-session", "fly-session-types", "flybrain-core", "flybrain-gb", diff --git a/services/flysim/crates/fly-session/src/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs index 14953d4..785b7b7 100644 --- a/services/flysim/crates/fly-session/src/legacy_parity.rs +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -14,9 +14,14 @@ //! (`agent_to_chunks`). A state digest is exact equality of every membrane, trace, gain, rate, //! RNG and decoder field. //! -//! [`ReferenceSource`] is the seam for FND-01: a reader of `LegacyFrame`'s `FLY_TRACE` is a -//! second reference beside [`DirectReference`], producing the same records from the running -//! loop instead of from a transcription of it. Nothing here depends on it. +//! FND-01's `FLY_TRACE` (`flysim::trace`, `flysim-legacy-frame-trace-v1`) is the running loop's +//! own record. It carries digests and behaviour fields rather than full telemetry, and neither the +//! frames nor the `{boot, bound, location}` context, so it cannot drive a worker by itself: it +//! checks one. [`read_frame_trace`] reads it and [`check_against_trace`] holds a run's records to +//! it. `flysim/tests/agent_trace_parity.rs` is the host that runs `LegacyFrame` with the trace on, +//! records the missing inputs as a [`LegacyScript`], and checks both the worker and +//! [`DirectReference`] against the trace -- so the transcription is itself checked against the +//! service. [`ReferenceSource`] stays the seam for sources of full records. //! //! [`toy`] is the committed toy connectome the goldens run on; the real dataset is optional. @@ -546,9 +551,8 @@ pub fn compare(left: &[ParityRecord], right: &[ParityRecord]) -> Result<(), Stri /// A source of reference records for a script. /// -/// [`DirectReference`] is one. FND-01's `LegacyFrame` trace (`FLY_TRACE`) is meant to be the -/// other: it would produce the same records from the running legacy loop, and at that point the -/// transcription in [`DirectReference`] is itself checked against the service. +/// [`DirectSource`] and [`RestoredSource`] are the two. FND-01's `FLY_TRACE` records digests +/// rather than full records, so it is a check ([`check_against_trace`]) rather than a source. pub trait ReferenceSource { fn records(&mut self, script: &LegacyScript) -> Result, String>; } @@ -557,8 +561,10 @@ pub trait ReferenceSource { // The direct reference: NeuralAgent in `Sim::step_frame` order /// `NeuralAgent` driven the way `flysim::simloop::Sim` drives it, transcribed line by line from -/// `fresh_start`, `step_frame`, `recover` and `try_restore`, with the emulator, adapter and -/// macro layer replaced by the script's recorded outputs. +/// `fresh_start`, `step_frame`, `recover` and `try_restore` (since FND-01, one type: +/// `flysim::frame::LegacyFrame`'s `initialize`, `transition`, `rollback` and `restore`, whose two +/// reorderings touch disjoint state), with the emulator, adapter and macro layer replaced by the +/// script's recorded outputs. pub struct DirectReference { dataset: Arc, agent: NeuralAgent, @@ -757,7 +763,52 @@ pub struct DirectSource { impl ReferenceSource for DirectSource { fn records(&mut self, script: &LegacyScript) -> Result, String> { - let (mut reference, first) = DirectReference::fresh(self.dataset.clone(), script)?; + let (reference, first) = DirectReference::fresh(self.dataset.clone(), script)?; + reference.run(first, script) + } +} + +/// [`ReferenceSource`] from a legacy agent state (a `FLYSIM01` checkpoint's), the way the +/// stream restores after a restart: `LegacyFrame::restore` into a fresh process's transient. +pub struct RestoredSource { + pub dataset: Arc, + pub state: flybrain_core::agent::AgentState, +} + +impl ReferenceSource for RestoredSource { + fn records(&mut self, script: &LegacyScript) -> Result, String> { + let mut agent = DirectReference::build(self.dataset.clone(), &script.macro_channels)?; + agent.import_state(&self.state).map_err(|e| e.to_string())?; + let frame = script.frames[script.initial_frame].clone(); + let (width, height) = (agent.frame.width, agent.frame.height); + agent.network.set_visual_frame(&frame, width, height); + let reference = DirectReference { + dataset: self.dataset.clone(), + agent, + macro_channels: script.macro_channels.clone(), + remainder: self.state.remainder, + location: None, + held_channel: None, + blocked_since_ms: 0.0, + frame_buffer: frame, + boot: script.initial_context.boot, + bound: script.initial_context.bound.clone(), + reinforcements: legacy_reinforcements(&self.state), + }; + let mut first = reference.record(0, "restore", 0, 0, None, None); + first.telemetry = None; + first.state = Some(reference.state_digest()); + reference.run(first, script) + } +} + +impl DirectReference { + fn run( + mut self, + first: ParityRecord, + script: &LegacyScript, + ) -> Result, String> { + let reference = &mut self; let mut records = vec![first]; let mut boundary = 0u64; for (index, step) in script.steps.iter().enumerate() { @@ -1394,6 +1445,95 @@ impl AgentDriver { } self.acknowledge(reply.request_id).await } + + /// Starts the agent from a legacy agent state -- a `FLYSIM01` checkpoint's `agent`, with + /// the loop's frame remainder in it -- instead of from a warm-up, the way the stream restores + /// after a restart (`legacy-transient-reset`). + /// + /// This is the test side of an import nothing ships yet: the worker is initialized, its own + /// capture is taken as the template for the session member, the agent chunks and the clock + /// are replaced with `state`'s, and the result is restored into a replacement worker through + /// the ordinary `State.StageRestore` / `ActivateRestore`, which validates it like any other + /// payload. `learning.updates` starts at [`legacy_reinforcements`], because `FLYSIM01` does + /// not record every reinforcement call. + pub async fn seed_from_legacy_state( + &mut self, + rig: &mut LegacyRig, + agent_id: &Id, + initial_frame: usize, + state: &flybrain_core::agent::AgentState, + ) -> Result { + self.initialize(initial_frame).await?; + let template = self.capture().await?; + let bytes = legacy_state_payload(&template.bytes, state, &self.context)?; + let digest = digest_of_bytes(&bytes); + let artifact = crate::state::seal_payload(&self.client, &bytes, &digest) + .await + .map_err(domain)?; + let seeded = Captured { + result: CaptureResult { + payload: artifact.reference().clone(), + ..template.result + }, + artifact, + bytes, + scope: template.scope, + }; + let target = rig.replace(agent_id).await?; + self.restore_into(target, &seeded).await?; + let after = self.capture().await?; + let restored = payload_state_digest(&after.bytes)?; + if restored != state_digest(state) { + return Err("the seeded worker's state is not the legacy state".to_owned()); + } + self.remainder = legacy_remainder_to_rational(state.remainder)?; + Ok(ParityRecord { + index: 0, + kind: "restore", + boundary: self.boundary, + ticks: 0, + brain_ticks: state.network.ms as u64, + remainder: self.remainder, + decision: None, + telemetry: None, + spikes: None, + state: Some(restored), + }) + } +} + +/// The reinforcement calls to start a legacy agent state's `learning.updates` at. +/// +/// `FLYSIM01` records `plasticity.updates`, the reinforcements that moved a gain, but not every +/// call, and the contract requires `learning.changed <= learning.updates`. An import that starts +/// the call count at zero makes the first telemetry unreadable (found on the row-58 stream +/// checkpoint: `changed` is in the thousands), so it starts at the recorded count, a lower bound +/// on the calls actually made. +pub fn legacy_reinforcements(state: &flybrain_core::agent::AgentState) -> u64 { + state.network.plasticity.updates as u64 +} + +/// A worker capture with its agent chunks and clock replaced by a legacy agent state, and its +/// context by `context`: see [`AgentDriver::seed_from_legacy_state`]. +pub fn legacy_state_payload( + template: &[u8], + state: &flybrain_core::agent::AgentState, + context: &TypedValue, +) -> Result, String> { + let mut session = captured_session(template)?; + let remainder = legacy_remainder_to_rational(state.remainder)?; + session["accumulator"]["remainder"] = remainder.to_json(); + session["accumulator"]["executedTicks"] = json!((state.network.ms as u64).to_string()); + session["reinforcements"] = json!(legacy_reinforcements(state).to_string()); + session["context"] = context.to_json(); + let chunks = agent_to_chunks(state); + let mut manifest = chunks.manifest; + manifest.set( + "session", + flybrain_core::json::JsonValue::parse(&session.to_string()).map_err(|e| e.to_string())?, + ); + flybrain_core::envelope::encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks) + .map_err(|e| e.to_string()) } /// Runs a script against the rig's agent, recording what the coordinator observes. @@ -1401,9 +1541,28 @@ pub async fn run_on_worker( rig: &mut LegacyRig, agent_id: &Id, script: &LegacyScript, +) -> Result, String> { + run_on_worker_from(rig, agent_id, script, None).await +} + +/// [`run_on_worker`], from a warm-up or, with `start`, from a legacy agent state +/// ([`AgentDriver::seed_from_legacy_state`]). +pub async fn run_on_worker_from( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, + start: Option<&flybrain_core::agent::AgentState>, ) -> Result, String> { let mut driver = rig.driver(agent_id, script); - let mut records = vec![driver.initialize(script.initial_frame).await?]; + let first = match start { + None => driver.initialize(script.initial_frame).await?, + Some(state) => { + driver + .seed_from_legacy_state(rig, agent_id, script.initial_frame, state) + .await? + } + }; + let mut records = vec![first]; for (index, step) in script.steps.iter().enumerate() { let mut record = match step { ScriptStep::Frame { @@ -1477,6 +1636,324 @@ pub fn golden_json(script: &LegacyScript, records: &[ParityRecord]) -> Value { }) } +// ------------------------------------------------------------------------------------------- +// FND-01's FLY_TRACE: the running legacy loop as a reference + +/// The format name on the first line of a `FLY_TRACE` file (`flysim::trace::FORMAT`). +pub const FRAME_TRACE_FORMAT: &str = "flysim-legacy-frame-trace-v1"; + +/// One sugar or operator pulse admitted at the top of a legacy frame, before its ticks. +#[derive(Clone, Debug, PartialEq)] +pub enum TraceAdmission { + Sugar { + duration_ms: f64, + }, + /// `POST /reward`: `plasticity.reinforce(value)` at admission. It has no session-framework + /// counterpart, so a script cannot carry it and [`check_against_trace`] refuses a trace + /// that has one. + RewardPulse { + value: f64, + }, +} + +/// The agent-observable half of one `FLY_TRACE` transition line, `behaviour` only. +#[derive(Clone, Debug, PartialEq)] +pub struct TraceTransition { + pub step: u64, + pub admissions: Vec, + pub ticks: u64, + pub brain_ticks: u64, + pub remainder: RationalNs, + pub rates_digest: String, + pub spikes_digest: String, + pub spike_count: u64, + /// The decode's active set, as the executor was given it. + pub decision: Vec, + /// The mask the emulator was given: the executor's, not the decision's. + pub mask: u32, + pub framebuffer_digest: String, + /// `(value, stimulationMs)` in adapter order. + pub rewards: Vec, + /// The boundary actions, `save-slot` and `rollback`, in order. + pub boundary_actions: Vec, +} + +/// Reads a `FLY_TRACE` file: the header, an optional start-boundary line, then one line per +/// transition. +pub fn read_frame_trace(text: &str) -> Result, String> { + let mut lines = text.lines().filter(|l| !l.trim().is_empty()); + let header: Value = serde_json::from_str(lines.next().ok_or("an empty trace")?) + .map_err(|e| format!("the trace header: {e}"))?; + if header["format"] != FRAME_TRACE_FORMAT { + return Err(format!( + "the trace is {}, not {FRAME_TRACE_FORMAT}", + header["format"] + )); + } + let text_u64 = |v: &Value, key: &str| -> Result { + v[key] + .as_str() + .and_then(|s| s.parse().ok()) + .ok_or_else(|| format!("{key} is not a U64 string")) + }; + let string = |v: &Value, key: &str| -> Result { + v[key] + .as_str() + .map(str::to_owned) + .ok_or_else(|| format!("{key} is not a string")) + }; + let mut out = Vec::new(); + for (n, line) in lines.enumerate() { + let value: Value = + serde_json::from_str(line).map_err(|e| format!("trace line {}: {e}", n + 2))?; + let Some(b) = value.get("behaviour") else { + // The start boundary's captures: operational only. + continue; + }; + let admissions = b["admissions"] + .as_array() + .ok_or("admissions is not a list")? + .iter() + .map(|a| match a["kind"].as_str() { + Some("sugar") => a["durationMs"] + .as_f64() + .map(|duration_ms| TraceAdmission::Sugar { duration_ms }) + .ok_or_else(|| "a sugar admission without durationMs".to_owned()), + Some("reward") => a["value"] + .as_f64() + .map(|value| TraceAdmission::RewardPulse { value }) + .ok_or_else(|| "a reward admission without value".to_owned()), + other => Err(format!("an admission of kind {other:?}")), + }) + .collect::, _>>()?; + let rewards = b["rewards"] + .as_array() + .ok_or("rewards is not a list")? + .iter() + .map(|r| { + Ok(RewardEvent { + value: r["value"].as_f64().ok_or("a reward without value")?, + stimulation_ms: r["stimulationMs"] + .as_f64() + .ok_or("a reward without stimulationMs")?, + }) + }) + .collect::, String>>()?; + let decision = b["decision"] + .as_array() + .ok_or("decision is not a list")? + .iter() + .map(|c| c.as_str().map(str::to_owned).ok_or("a decision channel")) + .collect::, _>>()?; + let boundary_actions = b["boundaryActions"] + .as_array() + .ok_or("boundaryActions is not a list")? + .iter() + .map(|a| { + a["kind"] + .as_str() + .map(str::to_owned) + .ok_or("an action kind") + }) + .collect::, _>>()?; + out.push(TraceTransition { + step: text_u64(b, "step")?, + admissions, + ticks: text_u64(b, "ticksAdvanced")?, + brain_ticks: text_u64(b, "brainTicks")?, + remainder: RationalNs::from_json(&b["remainder"]) + .map_err(|e| format!("remainder: {}", e.0))?, + rates_digest: string(b, "ratesDigest")?, + spikes_digest: string(b, "spikesDigest")?, + spike_count: b["spikeCount"].as_u64().ok_or("spikeCount")?, + decision, + mask: b["mask"] + .as_u64() + .and_then(|m| u32::try_from(m).ok()) + .ok_or("mask")?, + framebuffer_digest: string(b, "framebufferDigest")?, + rewards, + boundary_actions, + }); + } + Ok(out) +} + +/// `FLY_TRACE`'s `ratesDigest` of a telemetry's rates: per tracked role in the network's +/// order, the name's length (u32 LE), the name, and the rate's f64 bits (LE). The role id is +/// the role name (`legacy-rate-role-id-v1`). +pub fn trace_rates_digest(telemetry: &AgentTelemetry) -> Result { + let mut bytes = Vec::new(); + for sample in &telemetry.rates { + let name = gameboy::rate_role_name(&sample.role_id).map_err(|e| e.0)?; + bytes.extend_from_slice(&(name.len() as u32).to_le_bytes()); + bytes.extend_from_slice(name.as_bytes()); + bytes.extend_from_slice(&sample.hz.to_bits().to_le_bytes()); + } + Ok(digest_of_bytes(&bytes)) +} + +/// What a trace check covered. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TraceCheck { + pub transitions: usize, + pub sugar: usize, + pub rewards: usize, + pub rollbacks: usize, + pub macro_decisions: usize, + pub pressed: usize, + pub spikes: u64, +} + +/// Checks the records of a run of `script` -- the worker's, or [`DirectReference`]'s -- +/// against the `FLY_TRACE` of the legacy loop that produced the script. +/// +/// The trace carries digests and the behaviour fields, not the full telemetry, so this is a +/// check rather than a [`ReferenceSource`]. It holds the script to the trace first (the same +/// sugar, frames and reward events, a rollback exactly where the loop rolled back), then each +/// frame record to its transition: ticks, brain clock, exact remainder, the rates digest, the +/// spike-set digest, and the decision as `gameboy-channels-v1` of the decode's active set under +/// the context the step was decided in. +pub fn check_against_trace( + script: &LegacyScript, + records: &[ParityRecord], + trace: &[TraceTransition], +) -> Result { + if records.len() != script.steps.len() + 1 { + return Err(format!( + "{} records for {} steps", + records.len(), + script.steps.len() + )); + } + let mut check = TraceCheck::default(); + let mut transitions = trace.iter(); + let mut last: Option<&TraceTransition> = None; + let mut bound = script.initial_context.bound.clone(); + let mut previous_ticks = records[0].brain_ticks; + for (index, step) in script.steps.iter().enumerate() { + let record = &records[index + 1]; + let at = |what: String| format!("step {index} (record {}): {what}", index + 1); + match step { + ScriptStep::Frame { + sugar, + frame, + rewards, + next_context, + } => { + let t = transitions + .next() + .ok_or_else(|| at("the trace ended".to_owned()))?; + let admitted: Vec = sugar + .iter() + .map(|d| TraceAdmission::Sugar { duration_ms: *d }) + .collect(); + if t.admissions != admitted { + return Err(at(format!( + "the trace admitted {:?}, the script {admitted:?}", + t.admissions + ))); + } + if digest_of_bytes(&script.frames[*frame]) != t.framebuffer_digest { + return Err(at("the script's frame is not the loop's".to_owned())); + } + if &t.rewards != rewards { + return Err(at(format!( + "the trace rewarded {:?}, the script {rewards:?}", + t.rewards + ))); + } + if t.boundary_actions.iter().any(|a| a == "rollback") + != matches!( + script.steps.get(index + 1), + Some(ScriptStep::Rollback { .. }) + ) + { + return Err(at("the script's rollback is not where the loop's is".into())); + } + if record.kind != "frame" { + return Err(at(format!("a {} record for a frame", record.kind))); + } + let mut differ = Vec::new(); + if record.ticks != t.ticks { + differ.push(format!("ticks {} != {}", record.ticks, t.ticks)); + } + if record.brain_ticks != t.brain_ticks { + differ.push(format!( + "brainTicks {} != {}", + record.brain_ticks, t.brain_ticks + )); + } + if record.remainder != t.remainder { + differ.push(format!( + "remainder {:?} != {:?}", + record.remainder, t.remainder + )); + } + let telemetry = record + .telemetry + .as_ref() + .ok_or_else(|| at("a frame record without telemetry".to_owned()))?; + if trace_rates_digest(telemetry)? != t.rates_digest { + differ.push("ratesDigest".to_owned()); + } + if record.spikes.as_deref() != Some(t.spikes_digest.as_str()) { + differ.push("spikesDigest".to_owned()); + } + let want = channels_decision(&t.decision, &bound); + if record.decision.as_ref() != Some(&want) { + differ.push(format!( + "decision {:?} != {:?} (active {:?})", + record.decision, want, t.decision + )); + } + if !differ.is_empty() { + return Err(at(format!( + "differs from trace step {}: {}", + t.step, + differ.join("; ") + ))); + } + check.transitions += 1; + check.sugar += sugar.len(); + check.rewards += rewards.len(); + check.spikes += t.spike_count; + check.macro_decisions += usize::from(want.macro_channel.is_some()); + check.pressed += usize::from(want.mask() != 0); + bound = next_context.bound.clone(); + previous_ticks = record.brain_ticks; + last = Some(t); + } + ScriptStep::Rollback { frame, context } => { + let t = last.ok_or_else(|| at("a rollback before any frame".to_owned()))?; + if !t.boundary_actions.iter().any(|a| a == "rollback") { + return Err(at("the loop did not roll back here".to_owned())); + } + if record.kind != "rollback" || record.ticks != 0 { + return Err(at(format!("a {} record with ticks", record.kind))); + } + if record.brain_ticks != previous_ticks { + return Err(at("a rollback moved the brain clock".to_owned())); + } + // The slot's frame is the rolled-back world's, which the trace does not digest; + // the next transition's ticks and spikes are what it drives. + let _ = frame; + check.rollbacks += 1; + bound = context.bound.clone(); + } + ScriptStep::Restore => { + return Err(at( + "a restore splits a trace in two; check each process's trace".to_owned(), + )); + } + } + } + if let Some(t) = transitions.next() { + return Err(format!("the trace goes on at step {}", t.step)); + } + Ok(check) +} + #[cfg(test)] mod tests { use super::*; diff --git a/services/flysim/crates/fly-session/tests/legacy_agent.rs b/services/flysim/crates/fly-session/tests/legacy_agent.rs index 285c1c6..36c91a0 100644 --- a/services/flysim/crates/fly-session/tests/legacy_agent.rs +++ b/services/flysim/crates/fly-session/tests/legacy_agent.rs @@ -606,7 +606,8 @@ mod fafb { } fn pokered_channels() -> Vec { - let file = fly_session_types::fixtures::load("gameboy-decoder-config.json").expect("vectors"); + let file = + fly_session_types::fixtures::load("gameboy-decoder-config.json").expect("vectors"); file["cases"][1]["macroChannels"] .as_array() .expect("the Pokemon Red macro group") @@ -632,20 +633,31 @@ mod fafb { sugar: if k == 12 { vec![400.0] } else { vec![] }, frame: k % 6, rewards: if k % 11 == 0 { - vec![RewardEvent { value: 0.5, stimulation_ms: 120.0 }] + vec![RewardEvent { + value: 0.5, + stimulation_ms: 120.0, + }] } else { vec![] }, next_context: ReadoutContext { boot: k < 10, bound: bound(k), - location: (k > 5).then_some(Location { area: 12, x: 3 + (k / 40) as u32, y: 7 }), + location: (k > 5).then_some(Location { + area: 12, + x: 3 + (k / 40) as u32, + y: 7, + }), }, }); if k == 60 { steps.push(ScriptStep::Rollback { frame: 2, - context: ReadoutContext { boot: false, bound: bound(k), location: None }, + context: ReadoutContext { + boot: false, + bound: bound(k), + location: None, + }, }); } if k == 75 { @@ -658,7 +670,11 @@ mod fafb { macro_channels: channels, frames: Arc::new(frame_pool(6, 783)), initial_frame: 0, - initial_context: ReadoutContext { boot: true, bound: vec![], location: None }, + initial_context: ReadoutContext { + boot: true, + bound: vec![], + location: None, + }, steps, checkpoints: [30, last].into_iter().collect(), } @@ -693,8 +709,14 @@ mod fafb { let script = script(90); let started = std::time::Instant::now(); let dataset = Arc::new(load_brain_dataset_from_dir(&dir).expect("the dataset loads")); - let want = DirectSource { dataset }.records(&script).expect("the reference runs"); - eprintln!("reference: {} records in {:?}", want.len(), started.elapsed()); + let want = DirectSource { dataset } + .records(&script) + .expect("the reference runs"); + eprintln!( + "reference: {} records in {:?}", + want.len(), + started.elapsed() + ); let summary = legacy_parity::golden_json(&script, &want); eprintln!("reference digest {}", summary["digest"]); for mode in [ExecutionMode::InProcess, ExecutionMode::Process] { @@ -708,16 +730,156 @@ mod fafb { macro_channels: script.macro_channels.clone(), worker_threads: 1, }; - let mut rig = LegacyRig::start(root.path(), mode, &[agent]).await.expect("the rig"); + let mut rig = LegacyRig::start(root.path(), mode, &[agent]) + .await + .expect("the rig"); let got = legacy_parity::run_on_worker(&mut rig, &id("fly-a"), &script) .await .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); rig.stop().await; legacy_parity::compare(&want, &got).unwrap_or_else(|e| panic!("{}: {e}", mode.label())); - eprintln!("{}: {} records identical in {:?}", mode.label(), got.len(), started.elapsed()); + eprintln!( + "{}: {} records identical in {:?}", + mode.label(), + got.len(), + started.elapsed() + ); } for row in summary["rows"].as_array().expect("rows").iter().step_by(10) { eprintln!(" {}", row.as_str().expect("a row")); } } } + +/// FND-01's `FLY_TRACE` reader and check, without a ROM: a trace written in flysim's line shape +/// from the reference's own records is accepted, and each kind of disagreement is refused. The +/// real traces are `flysim/tests/agent_trace_parity.rs`. +mod frame_trace { + use super::*; + use fly_session::legacy_parity::{ + ScriptStep, check_against_trace, read_frame_trace, toy_raw_script, trace_rates_digest, + }; + use fly_session::types::{DomainType, digest_of_bytes}; + use flybrain_core::decoder::gameboy::GAMEBOY_BUTTONS; + use serde_json::json; + + /// `flysim::trace` lines for a script and its records. + fn trace_of(script: &LegacyScript, records: &[ParityRecord]) -> Vec { + let mut lines: Vec = Vec::new(); + for (index, step) in script.steps.iter().enumerate() { + let record = &records[index + 1]; + match step { + ScriptStep::Frame { + sugar, + frame, + rewards, + .. + } => { + let decision = record.decision.as_ref().expect("a decision"); + let mut active: Vec<&str> = GAMEBOY_BUTTONS + .iter() + .enumerate() + .filter(|(bit, _)| decision.buttons[*bit]) + .map(|(_, name)| *name) + .collect(); + if let Some(channel) = &decision.macro_channel { + active.push(channel); + } + lines.push(json!({ + "behaviour": { + "step": (lines.len() as u64).to_string(), + "admissions": sugar.iter().map(|d| json!({"kind": "sugar", "durationMs": d})).collect::>(), + "ticksAdvanced": record.ticks.to_string(), + "brainTicks": record.brain_ticks.to_string(), + "remainder": record.remainder.to_json(), + "ratesDigest": trace_rates_digest(record.telemetry.as_ref().expect("telemetry")).expect("rates"), + "spikesDigest": record.spikes.clone().expect("spikes"), + "spikeCount": 0, + "decision": active, + "mask": decision.mask(), + "macroEvents": [], + "framebufferDigest": digest_of_bytes(&script.frames[*frame]), + "wramDigest": "", + "rewards": rewards.iter().map(|r| json!({"kind": "toy", "value": r.value, "stimulationMs": r.stimulation_ms})).collect::>(), + "rank": 0, + "acknowledgedBoundary": (lines.len() as u64 + 1).to_string(), + "boundaryActions": [], + }, + "operational": {"captures": []}, + })); + } + ScriptStep::Rollback { .. } => { + let last = lines.last_mut().expect("a frame before the rollback"); + last["behaviour"]["boundaryActions"] + .as_array_mut() + .expect("a list") + .push(json!({"kind": "rollback", "slotId": "best", "stateDigest": null})); + } + ScriptStep::Restore => unreachable!("the raw script has no restore"), + } + } + lines + } + + fn text(lines: &[Value]) -> String { + let mut out = json!({"format": "flysim-legacy-frame-trace-v1"}).to_string(); + out.push('\n'); + out.push_str(&json!({"boundary": "0", "operational": {"captures": [{"checkpointId": "g1", "afterActions": 0}]}}).to_string()); + for line in lines { + out.push('\n'); + out.push_str(&line.to_string()); + } + out + } + + #[test] + fn a_trace_of_the_reference_checks_and_every_disagreement_is_refused() { + let script = toy_raw_script(80); + let records = reference(&script); + let lines = trace_of(&script, &records); + let trace = read_frame_trace(&text(&lines)).expect("the trace reads"); + assert_eq!(trace.len(), 80); + let check = check_against_trace(&script, &records, &trace).expect("the reference checks"); + assert_eq!( + (check.transitions, check.sugar, check.rollbacks), + (80, 1, 1) + ); + + let refused = |edit: &dyn Fn(&mut Vec)| { + let mut lines = lines.clone(); + edit(&mut lines); + let trace = read_frame_trace(&text(&lines)).expect("the trace reads"); + check_against_trace(&script, &records, &trace).expect_err("a disagreement") + }; + let e = refused(&|l| l[30]["behaviour"]["spikesDigest"] = json!("00")); + assert!(e.contains("spikesDigest"), "{e}"); + let e = refused(&|l| l[30]["behaviour"]["brainTicks"] = json!("1")); + assert!(e.contains("brainTicks"), "{e}"); + let e = refused(&|l| { + l[30]["behaviour"]["remainder"] = json!({"numerator": "0", "denominator": "1"}) + }); + assert!(e.contains("remainder"), "{e}"); + let e = refused(&|l| l[30]["behaviour"]["ratesDigest"] = json!("00")); + assert!(e.contains("ratesDigest"), "{e}"); + let e = refused(&|l| l[30]["behaviour"]["decision"] = json!(["select"])); + assert!(e.contains("decision"), "{e}"); + let e = refused(&|l| l[9]["behaviour"]["admissions"] = json!([])); + assert!(e.contains("admitted"), "{e}"); + let e = refused(&|l| { + l[9]["behaviour"]["admissions"] = json!([{"kind": "reward", "value": 1.0}]) + }); + assert!(e.contains("RewardPulse"), "{e}"); + let e = refused(&|l| l[5]["behaviour"]["framebufferDigest"] = json!("00")); + assert!(e.contains("frame"), "{e}"); + let e = refused(&|l| { + for line in l.iter_mut() { + line["behaviour"]["boundaryActions"] = json!([]); + } + }); + assert!(e.contains("rollback"), "{e}"); + let e = refused(&|l| { + l.pop(); + }); + assert!(e.contains("ended"), "{e}"); + } +} diff --git a/services/flysim/crates/flysim/Cargo.toml b/services/flysim/crates/flysim/Cargo.toml index b3184ba..3884630 100644 --- a/services/flysim/crates/flysim/Cargo.toml +++ b/services/flysim/crates/flysim/Cargo.toml @@ -55,6 +55,9 @@ unicode-normalization = "0.1" # The legacy profile's pinned identities (`tests/legacy_profile_identity.rs`): test-only, so the # service itself does not link the session types. fly-session-types = { path = "../fly-session-types" } +# AGENT-01's worker checked against this loop's FLY_TRACE (`tests/agent_trace_parity.rs`): +# test-only as well. fly-session does not depend on flysim, so this is no cycle. +fly-session = { path = "../fly-session" } futures-util = "0.3" # `default-features = false` drops the remote-reference resolver (and with it reqwest and a # TLS stack): `packages/feed/src/schema.json` is self-contained, so nothing has to be fetched. diff --git a/services/flysim/crates/flysim/tests/agent_trace_parity.rs b/services/flysim/crates/flysim/tests/agent_trace_parity.rs new file mode 100644 index 0000000..3f81d47 --- /dev/null +++ b/services/flysim/crates/flysim/tests/agent_trace_parity.rs @@ -0,0 +1,422 @@ +//! AGENT-01 against FND-01: the legacy agent worker, and the direct reference, checked against the +//! `FLY_TRACE` of the legacy frame the stream runs (`flysim::frame::LegacyFrame`). +//! +//! The trace records what the loop did to the brain as digests -- ticks, clock, exact remainder, +//! rates, the spike set, the decision -- but not everything a worker needs to be driven: the +//! frames (only their digests), and the `{boot, bound, location}` context the executor and the +//! adapter produced. So this test is the host: it runs `LegacyFrame` on the real emulator with the +//! trace on, records those inputs beside it as a `LegacyScript`, then drives the same script +//! through `LegacyAgentWorker` in every execution mode and through `DirectReference`, and holds +//! each record to its trace line (`fly_session::legacy_parity::check_against_trace`). The script +//! is checked against the trace as well: the same admissions, frames, reward events and rollback. +//! +//! Two runs, both explicit ROM jobs (`. bin/rom-env.sh`, never a download): +//! +//! - `toy_raw_from_power_on`: `FLY_ROM` only. The committed toy connectome in raw mode from +//! power-on, with two sugar admissions. Cheap enough for every ROM run of the workspace. +//! - `fafb_macros_from_a_checkpoint`: also `FLY_AGENT01_FAFB=1` and `data/fafb-v783`. The live +//! composition -- `gameboy-legacy-fafb-v783-v1`, macros mode -- restored from a stream +//! checkpoint (`FLY_AGENT01_TRACE_CHECKPOINT`, else `FLY_DOOR_CHECKPOINT`), with sugar and one +//! ratchet rollback onto the checkpoint's slot. The worker starts from the checkpoint's agent +//! state (`AgentDriver::seed_from_legacy_state`). +//! +//! `FLY_AGENT01_TRACE_FRAMES` sets the length (default 600 toy, 240 FAFB). The worker program for +//! process mode is the workspace's `fly-session` binary; a build that did not produce it skips +//! that mode and says so. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use fly_session::ExecutionMode; +use fly_session::fly_session_types::gameboy::{Location, ReadoutContext}; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity::{ + self, DirectSource, LegacyRig, LegacyScript, ParityRecord, ReferenceSource, RestoredSource, + RewardEvent, RigAgent, ScriptStep, TraceCheck, TraceTransition, toy, +}; +use fly_session::types::{digest_of_bytes, id}; +use flybrain_core::agent::{AgentConfig, AgentState, NeuralAgent}; +use flybrain_core::dataset::{BrainDataset, load_brain_dataset_from_dir}; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flybrain_gb::adapter::GameAdapter; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flybrain_gb::ratchet::Ratchet; +use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator}; +use flysim::config::Config; +use flysim::frame::{LegacyFrame, Parts}; +use flysim::macros::{MacroLayer, macro_layer}; +use flysim::snapshot::MacroMode; +use flysim::trace::FrameTrace; + +fn rom() -> Option> { + let Some(path) = std::env::var_os("FLY_ROM") else { + eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)"); + return None; + }; + Some(std::fs::read(&path).unwrap_or_else(|e| panic!("FLY_ROM {path:?}: {e}"))) +} + +fn frames(default: usize) -> usize { + std::env::var("FLY_AGENT01_TRACE_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +fn context(adapter: &dyn GameAdapter, macros: Option<&MacroLayer>) -> ReadoutContext { + ReadoutContext { + boot: adapter.boot(), + bound: macros.map(MacroLayer::bound_channels).unwrap_or_default(), + location: adapter + .location() + .map(|(area, x, y)| Location { area, x, y }), + } +} + +/// Frames by content, so a still screen is stored once. +#[derive(Default)] +struct Pool { + frames: Vec>, + index: HashMap, +} + +impl Pool { + fn add(&mut self, frame: &[u8]) -> usize { + let digest = digest_of_bytes(frame); + *self.index.entry(digest).or_insert_with(|| { + self.frames.push(frame.to_vec()); + self.frames.len() - 1 + }) + } +} + +/// How the legacy run starts. +enum Start<'a> { + /// `LegacyFrame::initialize`: one frame with no button, then the warm-up on it. + PowerOn, + /// `LegacyFrame::restore` from a stream checkpoint, as `Sim::try_restore` does. + Checkpoint(&'a flysim::store::Checkpoint), +} + +struct LegacyRun { + script: LegacyScript, + trace: Vec, + /// The agent state the run started from, for a restored start. + start: Option, + rewards: Vec<&'static str>, +} + +/// The stream's frame on the real emulator with `FLY_TRACE` on, recording the script beside it. +/// +/// Sugar is admitted the way `Sim::stimulate` admits it (stimulate, then the trace), at the top of +/// the frame. `rollback_at` forces the ratchet's rollback at that boundary when the ratchet holds a +/// slot and did not roll back itself: `LegacyFrame::rollback` is exactly what `boundary` runs when +/// the ratchet fires, and whether it fires is the task's decision, not the agent's. +#[allow(clippy::too_many_arguments)] +fn run_legacy( + rom: &[u8], + data: &Arc, + start: Start<'_>, + mode: MacroMode, + frames: usize, + sugar: &[(usize, f64)], + rollback_at: Option, + trace_path: &Path, +) -> LegacyRun { + let mut emulator = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .expect("binjgb should accept the cartridge"); + let mut adapter = PokemonRedReward::new(); + let mut ratchet = Ratchet::with_policy(adapter.recovery_policy()); + let mut config = Config::default(); + config.loop_.game = "pokemon-red".to_string(); + config.macros.mode = mode; + let channels = if mode.dealt() { + flybrain_gb::macro_channels("pokemon-red") + } else { + Vec::new() + }; + let preset = gameboy_decoder_config_with_macros(&channels); + let hold_ms = preset + .macros + .as_ref() + .or(preset.exclusive.as_ref()) + .expect("the preset has a group") + .hold_ms; + let mut agent_config = AgentConfig::with_decoder(preset); + agent_config.warmup_ms = config.loop_.warmup_ms; + assert_eq!( + config.loop_.warmup_ms, + fly_session::fly_session_types::gameboy::WARMUP_MS, + "the stream's warm-up is the profile's" + ); + let mut agent = NeuralAgent::new(Arc::clone(data), agent_config).expect("a valid agent"); + let mut frame = + LegacyFrame::new().with_trace(Some(FrameTrace::create(trace_path).expect("a trace file"))); + let start_state = match start { + Start::PowerOn => { + frame + .initialize(&mut emulator, &mut agent) + .expect("the first frame and the warm-up"); + None + } + Start::Checkpoint(checkpoint) => { + frame + .restore( + &mut Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: None, + }, + checkpoint, + ) + .expect("the checkpoint should restore"); + Some(checkpoint.agent.clone()) + } + }; + // `Sim::boot`: the macro layer is built after the restore or warm-up, seeded from the network + // as it then stands, and observes once before the first frame. + let mut macros = 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 mut pool = Pool::default(); + let initial_frame = pool.add(&frame.frame_buffer); + let initial_context = context(&adapter, macros.as_ref()); + let mut steps = Vec::new(); + let mut kinds = Vec::new(); + for k in 1..=frames { + let mut admitted = Vec::new(); + for (_, duration) in sugar.iter().filter(|(at, _)| *at == k) { + agent.network.stimulate(*duration); + if let Some(trace) = frame.trace_mut() { + trace.sugar(*duration); + } + admitted.push(*duration); + } + 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 ()).expect("a frame"); + let produced = pool.add(&frame.frame_buffer); + let rewards: Vec = transition + .evaluated + .rewards + .iter() + .map(|event| { + kinds.push(event.kind); + RewardEvent { + value: event.value, + stimulation_ms: f64::from(event.stimulation_ms), + } + }) + .collect(); + // The next context is read after the evaluation and before the ratchet: what the task + // hands `Agent.Commit`. + let next_context = context(&*parts.adapter, parts.macros.as_deref()); + let boundary = frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .expect("the boundary"); + steps.push(ScriptStep::Frame { + sugar: admitted, + frame: produced, + rewards, + next_context, + }); + let mut rolled_back = boundary.rollback.is_some(); + if !rolled_back && rollback_at == Some(k) && parts.ratchet.game().is_some() { + frame.rollback(&mut parts).expect("the forced rollback"); + rolled_back = true; + } + if rolled_back { + let restored = pool.add(&frame.frame_buffer); + steps.push(ScriptStep::Rollback { + frame: restored, + context: context(&*parts.adapter, parts.macros.as_deref()), + }); + } + } + frame.finish_trace(); + drop(frame); + let text = std::fs::read_to_string(trace_path).expect("the trace reads back"); + let trace = legacy_parity::read_frame_trace(&text).expect("a flysim-legacy-frame-trace-v1"); + LegacyRun { + script: LegacyScript { + name: format!("flysim-{}", mode.as_str()), + macro_channels: channels.iter().map(|c| (*c).to_owned()).collect(), + frames: Arc::new(pool.frames), + initial_frame, + initial_context, + steps, + checkpoints: Default::default(), + }, + trace, + start: start_state, + rewards: kinds, + } +} + +fn worker_modes() -> Vec { + let mut modes = vec![ExecutionMode::InProcess, ExecutionMode::Thread]; + let program = fly_session::launcher::default_worker_program(); + if program.is_file() { + modes.push(ExecutionMode::Process); + } else { + eprintln!( + "process mode skipped: no worker program at {} (build the fly-session binary, or set {})", + program.display(), + fly_session::launcher::WORKER_PROGRAM_ENV + ); + } + modes +} + +async fn on_worker( + mode: ExecutionMode, + run: &LegacyRun, + dataset_dir: PathBuf, + profile: LegacyProfileKind, +) -> Vec { + let root = tempfile::tempdir().expect("tmp"); + let agent = RigAgent { + agent_id: id("fly"), + port_id: id("p1"), + dataset_dir, + profile, + macro_channels: run.script.macro_channels.clone(), + worker_threads: 1, + }; + let mut rig = LegacyRig::start(root.path(), mode, &[agent]) + .await + .expect("the rig"); + let records = + legacy_parity::run_on_worker_from(&mut rig, &id("fly"), &run.script, run.start.as_ref()) + .await + .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + rig.stop().await; + records +} + +fn report(what: &str, check: &TraceCheck) { + eprintln!( + "{what}: {} transitions identical to FLY_TRACE ({} sugar, {} reward events, {} rollbacks, \ + {} macro decisions, {} pressed, {} spikes)", + check.transitions, + check.sugar, + check.rewards, + check.rollbacks, + check.macro_decisions, + check.pressed, + check.spikes + ); +} + +async fn check_all( + run: &LegacyRun, + reference: Vec, + dataset_dir: PathBuf, + profile: LegacyProfileKind, +) { + let check = legacy_parity::check_against_trace(&run.script, &reference, &run.trace) + .unwrap_or_else(|e| panic!("the direct reference against FLY_TRACE: {e}")); + report("direct reference", &check); + for mode in worker_modes() { + let started = std::time::Instant::now(); + let got = on_worker(mode, run, dataset_dir.clone(), profile).await; + let worker = legacy_parity::check_against_trace(&run.script, &got, &run.trace) + .unwrap_or_else(|e| panic!("{} against FLY_TRACE: {e}", mode.label())); + assert_eq!(worker, check); + // And record for record, telemetry included, the worker is the reference. + legacy_parity::compare(&reference, &got) + .unwrap_or_else(|e| panic!("{} against the direct reference: {e}", mode.label())); + report( + &format!("worker {} ({:?})", mode.label(), started.elapsed()), + &worker, + ); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn toy_raw_from_power_on() { + let Some(rom) = rom() else { return }; + let data = Arc::new(load_brain_dataset_from_dir(toy::dir()).expect("the toy dataset")); + let dir = tempfile::tempdir().expect("tmp"); + let n = frames(600); + let run = run_legacy( + &rom, + &data, + Start::PowerOn, + MacroMode::Raw, + n, + &[(40, 300.0), (n / 2, 500.0)], + None, + &dir.path().join("trace.jsonl"), + ); + assert_eq!(run.trace.len(), n); + let reference = DirectSource { dataset: data } + .records(&run.script) + .expect("the direct reference runs"); + check_all(&run, reference, toy::dir(), LegacyProfileKind::Toy).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fafb_macros_from_a_checkpoint() { + let Some(rom) = rom() else { return }; + if std::env::var_os("FLY_AGENT01_FAFB").is_none() { + eprintln!("skipping: FLY_AGENT01_FAFB is not set"); + return; + } + let Some(dataset_dir) = legacy_parity::fafb_dir() else { + eprintln!("skipping: data/fafb-v783 is not present in this checkout"); + return; + }; + let Some(path) = std::env::var_os("FLY_AGENT01_TRACE_CHECKPOINT") + .or_else(|| std::env::var_os("FLY_DOOR_CHECKPOINT")) + else { + eprintln!("skipping: neither FLY_AGENT01_TRACE_CHECKPOINT nor FLY_DOOR_CHECKPOINT is set"); + return; + }; + let checkpoint = flysim::store::load(Path::new(&path)).expect("a FLYSIM01 checkpoint"); + let data = Arc::new(load_brain_dataset_from_dir(&dataset_dir).expect("the dataset")); + let dir = tempfile::tempdir().expect("tmp"); + let n = frames(240); + let started = std::time::Instant::now(); + let run = run_legacy( + &rom, + &data, + Start::Checkpoint(&checkpoint), + MacroMode::Macros, + n, + &[(10, 400.0), (n / 2, 250.0)], + Some(n / 3), + &dir.path().join("trace.jsonl"), + ); + eprintln!( + "legacy loop: {n} frames from {} in {:?}; reward events {:?}", + Path::new(&path).display(), + started.elapsed(), + run.rewards + ); + assert!( + run.script + .steps + .iter() + .any(|s| matches!(s, ScriptStep::Rollback { .. })), + "the checkpoint holds no ratchet slot to roll back onto" + ); + let reference = RestoredSource { + dataset: data, + state: run.start.clone().expect("a restored start"), + } + .records(&run.script) + .expect("the direct reference runs"); + check_all(&run, reference, dataset_dir, LegacyProfileKind::Production).await; +} From dc403e8cdf67b6d7695f0b0294fc17e319b1b6ca Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 14:26:07 +0000 Subject: [PATCH 15/26] docs: AGENT-01 rebased onto v0.6.5 and checked against FLY_TRACE; FLYSIM01 import seeds learning.updates --- .../design/session-framework/implementation.md | 18 ++++++++++++++++++ .../session-framework/legacy-gameboy-v1.md | 6 ++++++ 2 files changed, 24 insertions(+) diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index 8c00be1..39f88ef 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -187,6 +187,24 @@ turned out to be the identity: the legacy names are already `Id`s. It is recorde [legacy-gameboy-v1](legacy-gameboy-v1.md) section 13, with the other agent-adapter choices. The harness's `ReferenceSource` is the seam for FND-01's `FLY_TRACE`. +**2026-09-29 (AGENT-01 rebased onto v0.6.5 and checked against FND-01's trace).** The rebase onto +main had no conflicts. Main changed nothing the worker reads except the adapter id in the +fixtures (v7). The toy goldens and the FAFB reference digest are unchanged. `FLY_TRACE` carries +the frames only as digests and not the `{boot, bound, location}` context, so it checks a worker +and cannot drive one. `legacy_parity::read_frame_trace` and `check_against_trace` hold a run's +records to it: ticks, clock, exact remainder, rates digest, spike-set digest and decision. The +script is checked too: the same sugar, frames, reward events and rollback. +`flysim/tests/agent_trace_parity.rs` is the host. It runs `LegacyFrame` on the ROM with the trace +on, records the missing inputs and checks the worker (in-process, thread and process) and the +direct reference against the trace: + +- the toy connectome in raw mode from power-on, for every ROM run; +- `gameboy-legacy-fafb-v783-v1` in macros mode from stream checkpoints (`FLY_AGENT01_FAFB=1`), + with sugar and a ratchet rollback, the worker seeded from the checkpoint's agent state. + +Both are identical. Found on the way: a `FLYSIM01` import must start `learning.updates` at the +legacy `plasticity.updates` (legacy-gameboy-v1 section 13, amendment of 2026-09-29). + **Implement:** adapter over existing LIF, plasticity, retina and fixed readout primitives; reference-first composition/goldens; independently seeded agent state and shared immutable data. Avoid using the old whole-frame `tick` wrapper if it changes the specified phase ordering. diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 8061213..343eee2 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -389,6 +389,12 @@ agent-adapter choices that the sections above leave open. `LegacyAgentWorker` `signal` is `plasticity.signal`. The legacy per-synapse count (`LearningStats.changed`, the gains away from 1.0) is not carried. It can still be read from a captured state. `stimulusRemainingMs` is the network's `reward_remaining` after the operation. + *Amended 2026-09-29 (AGENT-01 rebase):* `FLYSIM01` records `plasticity.updates` but not the + reinforcement calls. An agent imported from a `FLYSIM01` agent state therefore starts + `updates` at that state's `plasticity.updates`, which is a lower bound on the calls made. Starting + it at zero makes the first telemetry violate `changed <= updates`: on the live fly `changed` is + in the thousands. `legacy_parity::legacy_reinforcements` is the rule. The import that ENV-01 + or STATE-01 ships must apply it. - *Spikes.* Each `Agent.Commit` reply carries the attachment `telemetry.spikes`, with content type `application/x-fly-spike-bitset`. It uses the legacy feed's layout: bit *i* is neuron *i*, `ceil(neurons/8)` bytes. It covers the transition's ticks: a neuron is set when its last spike From 3d1a81a6796b1e574a2167519e383baf1c71750c Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:43:40 +0000 Subject: [PATCH 16/26] flybrain-gb: the boundary memory image (MEM-01) One read-only bulk read in the shim, fly_gb_read_memory_image: the address space's memory in address order, the register windows (VRAM, OAM, I/O) read $FF because binjgb's catch-up on a register read moves the exported state. MemoryImage, Cartridge and ImageReader put an image and the ROM behind MemoryReader, so the same macro engine and adapter run over it; the emulator's bank reads go through the same Cartridge. ROM tests prove the read leaves the state byte-identical, equals the single and cached reads, changes nothing downstream, and measure its cost. --- .../flysim/crates/flybrain-gb/csrc/shim.c | 45 +++ .../flysim/crates/flybrain-gb/src/emulator.rs | 70 ++-- services/flysim/crates/flybrain-gb/src/ffi.rs | 2 + .../flysim/crates/flybrain-gb/src/image.rs | 321 ++++++++++++++++++ services/flysim/crates/flybrain-gb/src/lib.rs | 5 + .../flybrain-gb/tests/rom_memory_image.rs | 303 +++++++++++++++++ 6 files changed, 721 insertions(+), 25 deletions(-) create mode 100644 services/flysim/crates/flybrain-gb/src/image.rs create mode 100644 services/flysim/crates/flybrain-gb/tests/rom_memory_image.rs diff --git a/services/flysim/crates/flybrain-gb/csrc/shim.c b/services/flysim/crates/flybrain-gb/csrc/shim.c index 1494e12..f31e934 100644 --- a/services/flysim/crates/flybrain-gb/csrc/shim.c +++ b/services/flysim/crates/flybrain-gb/csrc/shim.c @@ -127,6 +127,51 @@ u8 fly_gb_read_mem(FlyGb* gb, u16 address) { return emulator_read_mem(gb->e, address); } +/* + * The boundary memory image (MEM-01, legacy-gameboy-v1 section 8 as amended + * 2026-09-29): the CPU address space $0000..=$FFFF in address order. + * + * Every *memory* byte is exactly what fly_gb_read_mem returns for it: ROM as + * mapped ($0000-$7FFF), cartridge RAM ($A000-$BFFF), work RAM and its echo + * ($C000-$FDFF), the unused block ($FEA0-$FEFF), high RAM ($FF80-$FFFE) and + * IE ($FFFF). binjgb reads all of these straight out of its arrays. + * + * The *register* windows are not captured and read as FLY_GB_NOT_CAPTURED: + * VRAM ($8000-$9FFF), OAM ($FE00-$FE9F) and I/O, APU and wave RAM + * ($FF00-$FF7F). binjgb's read of those first runs a lazy catch-up + * (ppu_synchronize, timer_/serial_/intr_synchronize, apu_synchronize) that + * rewrites the subsystem's sync bookkeeping, so reading them would change the + * exported state and could not be called read-only. Nothing a task or an + * executor reads lives there (flysim tests/rom_memory_image.rs records every + * address they read). + * + * Read-only: the captured bytes are the same emulator_read_mem the single read + * makes, and nothing but `out` is written. fly_gb_set_buttons stays the only + * write into a running game; there is no memory-write path. + */ +#define FLY_GB_MEMORY_IMAGE_SIZE 0x10000u +#define FLY_GB_NOT_CAPTURED 0xffu + +size_t fly_gb_memory_image_size(void) { return FLY_GB_MEMORY_IMAGE_SIZE; } + +static int fly_gb_captured(u32 address) { + if (address >= 0x8000u && address <= 0x9fffu) return 0; /* VRAM */ + if (address >= 0xfe00u && address <= 0xfe9fu) return 0; /* OAM */ + if (address >= 0xff00u && address <= 0xff7fu) return 0; /* I/O, APU, wave */ + return 1; +} + +int fly_gb_read_memory_image(FlyGb* gb, u8* out, size_t size) { + u32 address; + if (out == NULL || size != FLY_GB_MEMORY_IMAGE_SIZE) return -1; + for (address = 0; address < FLY_GB_MEMORY_IMAGE_SIZE; ++address) { + out[address] = fly_gb_captured(address) + ? emulator_read_mem(gb->e, (u16)address) + : (u8)FLY_GB_NOT_CAPTURED; + } + return 0; +} + u32 fly_gb_audio_frequency(FlyGb* gb) { return emulator_get_audio_buffer(gb->e)->frequency; } diff --git a/services/flysim/crates/flybrain-gb/src/emulator.rs b/services/flysim/crates/flybrain-gb/src/emulator.rs index dd9b3e3..838fd6e 100644 --- a/services/flysim/crates/flybrain-gb/src/emulator.rs +++ b/services/flysim/crates/flybrain-gb/src/emulator.rs @@ -3,10 +3,9 @@ use std::ffi::c_void; use std::fmt; -use sha2::{Digest, Sha256}; - use crate::adapter::MemoryReader; use crate::ffi; +use crate::image::{Cartridge, MEMORY_IMAGE_LEN, MemoryImage}; /// Game Boy screen geometry, from `emulator.h`. pub const SCREEN_WIDTH: usize = 160; @@ -26,10 +25,6 @@ pub const CPU_TICKS_PER_SECOND: u64 = 4_194_304; /// so there is no `NEW_FRAME` event to wait for yet. const MAX_FRAME_ATTEMPTS: u32 = 120; -/// Bytes in one ROM bank (`$4000`), which is how [`Emulator::read_rom_bank`] -/// turns a bank number and a CPU address into an offset in the cartridge image. -const ROM_BANK_BYTES: usize = 0x4000; - /// Audio frequency flysim runs the emulator at. binjgb resamples internally to /// whatever is requested, so this is only a default. pub const DEFAULT_AUDIO_FREQUENCY: u32 = 48_000; @@ -144,9 +139,9 @@ pub struct Emulator { /// The shim owns its own padded copy behind the handle and does not hand it /// back, so this is a second one. It is read-only from here: nothing in this /// workspace writes a ROM byte, and the bank-addressed read is the only - /// reason it is kept. - rom: std::sync::Arc<[u8]>, - rom_sha256: [u8; 32], + /// reason it is kept. The same [`Cartridge`] an image-backed executor holds + /// (MEM-01), so a bank read is one rule over one set of bytes on both sides. + rom: Cartridge, audio_frequency: u32, /// Raw binjgb samples drained since the last [`Emulator::take_audio`]. pending_audio: Vec, @@ -178,8 +173,7 @@ impl Emulator { debug_assert_eq!(unsafe { ffi::fly_gb_frame_buffer_size() }, FRAMEBUFFER_LEN); Ok(Self { gb, - rom: rom.into(), - rom_sha256: Sha256::digest(rom).into(), + rom: Cartridge::new(rom), audio_frequency, pending_audio: Vec::new(), cache: FrameCache::new(), @@ -263,14 +257,45 @@ impl Emulator { /// No bank register is written and the emulator's state does not move: this /// is a read of bytes the process already owns. pub fn read_rom_bank(&self, bank: u8, address: u16) -> Option { - let offset = match address { - 0x0000..=0x3fff => usize::from(address), - 0x4000..=0x7fff => { - usize::from(bank) * ROM_BANK_BYTES + usize::from(address) - ROM_BANK_BYTES - } - _ => return None, - }; - self.rom.get(offset).copied() + self.rom.read_bank(bank, address) + } + + /// The cartridge this emulator runs, as the executor's ROM asset holds it. + pub fn cartridge(&self) -> Cartridge { + self.rom.clone() + } + + /// The boundary memory image: the CPU address space in one bulk read + /// (`legacy-gameboy-v1` section 8, MEM-01). + /// + /// For every memory address ([`crate::image::CAPTURED`]) byte *i* is what + /// [`Emulator::read_uncached`] returns for *i* now, and so what + /// [`Emulator::read_wram`] returns for it anywhere between this frame and + /// the next: the per-frame cache is only ever filled from the same read, and + /// nothing between two frames moves the emulator. The register windows + /// (VRAM, OAM, I/O) read [`crate::image::NOT_CAPTURED`], because binjgb's + /// read of a register runs a catch-up that moves the exported state. + /// + /// Read-only: the emulator's exported state is byte-identical before and + /// after, and a run read in bulk every frame is frame-for-frame identical to + /// one never read (`tests/rom_memory_image.rs`). The per-frame cache is + /// neither consulted nor filled. + pub fn read_memory_image(&self) -> MemoryImage { + let mut image = MemoryImage::zeroed(); + self.read_memory_image_into(&mut image); + image + } + + /// [`Emulator::read_memory_image`] into an image the caller already owns, + /// so a boundary's read allocates nothing. + pub fn read_memory_image_into(&self, image: &mut MemoryImage) { + debug_assert_eq!(unsafe { ffi::fly_gb_memory_image_size() }, MEMORY_IMAGE_LEN); + let out = image.as_mut_bytes(); + let code = + unsafe { ffi::fly_gb_read_memory_image(self.gb, out.as_mut_ptr(), MEMORY_IMAGE_LEN) }; + // The only refusals are a null buffer and a wrong size, and both are + // ruled out by the type. + assert_eq!(code, 0, "fly_gb_read_memory_image refused a {MEMORY_IMAGE_LEN}-byte buffer"); } /// Sample rate of the raw buffer, as binjgb configured it. @@ -345,12 +370,7 @@ impl Emulator { /// SHA-256 of the ROM bytes as supplied, lowercase hex. This is the /// `romSha256` half of the checkpoint compatibility string. pub fn rom_sha256(&self) -> String { - let mut hex = String::with_capacity(64); - for byte in self.rom_sha256 { - use fmt::Write; - let _ = write!(hex, "{byte:02x}"); - } - hex + self.rom.sha256_hex() } /// Emulated CPU ticks since boot. diff --git a/services/flysim/crates/flybrain-gb/src/ffi.rs b/services/flysim/crates/flybrain-gb/src/ffi.rs index 8973a8b..3a2b792 100644 --- a/services/flysim/crates/flybrain-gb/src/ffi.rs +++ b/services/flysim/crates/flybrain-gb/src/ffi.rs @@ -38,6 +38,8 @@ unsafe extern "C" { pub fn fly_gb_set_buttons(gb: *mut FlyGb, mask: u32); pub fn fly_gb_read_mem(gb: *mut FlyGb, address: u16) -> u8; + pub fn fly_gb_memory_image_size() -> usize; + pub fn fly_gb_read_memory_image(gb: *mut FlyGb, out: *mut u8, size: usize) -> c_int; pub fn fly_gb_audio_frequency(gb: *mut FlyGb) -> u32; pub fn fly_gb_audio_size(gb: *mut FlyGb) -> usize; diff --git a/services/flysim/crates/flybrain-gb/src/image.rs b/services/flysim/crates/flybrain-gb/src/image.rs new file mode 100644 index 0000000..17cf036 --- /dev/null +++ b/services/flysim/crates/flybrain-gb/src/image.rs @@ -0,0 +1,321 @@ +//! The boundary memory image and the cartridge beside it (MEM-01). +//! +//! `docs/design/session-framework/legacy-gameboy-v1.md` section 8: on the session framework the +//! macros run in the coordinator's action executor, not beside a live emulator. What they read +//! there is one 64 KiB image of the CPU address space per boundary, carried as an artifact in the +//! observation's `inspection`, plus the ROM as an `AssetRef`. This module is the read side of that +//! seam and nothing else: +//! +//! - [`MemoryImage`] is the image: for every memory address ([`CAPTURED`]) byte *i* is what +//! `fly_gb_read_mem(i)` returned at the boundary, taken in one bulk read by +//! [`crate::Emulator::read_memory_image`]; the register windows read [`NOT_CAPTURED`]. +//! - [`Cartridge`] is the ROM, content-addressed by its SHA-256, answering the bank-addressed +//! reads the image cannot ([`MemoryReader::read_rom`]). +//! - [`ImageReader`] puts the two behind [`MemoryReader`], so the **same** macro engine, scene +//! detector and reward adapter that read a live [`crate::Emulator`] read an image instead. There +//! is no second implementation of any rule: [`crate::pokemon_red::state::PokeState`] takes a +//! `&mut dyn MemoryReader`, and this is one. +//! +//! Nothing here writes to a game. An image is a copy; reading it cannot move an emulator. + +use std::fmt; +use std::sync::Arc; + +use sha2::{Digest, Sha256}; + +use crate::adapter::MemoryReader; + +/// Bytes in one image: `$0000..=$FFFF`. `fly-session-types`' `gameboy::MEMORY_IMAGE_BYTES`. +pub const MEMORY_IMAGE_LEN: usize = 0x1_0000; + +/// The artifact's content type (`legacy-gameboy-v1` section 8: "a listed bus attachment, content +/// type `application/octet-stream`"). The encoding is the raw bytes in address order, nothing +/// before and nothing after, so the artifact's `byteLength` is always [`MEMORY_IMAGE_LEN`]. +pub const MEMORY_IMAGE_CONTENT_TYPE: &str = "application/octet-stream"; + +/// What an address outside [`CAPTURED`] holds in an image: `$FF`, which is also what binjgb +/// returns for a read the hardware refuses (`INVALID_READ_BYTE`). +pub const NOT_CAPTURED: u8 = 0xff; + +/// The address ranges an image captures, inclusive: every *memory* byte of the address space. +/// +/// Each one is exactly what `fly_gb_read_mem` returned at the boundary: ROM as mapped, cartridge +/// RAM, work RAM and its echo, the unused block, high RAM and `IE`. The three *register* windows +/// between them -- VRAM `$8000-$9FFF`, OAM `$FE00-$FE9F`, I/O with the APU and wave RAM +/// `$FF00-$FF7F` -- are not captured and read [`NOT_CAPTURED`]: binjgb's read of a register +/// first runs the subsystem's lazy catch-up (`ppu_synchronize`, `timer_synchronize`, ...), which +/// rewrites its sync bookkeeping, so reading one moves the exported state (`legacy-gameboy-v1` +/// section 8, amendment of 2026-09-29). Nothing the tasks or executors read is in them. +pub const CAPTURED: [(u16, u16); 4] = + [(0x0000, 0x7fff), (0xa000, 0xfdff), (0xfea0, 0xfeff), (0xff80, 0xffff)]; + +/// Whether an image captures `address` ([`CAPTURED`]). +pub fn captured(address: u16) -> bool { + CAPTURED.iter().any(|&(low, high)| (low..=high).contains(&address)) +} + +/// Bytes in one ROM bank (`$4000`). +const ROM_BANK_BYTES: usize = 0x4000; + +/// Why an image or a cartridge was refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ImageError { + /// An image is exactly [`MEMORY_IMAGE_LEN`] bytes. + ImageSize { actual: usize }, + /// The cartridge's SHA-256 is not the one the composition names. + RomDigest { expected: String, actual: String }, +} + +impl fmt::Display for ImageError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::ImageSize { actual } => { + write!(f, "a memory image is {MEMORY_IMAGE_LEN} bytes, got {actual}") + } + Self::RomDigest { expected, actual } => { + write!(f, "the cartridge's sha256 is {actual}, the composition names {expected}") + } + } + } +} + +impl std::error::Error for ImageError {} + +/// One boundary's view of the CPU address space. +/// +/// Owned and immutable once taken: it is the payload of an inspection artifact, which the +/// coordinator keeps until the transition that reads it has been evaluated +/// (`state-media-v1` section 3, RT-01a amendment). +#[derive(Clone, PartialEq, Eq)] +pub struct MemoryImage { + bytes: Box<[u8; MEMORY_IMAGE_LEN]>, +} + +impl MemoryImage { + /// An image of zeroes, to be filled by [`crate::Emulator::read_memory_image_into`]. + pub fn zeroed() -> Self { + let bytes: Box<[u8]> = vec![0u8; MEMORY_IMAGE_LEN].into_boxed_slice(); + Self { bytes: bytes.try_into().expect("exactly MEMORY_IMAGE_LEN bytes") } + } + + /// Decode an artifact's bytes. Exactly [`MEMORY_IMAGE_LEN`] of them, or refused. + pub fn from_bytes(bytes: &[u8]) -> Result { + if bytes.len() != MEMORY_IMAGE_LEN { + return Err(ImageError::ImageSize { actual: bytes.len() }); + } + let mut image = Self::zeroed(); + image.bytes.copy_from_slice(bytes); + Ok(image) + } + + /// The artifact's bytes: the address space in address order. + pub fn as_bytes(&self) -> &[u8; MEMORY_IMAGE_LEN] { + &self.bytes + } + + pub(crate) fn as_mut_bytes(&mut self) -> &mut [u8; MEMORY_IMAGE_LEN] { + &mut self.bytes + } + + /// The byte at a CPU address. + pub fn byte(&self, address: u16) -> u8 { + self.bytes[usize::from(address)] + } + + /// SHA-256 of the artifact's bytes, 64 lowercase hex digits: the bus `Digest` encoding. + /// + /// Optional on the live artifact (a transient frame, `state-media-v1` section 1); mandatory + /// only if an image is ever carried in a checkpoint payload. + pub fn sha256_hex(&self) -> String { + hex(&Sha256::digest(self.bytes.as_slice())) + } +} + +impl fmt::Debug for MemoryImage { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MemoryImage").field("sha256", &self.sha256_hex()).finish() + } +} + +/// The ROM, as the executor holds it: the composition's `AssetRef`, content-addressed. +/// +/// Cheap to clone (one `Arc`). The emulator holds one too, for its own [`MemoryReader::read_rom`], +/// so the live reader and the image reader answer a bank read from the same function over the +/// same bytes. +#[derive(Clone)] +pub struct Cartridge { + bytes: Arc<[u8]>, + sha256: [u8; 32], +} + +impl Cartridge { + /// The cartridge as supplied: the bytes the emulator was given, before its padding. + pub fn new(rom: &[u8]) -> Self { + Self { bytes: rom.into(), sha256: Sha256::digest(rom).into() } + } + + /// The cartridge only if its SHA-256 is `expected` (lowercase hex), which is how the executor + /// refuses a ROM that is not the environment's `contentDigest` (`legacy-gameboy-v1` section 8). + pub fn verified(rom: &[u8], expected: &str) -> Result { + let cartridge = Self::new(rom); + let actual = cartridge.sha256_hex(); + if actual != expected { + return Err(ImageError::RomDigest { expected: expected.to_string(), actual }); + } + Ok(cartridge) + } + + /// SHA-256 of the ROM bytes as supplied, lowercase hex: the compatibility string's `romSha256`, + /// the environment's `contentDigest` and the inspection's `romDigest`. + pub fn sha256_hex(&self) -> String { + hex(&self.sha256) + } + + pub fn len(&self) -> usize { + self.bytes.len() + } + + pub fn is_empty(&self) -> bool { + self.bytes.is_empty() + } + + /// One byte of ROM bank `bank` at CPU address `address`: see [`MemoryReader::read_rom`]. + pub fn read_bank(&self, bank: u8, address: u16) -> Option { + let offset = match address { + 0x0000..=0x3fff => usize::from(address), + 0x4000..=0x7fff => { + usize::from(bank) * ROM_BANK_BYTES + usize::from(address) - ROM_BANK_BYTES + } + _ => return None, + }; + self.bytes.get(offset).copied() + } +} + +impl fmt::Debug for Cartridge { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Cartridge") + .field("sha256", &self.sha256_hex()) + .field("len", &self.bytes.len()) + .finish() + } +} + +/// A [`MemoryReader`] over one boundary's image and the cartridge. +/// +/// What the executor hands the macro engine in Phase B, and the task in Phase C: the same +/// `&mut dyn MemoryReader` the legacy loop hands them with a live emulator behind it. It needs no +/// cache of its own, because an image is already one frame's reads. +#[derive(Debug, Clone, Copy)] +pub struct ImageReader<'a> { + image: &'a MemoryImage, + rom: &'a Cartridge, +} + +impl<'a> ImageReader<'a> { + pub fn new(image: &'a MemoryImage, rom: &'a Cartridge) -> Self { + Self { image, rom } + } + + pub fn image(&self) -> &'a MemoryImage { + self.image + } +} + +impl MemoryReader for ImageReader<'_> { + fn read8(&mut self, address: u16) -> u8 { + self.image.byte(address) + } + + fn read_rom(&mut self, bank: u8, address: u16) -> Option { + self.rom.read_bank(bank, address) + } +} + +fn hex(bytes: &[u8]) -> String { + use fmt::Write; + let mut out = String::with_capacity(bytes.len() * 2); + for byte in bytes { + let _ = write!(out, "{byte:02x}"); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_image_is_exactly_the_address_space() { + assert_eq!(MEMORY_IMAGE_LEN, usize::from(u16::MAX) + 1); + assert_eq!( + MemoryImage::from_bytes(&[0; MEMORY_IMAGE_LEN - 1]).unwrap_err(), + ImageError::ImageSize { actual: MEMORY_IMAGE_LEN - 1 } + ); + assert_eq!( + MemoryImage::from_bytes(&[0; MEMORY_IMAGE_LEN + 1]).unwrap_err(), + ImageError::ImageSize { actual: MEMORY_IMAGE_LEN + 1 } + ); + } + + #[test] + fn the_encoding_is_the_bytes_in_address_order() { + let bytes: Vec = (0..MEMORY_IMAGE_LEN).map(|i| (i ^ (i >> 8)) as u8).collect(); + let image = MemoryImage::from_bytes(&bytes).unwrap(); + assert_eq!(image.as_bytes().as_slice(), bytes.as_slice()); + let rom = Cartridge::new(&[0; 0x8000]); + let mut reader = ImageReader::new(&image, &rom); + for address in [0x0000u16, 0x00ff, 0xc000, 0xd35e, 0xff80, 0xffff] { + assert_eq!(reader.read8(address), bytes[usize::from(address)], "{address:#06x}"); + } + // The digest is over exactly those bytes, in the bus `Digest` encoding. + assert_eq!(image.sha256_hex(), hex(&Sha256::digest(&bytes))); + assert_eq!(image.sha256_hex().len(), 64); + assert!(image.sha256_hex().bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))); + } + + #[test] + fn the_captured_ranges_are_the_memory_between_the_register_windows() { + let captured_count = (0..=u16::MAX).filter(|&address| captured(address)).count(); + // 64 KiB less VRAM (8 KiB), OAM (160 B) and I/O (128 B). + assert_eq!(captured_count, MEMORY_IMAGE_LEN - 0x2000 - 0xa0 - 0x80); + for register in [0x8000u16, 0x9fff, 0xfe00, 0xfe9f, 0xff00, 0xff44, 0xff7f] { + assert!(!captured(register), "{register:#06x}"); + } + for memory in [0x0000u16, 0x7fff, 0xa000, 0xc000, 0xdfff, 0xe000, 0xfdff, 0xfea0, 0xff80, 0xffff] { + assert!(captured(memory), "{memory:#06x}"); + } + // Every symbol the Pokémon macros and adapter name is in WRAM or HRAM. + use crate::pokemon_red::symbols::ram; + for symbol in [ram::wCurMap, ram::wPartyCount, ram::wTileMap, ram::wStatusFlags7, ram::wListMenuID] { + assert!(captured(symbol), "{symbol:#06x}"); + } + } + + #[test] + fn a_bank_read_is_the_emulators_rule() { + // Four banks, each byte naming its bank. + let rom: Vec = (0..4 * ROM_BANK_BYTES).map(|i| (i / ROM_BANK_BYTES) as u8).collect(); + let cartridge = Cartridge::new(&rom); + // Bank 0 is always mapped, whatever the bank asked for. + assert_eq!(cartridge.read_bank(3, 0x0100), Some(0)); + assert_eq!(cartridge.read_bank(3, 0x4000), Some(3)); + assert_eq!(cartridge.read_bank(1, 0x7fff), Some(1)); + // A bank the cartridge does not have, and an address that is not ROM. + assert_eq!(cartridge.read_bank(4, 0x4000), None); + assert_eq!(cartridge.read_bank(1, 0x8000), None); + assert_eq!(cartridge.read_bank(1, 0xc000), None); + } + + #[test] + fn a_cartridge_is_refused_under_another_digest() { + let rom = [7u8; 0x8000]; + let digest = Cartridge::new(&rom).sha256_hex(); + assert!(Cartridge::verified(&rom, &digest).is_ok()); + let wrong = "0".repeat(64); + assert!(matches!( + Cartridge::verified(&rom, &wrong), + Err(ImageError::RomDigest { .. }) + )); + } +} diff --git a/services/flysim/crates/flybrain-gb/src/lib.rs b/services/flysim/crates/flybrain-gb/src/lib.rs index 15fec61..d950de3 100644 --- a/services/flysim/crates/flybrain-gb/src/lib.rs +++ b/services/flysim/crates/flybrain-gb/src/lib.rs @@ -20,6 +20,7 @@ pub mod adapter; pub mod compatibility; pub mod emulator; mod ffi; +pub mod image; pub mod macros; mod ordered; pub mod platformer; @@ -32,6 +33,10 @@ pub use adapter::{ adapter_for, adapter_for_with_rom_pin, }; pub use compatibility::Compatibility; +pub use image::{ + CAPTURED, Cartridge, ImageError, ImageReader, MEMORY_IMAGE_CONTENT_TYPE, MEMORY_IMAGE_LEN, + MemoryImage, NOT_CAPTURED, captured, +}; pub use emulator::{ DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, FRAMEBUFFER_LEN, GbError, SCREEN_HEIGHT, SCREEN_WIDTH, buttons, diff --git a/services/flysim/crates/flybrain-gb/tests/rom_memory_image.rs b/services/flysim/crates/flybrain-gb/tests/rom_memory_image.rs new file mode 100644 index 0000000..575568a --- /dev/null +++ b/services/flysim/crates/flybrain-gb/tests/rom_memory_image.rs @@ -0,0 +1,303 @@ +//! The shim's one bulk read, on the real cartridge (MEM-01, `legacy-gameboy-v1` section 8). +//! +//! Gated on `FLY_ROM` like every ROM test here; skips cleanly without it: +//! +//! ```sh +//! . the operator's rom env script # or FLY_ROM=... alone +//! cargo test --release -p flybrain-gb --test rom_memory_image -- --nocapture +//! ``` +//! +//! What section 8 asks the implementing slice to prove, at every boundary of a run that goes from +//! power-on through the intro, the title and the naming screens into the bedroom: +//! +//! 1. **Read-only.** The emulator's exported state is byte-identical before and after the read. +//! 2. **Equal to the single reads.** Every captured byte equals the `fly_gb_read_mem` call for +//! its address and what the per-frame cached read (the one every task and executor use) +//! returns; every uncaptured one is `$FF`. +//! 3. **Nothing moves downstream.** Two emulators in lockstep, one read in bulk at every boundary +//! and one never, produce the same framebuffers, audio and states frame for frame. +//! 4. **Why the register windows are out.** Reading them one byte at a time, as a full image +//! would, does move the exported state (binjgb's lazy PPU/timer/serial catch-up), which is +//! the amendment of 2026-09-29 to section 8. + +use flybrain_gb::adapter::MemoryReader; +use flybrain_gb::{ + CAPTURED, Cartridge, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, ImageReader, + MEMORY_IMAGE_LEN, MemoryImage, NOT_CAPTURED, buttons, captured, +}; + +fn rom() -> Option> { + let path = std::env::var_os("FLY_ROM")?; + match std::fs::read(&path) { + Ok(bytes) => Some(bytes), + Err(error) => panic!("FLY_ROM is set to {path:?} but could not be read: {error}"), + } +} + +fn boot(rom: &[u8]) -> Emulator { + Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .expect("binjgb should accept the ROM") +} + +/// A pad that gets from power-on into the game and walks: A through the intro and the naming +/// screens (a pulse every sixteen frames), then a slow rotation of directions with A between. +fn pad(frame: u32) -> u8 { + if frame < 3_000 { + if frame % 16 < 2 { buttons::A } else { buttons::NONE } + } else { + match (frame / 24) % 6 { + 0 => buttons::DOWN, + 1 => buttons::RIGHT, + 2 => buttons::UP, + 3 => buttons::A, + 4 => buttons::LEFT, + _ => buttons::START, + } + } +} + +const FRAMES: u32 = 4_200; + +#[test] +fn the_bulk_read_is_read_only_and_equals_the_single_reads() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let mut gb = boot(&rom); + let mut image = MemoryImage::zeroed(); + let mut checked = 0u32; + for frame in 0..FRAMES { + gb.set_buttons(pad(frame)); + gb.run_frame().expect("a frame"); + let _ = gb.take_audio_u8(); + + let before = gb.export_state().expect("state"); + gb.read_memory_image_into(&mut image); + let after = gb.export_state().expect("state"); + assert!(before == after, "frame {frame}: the bulk read moved the emulator's state"); + + // Every byte, every 7th frame (a full sweep is 65,536 FFI calls); the WRAM/HRAM windows + // the macros read, every frame. + let full = frame % 7 == 0; + for address in 0..=u16::MAX { + let wanted = full || (0xc000..0xe000).contains(&address) || address >= 0xff80; + if !wanted { + continue; + } + if !captured(address) { + assert_eq!(image.byte(address), NOT_CAPTURED, "frame {frame}: {address:#06x}"); + continue; + } + assert_eq!( + image.byte(address), + gb.read_uncached(address), + "frame {frame}: {address:#06x} differs from the single read" + ); + assert_eq!( + image.byte(address), + gb.read_wram(address), + "frame {frame}: {address:#06x} differs from the cached read" + ); + } + if full { + checked += 1; + } + // The single reads above moved nothing either. + assert!(after == gb.export_state().expect("state"), "frame {frame}: the single reads moved it"); + } + assert!(checked > 500, "{checked} full sweeps"); +} + +#[test] +fn reading_in_bulk_every_frame_changes_nothing_downstream() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let mut read = boot(&rom); + let mut plain = boot(&rom); + let mut image = MemoryImage::zeroed(); + for frame in 0..FRAMES { + read.read_memory_image_into(&mut image); + for gb in [&mut read, &mut plain] { + gb.set_buttons(pad(frame)); + gb.run_frame().expect("a frame"); + } + assert_eq!(read.take_audio_u8(), plain.take_audio_u8(), "frame {frame}: audio"); + assert!(read.framebuffer() == plain.framebuffer(), "frame {frame}: framebuffer"); + assert_eq!(read.ticks(), plain.ticks(), "frame {frame}: ticks"); + if frame % 50 == 0 { + assert!( + read.export_state().unwrap() == plain.export_state().unwrap(), + "frame {frame}: state" + ); + } + } + assert!(read.export_state().unwrap() == plain.export_state().unwrap()); +} + +#[test] +fn an_image_reader_answers_what_the_emulator_answers() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let mut gb = boot(&rom); + let cartridge = Cartridge::verified(&rom, &gb.rom_sha256()).expect("the emulator's own ROM"); + assert_eq!(cartridge.sha256_hex(), gb.cartridge().sha256_hex()); + for frame in 0..3_200 { + gb.set_buttons(pad(frame)); + gb.run_frame().expect("a frame"); + } + let image = gb.read_memory_image(); + assert_eq!(image.as_bytes().len(), MEMORY_IMAGE_LEN); + let mut reader = ImageReader::new(&image, &cartridge); + for &(low, high) in &CAPTURED { + for address in low..=high { + assert_eq!( + reader.read8(address), + MemoryReader::read8(&mut gb, address), + "{address:#06x}" + ); + } + } + // Every bank the cartridge has, and one past it. + let banks = u8::try_from(rom.len().div_ceil(0x4000)).unwrap_or(u8::MAX); + for bank in 0..=banks { + for address in (0u16..0x8000).step_by(97).chain([0x3fff, 0x4000, 0x7fff, 0x8000, 0xc000]) { + assert_eq!( + reader.read_rom(bank, address), + MemoryReader::read_rom(&mut gb, bank, address), + "bank {bank} {address:#06x}" + ); + } + } +} + +/// The amendment's reason, measured: over the same run, reading any of the three register windows +/// one byte at a time -- which is what a full 64 KiB image through `fly_gb_read_mem` would do -- +/// changes the exported state on some boundary, and reading the captured ranges never does. +#[test] +fn the_register_windows_are_the_reads_that_move_the_state() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let mut gb = boot(&rom); + let windows: [(&str, u16, u16); 3] = + [("vram", 0x8000, 0x9fff), ("oam", 0xfe00, 0xfe9f), ("io", 0xff00, 0xff7f)]; + let mut moved = [0u32; 3]; + let mut sampled = 0u32; + for frame in 0..FRAMES { + gb.set_buttons(pad(frame)); + gb.run_frame().expect("a frame"); + if frame % 40 != 0 { + continue; + } + sampled += 1; + for (index, &(_, low, high)) in windows.iter().enumerate() { + // A throwaway copy of this boundary, so each window is measured from the same state. + let state = gb.export_state().expect("state"); + let mut probe = boot(&rom); + probe.import_state(&state).expect("same build"); + for address in low..=high { + let _ = probe.read_uncached(address); + } + if probe.export_state().expect("state") != state { + moved[index] += 1; + } + } + } + eprintln!( + "{sampled} boundaries: {}", + windows + .iter() + .zip(moved) + .map(|((name, ..), n)| format!("{name} moved the state on {n}")) + .collect::>() + .join(", ") + ); + // The PPU's and the timer's catch-ups run on almost every boundary. + assert!(moved[0] > 0, "reading VRAM never moved the state"); + assert!(moved[2] > 0, "reading I/O never moved the state"); +} + +/// The per-boundary cost (MEM-01 deliverable 4), printed for the report rather than asserted: +/// it is wall time on whatever box runs it. What it does assert is only that one read fits +/// comfortably inside a frame (16.74 ms), which a loaded box also meets. +/// +/// - `bulk`: the shim's read into an owned image, which is what the environment pays per boundary; +/// - `copy`: cloning an image (64 KiB `memcpy`), what handing it to a store that copies costs; +/// - `digest`: SHA-256 of the image, which the live artifact may omit; +/// - `single`: the same captured addresses through 57,120 single FFI reads, for comparison. +#[test] +fn the_bulk_read_costs_a_fraction_of_a_frame() { + use std::time::{Duration, Instant}; + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let mut gb = boot(&rom); + for frame in 0..3_200 { + gb.set_buttons(pad(frame)); + gb.run_frame().expect("a frame"); + } + const ROUNDS: usize = 2_000; + let mut bulk = Vec::with_capacity(ROUNDS); + let mut copy = Vec::with_capacity(ROUNDS); + let mut digest = Vec::with_capacity(ROUNDS); + let mut single = Vec::with_capacity(ROUNDS / 20); + let mut image = MemoryImage::zeroed(); + let mut sink = 0u64; + for round in 0..ROUNDS { + gb.set_buttons(pad(3_200 + round as u32)); + gb.run_frame().expect("a frame"); + let start = Instant::now(); + gb.read_memory_image_into(&mut image); + bulk.push(start.elapsed()); + let start = Instant::now(); + let copied = image.clone(); + copy.push(start.elapsed()); + sink += u64::from(copied.byte(0xd35e)); + let start = Instant::now(); + sink += image.sha256_hex().len() as u64; + digest.push(start.elapsed()); + if round % 20 == 0 { + let start = Instant::now(); + for &(low, high) in &CAPTURED { + for address in low..=high { + sink += u64::from(gb.read_uncached(address)); + } + } + single.push(start.elapsed()); + } + } + let stats = |name: &str, samples: &mut Vec| { + samples.sort(); + let at = |q: f64| samples[((samples.len() - 1) as f64 * q) as usize].as_secs_f64() * 1e6; + let mean = samples.iter().sum::().as_secs_f64() * 1e6 / samples.len() as f64; + eprintln!( + "{name:>7}: mean {mean:8.1} us median {:8.1} us p99 {:8.1} us ({} samples)", + at(0.5), + at(0.99), + samples.len() + ); + at(0.5) + }; + let median = stats("bulk", &mut bulk); + stats("copy", &mut copy); + stats("digest", &mut digest); + stats("single", &mut single); + let fps = 59.7275; + eprintln!( + "image {} B/boundary = {:.3} MB/s at {fps} fps; bulk median {:.2}% of a {:.2} ms frame; \ + bulk read throughput {:.0} MB/s (sink {sink})", + MEMORY_IMAGE_LEN, + MEMORY_IMAGE_LEN as f64 * fps / 1e6, + median / 1e3 / (1e3 / fps) * 100.0, + 1e3 / fps, + MEMORY_IMAGE_LEN as f64 / median, + ); + assert!(median < 8_000.0, "a bulk read took {median} us at the median"); +} From a23e587c96a7f0923ff97c946b44e44553bed9e6 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:43:40 +0000 Subject: [PATCH 17/26] flysim: image-backed shadow executor equals the live one (MEM-01) tests/rom_memory_image.rs runs a live arm and a shadow task+executor that reads only per-boundary images and the cartridge, from nine rom-env checkpoints: every MacroState answer, deal, pad, decision, reward, ledger and rollback compared frame by frame, and every shadow read inside the captured ranges. Plus the gameboy-memory-inspection-v1 encoding against the session types. --- .../crates/flysim/tests/rom_memory_image.rs | 690 ++++++++++++++++++ 1 file changed, 690 insertions(+) create mode 100644 services/flysim/crates/flysim/tests/rom_memory_image.rs diff --git a/services/flysim/crates/flysim/tests/rom_memory_image.rs b/services/flysim/crates/flysim/tests/rom_memory_image.rs new file mode 100644 index 0000000..3598152 --- /dev/null +++ b/services/flysim/crates/flysim/tests/rom_memory_image.rs @@ -0,0 +1,690 @@ +//! MEM-01: the macro engine over a boundary's memory image is the macro engine over the live +//! emulator, frame by frame, on the real cartridge. +//! +//! Gated on `FLY_ROM` and the checkpoints `the operator's rom env script` exports; every +//! scenario whose checkpoint is not set is skipped, and without `FLY_ROM` the whole test is: +//! +//! ```sh +//! . the operator's rom env script +//! cargo test --release -p flysim --test rom_memory_image -- --nocapture +//! ``` +//! +//! ## What runs +//! +//! Two copies of the Pokémon task and executor over one cartridge. The **live** arm is the +//! stream's own frame (`LegacyFrame::execute` and `stub_advance`, the stub-readout drivers' path): +//! its `MacroLayer` and `PokemonRedReward` read the emulator through `MemoryReader`, and its mask +//! is the one the emulator is given. The **shadow** arm is what the session framework's +//! `pokered-macros-v1` executor will be (`legacy-gameboy-v1` sections 8 and 10): a second +//! `MacroLayer` and a second `PokemonRedReward`, built by the same constructors, that never see the +//! emulator. They read one `MemoryImage` per boundary, taken with the shim's bulk read and +//! retained from the evaluation of `k-1 -> k` through the decision at `k`, plus the ROM as a +//! `Cartridge`. Both arms get the same decoded channels from the same stub readout (the shipping +//! decoder fed synthetic rates, as `rom_macros_mode.rs` does). +//! +//! ## What is compared, every frame +//! +//! - **The deal and the pad:** bound channels, scene, the feed's palette strip, the running macro, +//! the empty-pad clock, and the rollback's "nearer the objective" signal. +//! - **The decision:** mask, macro events and silence reason from `decide`. +//! - **The evaluation:** reward events, the abandonment `observe` reports, progress, location, +//! snapshot safety and game over; the adapter's whole exported ledger every 30 frames. +//! - **Every `MacroState` answer**, through `PokeState` with the adapter's ledger: scene, player, +//! map size, party, battle, text box, start menu, shop, PC, money, bag, NPCs on and off screen, +//! signs, warps, connections, walkability, counters, pushed/visited tiles around the player, +//! script and text latches, the YES/NO prompt, the A latch, frontier exhaustion, the decoded +//! map grid, the step destination, shop stock, move and item refusals, the exit, map and +//! objective ledgers, the path layer's exits, frontier and targets, the scene's palette set and +//! every macro's precondition. +//! - **Rollbacks:** twice per scenario the ratchet's game-only rollback is replayed on both arms +//! (cancel, import, release buttons, clear transients, re-observe on an image read after the +//! import), and the events and the next frames must agree. +//! +//! And one thing the shadow can check that the live arm cannot: every address it read is inside +//! the image's captured ranges, so the register windows the image leaves out +//! (`legacy-gameboy-v1` section 8, amended 2026-09-29) are never asked for. + +use std::time::{Duration, Instant}; + +use flybrain_core::decoder::PopulationDecoder; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flybrain_core::ordered::NumberMap; +use flybrain_gb::adapter::MemoryReader; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flybrain_gb::pokemon_red::macros::cartridge::{Edge, ExitId, MacroState}; +use flybrain_gb::pokemon_red::macros::palette::{MacroKind, precondition, scene_set}; +use flybrain_gb::pokemon_red::macros::path; +use flybrain_gb::pokemon_red::state::PokeState; +use flybrain_gb::{ + AdapterLedger, Cartridge, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, + GameAdapter, ImageReader, MEMORY_IMAGE_LEN, MemoryImage, captured, +}; +use flysim::config::Config; +use flysim::frame::LegacyFrame; +use flysim::macros::{MacroLayer, macro_layer}; +use flysim::snapshot::MacroMode; + +const MS_PER_FRAME: f64 = 1000.0 / 59.7275; +const FRAMES_PER_SECOND: f64 = 59.7275; +const BURST_MS: f64 = 100.0; +const SEED: u32 = 20_260_916; +const HOT: f64 = 16.0; +const REST: f64 = 10.0; +const HOLDS_PER_SLOT: usize = 3; + +/// Frames per scenario; `FLY_MEMIMAGE_FRAMES` overrides. +const DEFAULT_FRAMES: u32 = 3_000; + +/// The scenarios: the checkpoint's `rom-env.sh` variable, what it is there to cover, and a +/// channel the stub leans on every other burst. A scenario that leans on `macro_menu` also has +/// the harness open the start menu itself on an overworld boundary every 250 frames (the first idle one after) (START held +/// for three frames on the emulator, then twenty idle, both arms re-observing the image after): +/// the palette's own MENU press does not reliably leave the menu up long enough to be seen. +const SCENARIOS: &[(&str, &str, Option<&str>)] = &[ + ("FLY_CENTER_CHECKPOINT", "centre", None), + ("FLY_MART_CHECKPOINT", "mart", None), + ("FLY_CATCH_CHECKPOINT", "forest battles", None), + ("FLY_GYM_CHECKPOINT", "gym", None), + ("FLY_DOOR_CHECKPOINT", "overworld door", None), + ("FLY_BUILDING_CHECKPOINT", "building", None), + ("FLY_MT_MOON_CHECKPOINT", "cave", None), + ("FLY_ROW62_MART_CHECKPOINT", "mart 2", None), + ("FLY_PEWTER_CHECKPOINT", "start menu", Some("macro_menu")), +]; + +fn rates(hot: Option<&str>) -> NumberMap { + let mut rates = NumberMap::new(); + for channel in flybrain_gb::macro_channels("pokemon-red") { + rates.set(channel, REST); + } + for bucket in 0..8 { + rates.set(&format!("command_{bucket}"), REST); + } + if let Some(channel) = hot { + rates.set(channel, HOT); + } + rates +} + +fn rom() -> Option> { + let path = std::env::var_os("FLY_ROM")?; + match std::fs::read(&path) { + Ok(bytes) => Some(bytes), + Err(error) => panic!("FLY_ROM is set to {path:?} but could not be read: {error}"), + } +} + +/// The shadow's reader: the image and the cartridge, counting what is asked of it. +struct Recording<'a> { + inner: ImageReader<'a>, + seen: &'a mut Vec, + uncaptured: &'a mut u64, +} + +impl MemoryReader for Recording<'_> { + fn read8(&mut self, address: u16) -> u8 { + let index = usize::from(address); + self.seen[index >> 6] |= 1 << (index & 63); + if !captured(address) { + *self.uncaptured += 1; + } + self.inner.read8(address) + } + + fn read_rom(&mut self, bank: u8, address: u16) -> Option { + self.inner.read_rom(bank, address) + } +} + +/// Every `MacroState` answer this frame, as text, in a fixed order. +fn sweep(state: &mut dyn MacroState) -> Vec { + let mut out = Vec::with_capacity(512); + macro_rules! q { + ($label:expr, $value:expr) => { + out.push(format!("{}={:?}", $label, $value)) + }; + } + let scene = state.scene(); + q!("scene", scene); + let player = state.player(); + q!("player", player); + q!("map_size", state.map_size()); + q!("party", state.party()); + q!("battle", state.battle()); + q!("text_box", state.text_box()); + q!("start_menu", state.start_menu()); + q!("shop", state.shop()); + q!("pc", state.pc()); + q!("money", state.money()); + q!("bag", state.bag()); + q!("npcs", state.npcs()); + q!("offscreen_npcs", state.offscreen_npcs()); + q!("signs", state.signs()); + let warps = state.warps(); + q!("warps", warps); + q!("connections", state.connections()); + q!("scripted", state.scripted()); + q!("text_open", state.text_open()); + q!("yes_no", state.yes_no_prompt()); + q!("a_latched", state.a_latched()); + q!("frontier_exhausted", state.frontier_exhausted()); + // The grid can be a few thousand tiles; its equality is what matters, so compare it whole + // through its Debug text but keep only a digest of it. + let grid = state.map_grid().map(|grid| { + use sha2::Digest; + let text = format!("{grid:?}"); + format!("{:x}", sha2::Sha256::digest(text.as_bytes())) + }); + q!("map_grid", grid); + q!("stepping_onto", state.stepping_onto()); + q!("shop_stock", state.shop_stock()); + q!("objective", state.objective()); + if let Some(player) = player { + for y in player.y.saturating_sub(6)..=player.y.saturating_add(6) { + for x in player.x.saturating_sub(6)..=player.x.saturating_add(7) { + out.push(format!( + "tile({x},{y})={:?}/{}/{}/{}", + state.walkable(x, y), + state.counter_tile(x, y), + state.pushed_tile(x, y), + state.tile_visited(x, y), + )); + } + } + } + for index in 0..u8::try_from(warps.len()).unwrap_or(u8::MAX) { + q!(format!("exit_visited(warp {index})"), state.exit_visited(ExitId::Warp(index))); + } + for edge in [Edge::North, Edge::South, Edge::East, Edge::West] { + q!(format!("exit_visited({edge:?})"), state.exit_visited(ExitId::Edge(edge))); + } + let maps: Vec = (0..=u8::MAX).filter(|&map| state.map_visited(map)).collect(); + q!("maps_visited", maps); + let moves: Vec = (1..=165).filter(|&id| state.move_without_effect(id)).collect(); + q!("moves_without_effect", moves); + let items: Vec = (1..=u8::MAX).filter(|&id| state.item_refused(id)).collect(); + q!("items_refused", items); + q!("exits", path::exits(state)); + q!("frontier", path::frontier(state)); + q!("interactables", path::interactables(state)); + q!("interactable_targets", path::interactable_targets(state)); + q!("person_targets", path::person_targets(state)); + q!("offscreen_person_targets", path::offscreen_person_targets(state)); + q!("scene_set", scene_set(scene, state)); + let preconditions: Vec<(MacroKind, bool)> = + MacroKind::ALL.iter().map(|&kind| (kind, precondition(kind, state))).collect(); + q!("preconditions", preconditions); + out +} + +/// What one scenario covered, for the report. +#[derive(Default)] +struct Coverage { + frames: u64, + swept: u64, + answers: u64, + scenes: std::collections::BTreeMap<&'static str, u64>, + maps: std::collections::BTreeSet, + started: u64, + rewards: u64, + rollbacks: u64, + menus_opened: u64, + distinct_addresses: u64, + uncaptured: u64, + read_time: Duration, + reads: u64, + digest_time: Duration, +} + +/// Mismatches are collected, not panicked on, so a failure reports its first few frames. +struct Diff { + label: String, + first: Vec, + count: u64, +} + +impl Diff { + fn check(&mut self, frame: u64, what: &str, live: String, shadow: String) { + if live != shadow { + self.count += 1; + if self.first.len() < 8 { + self.first.push(format!( + "{} frame {frame} {what}:\n live {live}\n shadow {shadow}", + self.label + )); + } + } + } +} + +/// The shim's bulk read, timed. +fn read_image(gb: &Emulator, image: &mut MemoryImage, cov: &mut Coverage) { + let start = Instant::now(); + gb.read_memory_image_into(image); + cov.read_time += start.elapsed(); + cov.reads += 1; +} + +fn run( + rom: &[u8], + label: &str, + checkpoint: &flysim::store::Checkpoint, + frames: u32, + lean: Option<&str>, +) -> (Coverage, Diff) { + let mut gb = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .expect("binjgb should accept the cartridge"); + gb.import_state(&checkpoint.runtime.emulator).expect("the checkpoint's emulator state"); + // The executor's ROM asset: refused unless it is the environment's content. + let cartridge = Cartridge::verified(rom, &gb.rom_sha256()).expect("the environment's ROM"); + let mut live_adapter = PokemonRedReward::new(); + let mut shadow_adapter = PokemonRedReward::new(); + live_adapter.import_state(&checkpoint.runtime.reward).expect("reward ledger"); + shadow_adapter.import_state(&checkpoint.runtime.reward).expect("reward ledger"); + + let channels = flybrain_gb::macro_channels("pokemon-red"); + let preset = gameboy_decoder_config_with_macros(&channels); + let hold_ms = preset.macros.as_ref().expect("a macro group").hold_ms; + let mut decoder = PopulationDecoder::new(preset).expect("the preset is well formed"); + decoder.calibrate(&rates(None)); + let mut config = Config::default(); + config.loop_.game = "pokemon-red".to_string(); + config.macros.mode = MacroMode::Macros; + config.validate().expect("pokemon-red has a palette"); + let mut live: MacroLayer = macro_layer(&config, hold_ms, SEED).expect("a layer"); + let mut shadow: MacroLayer = macro_layer(&config, hold_ms, SEED).expect("a layer"); + + let mut cov = Coverage::default(); + let mut diff = Diff { label: label.to_string(), first: Vec::new(), count: 0 }; + let mut seen = vec![0u64; MEMORY_IMAGE_LEN / 64]; + let mut uncaptured = 0u64; + + // O[0]: the boundary's image, retained until the next transition is evaluated. + let mut image = MemoryImage::zeroed(); + read_image(&gb, &mut image, &mut cov); + + let mut ms = 0.0; + { + let a = live.observe(&mut gb, &AdapterLedger(&live_adapter), ms); + let mut reader = Recording { + inner: ImageReader::new(&image, &cartridge), + seen: &mut seen, + uncaptured: &mut uncaptured, + }; + let b = shadow.observe(&mut reader, &AdapterLedger(&shadow_adapter), ms); + diff.check(0, "initial observe", format!("{a:?}"), format!("{b:?}")); + } + + let mut frame = LegacyFrame::new(); + let mut next_burst = ms; + let mut burst = 0usize; + // The ratchet's slot: a state taken early, restored twice. + let mut slot: Option> = None; + let rollback_at = [frames / 3, 2 * frames / 3]; + let mut menu_due = false; + + for k in 0..u64::from(frames) { + // --- The deal and the pad, at boundary k. + let bound = live.bound_channels(); + diff.check(k, "bound", format!("{bound:?}"), format!("{:?}", shadow.bound_channels())); + diff.check(k, "scene", live.scene_name().into(), shadow.scene_name().into()); + diff.check( + k, + "palette", + format!("{:?}", live.feed_palette()), + format!("{:?}", shadow.feed_palette()), + ); + diff.check(k, "running", format!("{:?}", live.running()), format!("{:?}", shadow.running())); + diff.check( + k, + "pad_empty_ms", + format!("{:?}", live.pad_empty_ms(ms)), + format!("{:?}", shadow.pad_empty_ms(ms)), + ); + diff.check( + k, + "nearer", + format!("{:?}", live.nearer_the_objective()), + format!("{:?}", shadow.nearer_the_objective()), + ); + *cov.scenes.entry(live.scene_name()).or_default() += 1; + if let Some(map) = live_adapter.map_id() { + cov.maps.insert(map); + } + + // --- Every MacroState answer over O[k], both ways. + { + let live_answers = { + let ledger = AdapterLedger(&live_adapter); + let mut state = PokeState::with_ledger(&mut gb, &ledger); + sweep(&mut state) + }; + let shadow_answers = { + let ledger = AdapterLedger(&shadow_adapter); + let mut reader = Recording { + inner: ImageReader::new(&image, &cartridge), + seen: &mut seen, + uncaptured: &mut uncaptured, + }; + let mut state = PokeState::with_ledger(&mut reader, &ledger); + sweep(&mut state) + }; + cov.swept += 1; + cov.answers += live_answers.len() as u64; + if live_answers != shadow_answers { + if live_answers.len() != shadow_answers.len() { + diff.check( + k, + "answer count", + live_answers.len().to_string(), + shadow_answers.len().to_string(), + ); + } + for (a, b) in live_answers.iter().zip(&shadow_answers) { + diff.check(k, "MacroState", a.clone(), b.clone()); + } + } + } + + // --- The stub readout, then Phase B on both arms. + let bursting = ms < next_burst + BURST_MS; + let rotation = channels[(burst / HOLDS_PER_SLOT) % channels.len()]; + let hot = bursting.then_some(match lean { + Some(channel) if burst.is_multiple_of(2) => channel, + _ => rotation, + }); + if ms >= next_burst + hold_ms { + next_burst = ms; + burst += 1; + } + let active = decoder.decode_bound(&rates(hot), ms, false, None, Some(&bound)); + let executed = frame.execute(Some(&mut live), &active, 0, ms, &mut gb, &live_adapter); + let decided = { + let mut reader = Recording { + inner: ImageReader::new(&image, &cartridge), + seen: &mut seen, + uncaptured: &mut uncaptured, + }; + shadow.decide(&active, 0, ms, &mut reader, &AdapterLedger(&shadow_adapter)) + }; + diff.check(k, "mask", executed.mask.to_string(), decided.mask.to_string()); + diff.check(k, "events", format!("{:?}", executed.events), format!("{:?}", decided.events)); + diff.check( + k, + "silence", + format!("{:?}", executed.silence), + format!("{:?}", decided.silence), + ); + cov.started += executed.events.iter().filter(|event| event.outcome.is_none()).count() as u64; + + // --- The environment runs the live mask; O[k+1] is read once, in bulk. + ms += MS_PER_FRAME; + let evaluated = frame + .stub_advance(Some(&mut live), &mut gb, &mut live_adapter, ms) + .expect("a frame"); + read_image(&gb, &mut image, &mut cov); + if k % 64 == 0 { + let start = Instant::now(); + let _ = image.sha256_hex(); + cov.digest_time += start.elapsed(); + } + + // --- Phase C on the shadow, over the image alone. + let (rewards, abandoned) = { + let mut reader = Recording { + inner: ImageReader::new(&image, &cartridge), + seen: &mut seen, + uncaptured: &mut uncaptured, + }; + let rewards = shadow_adapter.sample(&mut reader, ms); + let abandoned = shadow.observe(&mut reader, &AdapterLedger(&shadow_adapter), ms); + (rewards, abandoned) + }; + cov.rewards += evaluated.rewards.len() as u64; + diff.check(k, "rewards", format!("{:?}", evaluated.rewards), format!("{rewards:?}")); + diff.check(k, "abandoned", format!("{:?}", evaluated.abandoned), format!("{abandoned:?}")); + diff.check( + k, + "progress", + format!("{:?}", evaluated.progress), + format!("{:?}", shadow_adapter.progress()), + ); + diff.check( + k, + "location", + format!("{:?}", live_adapter.location()), + format!("{:?}", shadow_adapter.location()), + ); + diff.check( + k, + "safe/over", + format!("{}/{}", live_adapter.safe_for_snapshot(), live_adapter.game_over()), + format!("{}/{}", shadow_adapter.safe_for_snapshot(), shadow_adapter.game_over()), + ); + if k % 30 == 0 { + diff.check( + k, + "adapter ledger", + live_adapter.export_state().to_string(), + shadow_adapter.export_state().to_string(), + ); + } + + // --- The start-menu scenario: the harness opens the menu, both arms observe the result. + if lean == Some("macro_menu") && k % 250 == 125 { + menu_due = true; + } + if menu_due + && live.scene_name() == "overworld" + && live.running().is_none() + { + for (mask, frames) in [(flybrain_gb::buttons::START, 3), (0, 20)] { + gb.set_buttons(mask); + for _ in 0..frames { + gb.run_frame().expect("a frame"); + } + } + let _ = gb.take_audio_u8(); + let a = live.observe(&mut gb, &AdapterLedger(&live_adapter), ms); + read_image(&gb, &mut image, &mut cov); + let b = { + let mut reader = Recording { + inner: ImageReader::new(&image, &cartridge), + seen: &mut seen, + uncaptured: &mut uncaptured, + }; + shadow.observe(&mut reader, &AdapterLedger(&shadow_adapter), ms) + }; + diff.check(k, "menu opened", format!("{a:?}"), format!("{b:?}")); + menu_due = false; + cov.menus_opened += 1; + } + + // --- The ratchet's slot and its rollback, on both arms. + if k == 100 { + slot = Some(gb.export_state().expect("state")); + } + if rollback_at.contains(&(k as u32)) + && let Some(state) = slot.as_ref() + { + let a = { + let mut events = live.cancel(ms); + gb.import_state(state).expect("the slot"); + gb.set_buttons(0); + live_adapter.clear_transient(); + events.extend(live.observe(&mut gb, &AdapterLedger(&live_adapter), ms)); + events + }; + // The environment's RestoreSlot returns "a memory image read after the import". + read_image(&gb, &mut image, &mut cov); + let b = { + let mut events = shadow.cancel(ms); + shadow_adapter.clear_transient(); + let mut reader = Recording { + inner: ImageReader::new(&image, &cartridge), + seen: &mut seen, + uncaptured: &mut uncaptured, + }; + events.extend(shadow.observe(&mut reader, &AdapterLedger(&shadow_adapter), ms)); + events + }; + diff.check(k, "rollback", format!("{a:?}"), format!("{b:?}")); + cov.rollbacks += 1; + } + cov.frames += 1; + } + diff.check( + u64::from(frames), + "final adapter ledger", + live_adapter.export_state().to_string(), + shadow_adapter.export_state().to_string(), + ); + diff.check( + u64::from(frames), + "counts", + format!("{:?}", live.counts()), + format!("{:?}", shadow.counts()), + ); + cov.distinct_addresses = seen.iter().map(|word| u64::from(word.count_ones())).sum(); + cov.uncaptured = uncaptured; + (cov, diff) +} + +#[test] +fn the_macros_over_the_image_are_the_macros_over_the_emulator() { + let Some(rom) = rom() else { + eprintln!("skipped: FLY_ROM is not set"); + return; + }; + let frames = std::env::var("FLY_MEMIMAGE_FRAMES") + .ok() + .and_then(|value| value.parse().ok()) + .unwrap_or(DEFAULT_FRAMES); + let mut all_scenes = std::collections::BTreeSet::new(); + let mut all_maps = std::collections::BTreeSet::new(); + let mut failures = Vec::new(); + let mut ran = 0; + let (mut read_time, mut reads, mut total_frames, mut total_answers) = + (Duration::ZERO, 0u64, 0u64, 0u64); + for &(variable, label, lean) in SCENARIOS { + let Some(path) = std::env::var_os(variable) else { + eprintln!("{label}: skipped, {variable} is not set"); + continue; + }; + let checkpoint = flysim::store::load(std::path::Path::new(&path)) + .expect("the checkpoint should be a FLYSIM01 envelope"); + let started = Instant::now(); + let (cov, diff) = run(&rom, label, &checkpoint, frames, lean); + ran += 1; + eprintln!( + "{label} ({variable}): {} frames, {} sweeps / {} answers, {} macros started, {} rewards, \ + {} rollbacks, {} menus opened, {} distinct addresses read ({} uncaptured reads), maps {:x?}, scenes {:?}; \ + bulk read {:.1} us mean; digest {:.1} us mean; {} mismatches; {:.0} s", + cov.frames, + cov.swept, + cov.answers, + cov.started, + cov.rewards, + cov.rollbacks, + cov.menus_opened, + cov.distinct_addresses, + cov.uncaptured, + cov.maps, + cov.scenes, + cov.read_time.as_secs_f64() * 1e6 / cov.reads.max(1) as f64, + cov.digest_time.as_secs_f64() * 1e6 / cov.frames.div_ceil(64).max(1) as f64, + diff.count, + started.elapsed().as_secs_f64(), + ); + for line in &diff.first { + eprintln!("{line}"); + } + if diff.count > 0 { + failures.push(format!("{label}: {} mismatches", diff.count)); + } + if cov.uncaptured > 0 { + failures.push(format!("{label}: {} reads outside the captured ranges", cov.uncaptured)); + } + all_scenes.extend(cov.scenes.keys().copied()); + all_maps.extend(cov.maps.iter().copied()); + read_time += cov.read_time; + reads += cov.reads; + total_frames += cov.frames; + total_answers += cov.answers; + } + if ran == 0 { + eprintln!("skipped: no scenario checkpoint is set (source rom-env.sh)"); + return; + } + let mean = read_time.as_secs_f64() / reads.max(1) as f64; + eprintln!( + "total: {ran} scenarios, {total_frames} frames, {total_answers} MacroState answers equal; \ + scenes {all_scenes:?}; bulk read {:.1} us mean per boundary = {:.2}% of a {:.2} ms frame; \ + {:.2} MB/s of image at {FRAMES_PER_SECOND} fps", + mean * 1e6, + mean * 1e3 / MS_PER_FRAME * 100.0, + MS_PER_FRAME, + MEMORY_IMAGE_LEN as f64 * FRAMES_PER_SECOND / 1e6, + ); + assert!(failures.is_empty(), "{failures:#?}"); + // The coverage the slice promised, when the full checkpoint set is present. + if ran == SCENARIOS.len() { + for scene in ["overworld", "battle", "menu", "dialog", "shop"] { + assert!(all_scenes.contains(scene), "no {scene} frame in {all_scenes:?}"); + } + let centres = [0x29u32, 0x3a, 0x40, 0x44]; + assert!( + centres.iter().any(|map| all_maps.contains(map)), + "no Pokemon Center in {all_maps:x?}" + ); + } +} + +/// The inspection artifact (`gameboy-memory-inspection-v1`, `legacy-gameboy-v1` section 8): an +/// image encodes as exactly its 65,536 bytes in address order, `application/octet-stream`, with +/// an optional SHA-256 digest in the bus `Digest` encoding, and its `romDigest` is the +/// cartridge's. No ROM needed: a synthetic image and cartridge carry the same shapes. +#[test] +fn an_image_encodes_as_the_memory_inspection_artifact() { + use fly_session_types::gameboy::{MEMORY_IMAGE_BYTES, MemoryInspection}; + use fly_session_types::workers::AssetRef; + use fly_session_types::ArtifactRef; + use flybrain_gb::MEMORY_IMAGE_CONTENT_TYPE; + + assert_eq!(MEMORY_IMAGE_LEN as u64, MEMORY_IMAGE_BYTES); + let bytes: Vec = (0..MEMORY_IMAGE_LEN).map(|i| ((i * 31) >> 3) as u8).collect(); + let image = MemoryImage::from_bytes(&bytes).expect("a full image"); + let rom: Vec = (0..0x8000).map(|i| (i % 251) as u8).collect(); + let cartridge = Cartridge::new(&rom); + + let memory = ArtifactRef { + store_id: "session".into(), + artifact_id: "inspection-0".into(), + generation: 1, + byte_length: image.as_bytes().len() as u64, + content_type: MEMORY_IMAGE_CONTENT_TYPE.into(), + digest: Some(image.sha256_hex()), + }; + let inspection = MemoryInspection { memory, rom_digest: cartridge.sha256_hex() }; + let typed = inspection.to_typed(); + let back = MemoryInspection::from_typed(&typed).expect("the schema accepts it"); + assert_eq!(back, inspection); + let asset = AssetRef { + id: "pokemon-red".into(), + digest: cartridge.sha256_hex(), + byte_length: rom.len() as u64, + format: "gb-rom".into(), + }; + back.validate_against(&cartridge.sha256_hex(), &asset).expect("one ROM on all three sides"); + // The bytes the artifact carries decode back to the same image. + assert_eq!(MemoryImage::from_bytes(image.as_bytes()).expect("round trip"), image); + + // A truncated image is refused by both sides of the seam. + let mut short = inspection.clone(); + short.memory.byte_length = MEMORY_IMAGE_BYTES - 1; + assert!(MemoryInspection::from_typed(&short.to_typed()).is_err()); + assert!(MemoryImage::from_bytes(&bytes[1..]).is_err()); + // Another ROM is refused. + let other = Cartridge::new(&rom[1..]); + assert!(back.validate_against(&other.sha256_hex(), &asset).is_err()); +} From f666b404ddbb58841c56e80c05ef8f9a4623f1c5 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:43:40 +0000 Subject: [PATCH 18/26] docs: MEM-01 status and the section 8 memory-image amendment (2026-09-29) --- .../session-framework/implementation.md | 37 +++++++++++++++++++ .../session-framework/legacy-gameboy-v1.md | 35 +++++++++++++++++- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index a11fa4c..2a16425 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -220,6 +220,43 @@ adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash its own identity and public adapter selection. No console-specific state enters generic session types. ROM-backed checks are optional explicit jobs, not required downloads. +### MEM-01 — The boundary memory image (port slice) + +**2026-09-29: built** on `port/mem-01` off v0.6.5 and awaiting review. It changes no live +behaviour: nothing in `flysim` calls the new read, and the compatibility string is unchanged. It +delivers the piece of ENV-01 above that reads "add the one read-only bulk memory read to the shim +and prove it mutates nothing", together with the executor-side reader that TASK-01 and the +CUT-01 shadow need. + +- **Shim.** `fly_gb_read_memory_image(gb, out, 65536)` fills the buffer in address order. + `Emulator::read_memory_image{,_into}` wraps it. There is no new write path. + [legacy-gameboy-v1](legacy-gameboy-v1.md) section 8 carries a dated amendment (2026-09-29): + VRAM, OAM and I/O are not captured and read `$FF`. binjgb's read of those windows runs a + catch-up that moves the exported state. Every memory byte is captured exactly. +- **Executor reader.** `flybrain_gb::{MemoryImage, Cartridge, ImageReader}`. `ImageReader` + implements `MemoryReader`. The palette, `MacroLayer`, `PokeState` and `PokemonRedReward` run + over it unchanged; this is the same code, not a port. The emulator's own bank reads now go + through the same `Cartridge::read_bank`. +- **Proof.** flybrain-gb `tests/rom_memory_image.rs` (ROM) checks three things. The exported + state is byte-identical before and after each bulk read over 4,200 boot frames. The image + equals the single and cached reads. Reading every frame leaves framebuffers, audio and state + frame-for-frame equal to a run that is never read. flysim `tests/rom_memory_image.rs` runs a + live arm and an image-only shadow arm (task and executor) from nine rom-env checkpoints for + 3,000 frames each: 27,000 frames with about 5.5 M `MacroState` answers, deals, pads, + decisions, rewards, ledgers and rollbacks. It finds 0 mismatches and 0 reads outside the + captured ranges. +- **Cost.** A bulk read has a median of 0.31 ms per boundary, 1.9 % of a 16.74 ms frame or + about 209 MB/s of reading. This is the same cost as the 57,120 single reads it replaces. The + image is 3.91 MB/s at 59.7275 fps. A 64 KiB copy has a median of 5 µs, and the optional + SHA-256 digest a median of 0.36 ms. Means and p99 values are dominated by preemption: the + measurement ran on the shared 4-core build box at load 16. + +**For ENV-01:** after `run_frame` and after a slot import, publish +`read_memory_image` as the `gameboy-memory-inspection-v1` artifact (`MEMORY_IMAGE_CONTENT_TYPE`, +65,536 bytes, digest optional, `romDigest` = `Cartridge::sha256_hex`). **For TASK-01:** build +the executor over `ImageReader::new(&O[k], &cartridge)` in Phase B and over O[k+1] in Phase C, +retaining O[k] until then. The `Cartridge` comes from `Cartridge::verified(rom, contentDigest)`. + ### STATE-01 — Coherent all-participant checkpoint/recovery **Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01. diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 163934e..4f0a6b1 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -168,7 +168,8 @@ interface GameboyMemoryInspection { } ``` -- **The image.** Byte *i* is what `fly_gb_read_mem(i)` returns at this boundary, which is +- **The image.** (Amended 2026-09-29, below: the register windows are not captured.) Byte *i* + is what `fly_gb_read_mem(i)` returns at this boundary, which is what every task and executor read in the legacy loop sees through the per-frame read cache. It is a listed bus attachment, content type `application/octet-stream`. Its digest is optional, because it is a transient live artifact ([state-media-v1](state-media-v1.md) section 1). At @@ -186,6 +187,38 @@ interface GameboyMemoryInspection { - **Retention.** The coordinator keeps O[k]'s image until transition k→k+1 has been evaluated. The executor reads it in Phase B, and the task reads old and new images in Phase C. +**Amendment, 2026-09-29 (MEM-01).** The image captures the address space's *memory*, not its +*registers*. The two proofs this section demands contradicted each other for three windows: a +read of VRAM (`$8000-$9FFF`), OAM (`$FE00-$FE9F`) or I/O with the APU and wave RAM +(`$FF00-$FF7F`) goes through binjgb's lazy catch-up (`ppu_synchronize`, `timer_synchronize`, +`serial_synchronize`, `intr_synchronize`, `apu_synchronize`) before it answers. The catch-up +rewrites the subsystem's sync bookkeeping, so the exported state changes. On a boot run it +changed on 104 to 105 of 105 sampled boundaries for each window. A full 65,536-byte read +through `emulator_read_mem` is therefore not read-only by the state-comparison test. The amended +rule: + +- **Captured**: `$0000-$7FFF` (ROM as mapped), `$A000-$FDFF` (cartridge RAM, work RAM and its + echo), `$FEA0-$FEFF` (the unused block) and `$FF80-$FFFF` (high RAM and `IE`). Byte *i* is + exactly what `fly_gb_read_mem(i)` returns at this boundary. binjgb reads each of these + straight out of an array, with no catch-up. +- **Not captured**: the three register windows above. They read `$FF` (binjgb's + `INVALID_READ_BYTE`), and the shim does not call `emulator_read_mem` for them. +- **Unchanged**: the artifact is still 65,536 bytes in address order, + `application/octet-stream`, with an optional digest. `gameboy-memory-inspection-v1` is + therefore unchanged, and so are its schema digest and the contract digest. +- **Why no task or executor loses anything**: none of them reads a register window. The Pokémon + adapter, scene detector and macro engine read WRAM, HRAM and ROM only. MEM-01's equivalence + harness (flysim `tests/rom_memory_image.rs`) counts every address the image-backed arm reads + over 27,000 frames from nine checkpoints and finds no read outside the captured ranges. A future + task that needs a register must amend this section first. A register cannot be captured + read-only through this shim. + +The shim function is `fly_gb_read_memory_image(gb, out, 65536)`, and in Rust it is +`Emulator::read_memory_image{,_into}`. The executor's reader is `flybrain_gb::ImageReader`, +which pairs a `MemoryImage` with a `Cartridge`. `Cartridge::verified` refuses a ROM whose SHA-256 +is not the environment's `contentDigest`. The emulator answers its own bank reads through the same +`Cartridge::read_bank`. + ## 9. Environment - **Initialize.** The backend configuration declares a setup scaffold of **one frame with no From 0d6bce8838ee61fe370cfe1822bd5144aad4ae9c Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 13:43:46 +0000 Subject: [PATCH 19/26] flybrain-gb README: the image module --- services/flysim/crates/flybrain-gb/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/services/flysim/crates/flybrain-gb/README.md b/services/flysim/crates/flybrain-gb/README.md index fa9f917..07b8555 100644 --- a/services/flysim/crates/flybrain-gb/README.md +++ b/services/flysim/crates/flybrain-gb/README.md @@ -15,6 +15,7 @@ ROM bytes -> Emulator::run_frame -> RGBA frame + PCM + WRAM | Module | What it is | | --- | --- | | `emulator` | Safe wrapper over binjgb: frames, framebuffer, buttons, WRAM, audio, save states, ROM hash | +| `image` | The boundary memory image (`read_memory_image`), the `Cartridge` and `ImageReader`, which runs the macros and adapters over an image instead of a live emulator (MEM-01) | | `adapter` | `GameAdapter`, `RewardEvent`, `ProgressSnapshot`, `MemoryReader`, `adapter_for` | | `pokemon_red` | The `pokered-unique8-v7` reward adapter, its catalog and its generated symbol table | | `platformer` | The `sml-progress-v1` Super Mario Land adapter, its catalog and its RAM map | From 32631e2d02413d1d186d0b14b08579f10d66a994 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 15:31:13 +0000 Subject: [PATCH 20/26] flysim-store: the FLYSIM01 store and the sugar journal in one crate; journal boot header, rotation and reset clearing store.rs and journal.rs move unchanged from flysim into the new flysim-store crate, which flysim re-exports, so the session runtime can write and read the same store (STATE-02). The journal gains a per-process boot header, rotation at 4 MiB with three kept files, and clear(), which flysim --reset-to-milestone now calls after copying the stores aside. --- services/flysim/Cargo.lock | 14 + services/flysim/Cargo.toml | 1 + .../flysim/crates/flysim-store/Cargo.toml | 27 + .../flysim/crates/flysim-store/src/journal.rs | 515 ++++++++++++++ .../flysim/crates/flysim-store/src/lib.rs | 12 + .../flysim/crates/flysim-store/src/store.rs | 645 ++++++++++++++++++ services/flysim/crates/flysim/Cargo.toml | 2 + services/flysim/crates/flysim/src/journal.rs | 176 +---- services/flysim/crates/flysim/src/reset.rs | 29 + services/flysim/crates/flysim/src/simloop.rs | 16 + services/flysim/crates/flysim/src/store.rs | 645 +----------------- 11 files changed, 1268 insertions(+), 814 deletions(-) create mode 100644 services/flysim/crates/flysim-store/Cargo.toml create mode 100644 services/flysim/crates/flysim-store/src/journal.rs create mode 100644 services/flysim/crates/flysim-store/src/lib.rs create mode 100644 services/flysim/crates/flysim-store/src/store.rs diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index d87a04a..d356eee 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -508,6 +508,7 @@ dependencies = [ "flybrain-core", "flybrain-gb", "flybus", + "flysim-store", "futures-util", "jsonschema", "serde", @@ -523,6 +524,19 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "flysim-store" +version = "0.1.1" +dependencies = [ + "anyhow", + "flybrain-core", + "flybrain-gb", + "serde", + "serde_json", + "tempfile", + "tracing", +] + [[package]] name = "foldhash" version = "0.2.0" diff --git a/services/flysim/Cargo.toml b/services/flysim/Cargo.toml index 2def2d3..2673363 100644 --- a/services/flysim/Cargo.toml +++ b/services/flysim/Cargo.toml @@ -8,6 +8,7 @@ members = [ "crates/flybrain-gb", "crates/flybus", "crates/flysim", + "crates/flysim-store", ] [workspace.package] diff --git a/services/flysim/crates/flysim-store/Cargo.toml b/services/flysim/crates/flysim-store/Cargo.toml new file mode 100644 index 0000000..aaef1aa --- /dev/null +++ b/services/flysim/crates/flysim-store/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "flysim-store" +version.workspace = true +edition = "2024" +rust-version.workspace = true +license.workspace = true +publish = false +description = "The FLYSIM01 checkpoint store (envelope, generations, milestone archives) and the sugar journal, shared by flysim and the session runtime." + +[lib] +name = "flysim_store" +path = "src/lib.rs" + +# STATE-02: `flysim` (the legacy loop) and `fly-session` (the session runtime) write and read +# the same store, so the code lives here once and both link it. No dependency on either of +# them, and nothing async: the writer threads belong to the callers. +[dependencies] +flybrain-core = { path = "../flybrain-core" } +flybrain-gb = { path = "../flybrain-gb" } + +anyhow = "1.0" +serde = { workspace = true } +serde_json = { workspace = true } +tracing = "0.1" + +[dev-dependencies] +tempfile = "3" diff --git a/services/flysim/crates/flysim-store/src/journal.rs b/services/flysim/crates/flysim-store/src/journal.rs new file mode 100644 index 0000000..f487b66 --- /dev/null +++ b/services/flysim/crates/flysim-store/src/journal.rs @@ -0,0 +1,515 @@ +//! The sugar journal: every admitted audience input, stamped with the frame it was applied before. +//! +//! `sugar-journal.jsonl` in `[paths] hot_dir`, one JSON object per line, append-only. It is not +//! part of a checkpoint and nothing reads it back into the fly: it is the record a shadow run +//! (the session framework's CUT-01, `docs/design/session-framework/legacy-gameboy-v1.md` section +//! 15) replays audience input from. The legacy loop applies an admitted sugar at once, in the +//! command drain at the top of a frame, so an input is fully placed by the transition it precedes: +//! +//! ```json +//! {"frame":"6465126","brainMs":108246189,"kind":"sugar","durationMs":400,"by":"viewer","source":"twitch","eventId":81234,"wallMs":1790000000000} +//! ``` +//! +//! - `frame` is the frame counter when the input was applied, which is the `step` of the next +//! transition in the frame trace (`crate::trace`): replay applies it before that transition's +//! ticks. A restore carries the frame counter, so stamps continue across restarts. +//! - `kind` is `sugar` (a `reward-pulse` stimulation of `durationMs`, after the admission rules +//! and the clamp) or `reward` (an operator's `POST /reward`, one reinforcement of `value`). +//! - `brainMs` cross-checks the stamp; `eventId` joins the event log; `wallMs` is for people. +//! +//! Refused requests are not journalled: admission is wall-clock policy, and a replay applies what +//! was admitted. A write that fails is a warning, never a refusal: the input has already reached +//! the fly. +//! +//! **Boot header, rotation and reset (STATE-02, before SHADOW-01).** Three things a replay needs +//! that the first version left open: +//! +//! - *Boot header.* Every process writes one header line when it starts, before any input: +//! +//! ```json +//! {"journal":"flysim-sugar-journal-v1","boot":{"runtime":"flysim","startFrame":"6465126","brainMs":108246189,"origin":"hot latest generation 230739","generation":230739,"compatibility":"…","wallMs":1790000000000}} +//! ``` +//! +//! A restore splits a run into processes, and a restored process starts from a checkpoint that +//! can be older than the last input the previous process journalled (a hot copy is up to five +//! seconds old, a milestone reset much more). The header is where a reader cuts the journal +//! into per-process segments ([`read_segments`]) and learns which checkpoint each one replays +//! from. It has no `frame` member, so [`read`], which keeps input lines only, skips it. +//! - *Rotation.* The journal lives on tmpfs. When the next line would take it past +//! [`MAX_BYTES`], the file becomes `sugar-journal-1.jsonl` (older ones shift up, the oldest +//! beyond [`KEEP_ROTATIONS`] is removed) and a fresh file starts with a `continues` line that +//! repeats the boot header, so every file can be read on its own. +//! - *Reset.* [`clear`] removes the journal and its rotations. `flysim --reset-to-milestone` +//! calls it (after copying the stores aside), because a reset rewinds the frame counter to the +//! rung's: inputs stamped with the abandoned run's frames would otherwise sit in front of the +//! new run's and read as if they were in its future. + +use std::fs::{File, OpenOptions}; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +/// The journal's file name inside the hot directory. +pub const FILE_NAME: &str = "sugar-journal.jsonl"; + +/// The format name in every header line. +pub const FORMAT: &str = "flysim-sugar-journal-v1"; + +/// The size a journal file may reach before it is rotated. Sugar is rate-limited per minute, so +/// this is days of input; the bound exists because the hot directory is tmpfs. +pub const MAX_BYTES: u64 = 4 << 20; + +/// Rotated files kept beside the live one: `sugar-journal-1.jsonl` (newest) and up. +pub const KEEP_ROTATIONS: usize = 3; + +/// What was applied. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Input { + Sugar { duration_ms: f64 }, + Reward { value: f64 }, +} + +/// One journal line. +#[derive(Debug, Clone, PartialEq)] +pub struct Entry<'a> { + pub frame: u64, + pub brain_ms: f64, + pub input: Input, + pub by: &'a str, + pub source: &'a str, + pub event_id: u64, + pub wall_ms: u64, +} + +impl Entry<'_> { + pub fn to_json(&self) -> Value { + let mut line = json!({ "frame": self.frame.to_string(), "brainMs": self.brain_ms }); + let map = line.as_object_mut().expect("an object"); + match self.input { + Input::Sugar { duration_ms } => { + map.insert("kind".into(), "sugar".into()); + map.insert("durationMs".into(), json!(duration_ms)); + } + Input::Reward { value } => { + map.insert("kind".into(), "reward".into()); + map.insert("value".into(), json!(value)); + } + } + map.insert("by".into(), self.by.into()); + map.insert("source".into(), self.source.into()); + map.insert("eventId".into(), self.event_id.into()); + map.insert("wallMs".into(), self.wall_ms.into()); + line + } +} + +/// The header a process writes when it starts: where its inputs begin. +#[derive(Debug, Clone, PartialEq)] +pub struct BootHeader { + /// `flysim` for the legacy loop, `fly-session` for the session runtime. + pub runtime: String, + /// The frame counter the process starts at: its first input can be stamped no earlier. + pub start_frame: u64, + pub brain_ms: f64, + /// `fresh start`, or the restore candidate's origin (`hot latest generation 7`, ...). + pub origin: String, + /// The generation restored from, if the candidate names one. + pub generation: Option, + pub compatibility: String, + pub wall_ms: u64, +} + +impl BootHeader { + pub fn to_json(&self) -> Value { + json!({ + "runtime": self.runtime, + "startFrame": self.start_frame.to_string(), + "brainMs": self.brain_ms, + "origin": self.origin, + "generation": self.generation, + "compatibility": self.compatibility, + "wallMs": self.wall_ms, + }) + } +} + +/// The append-only journal, rotated at [`MAX_BYTES`]. +pub struct SugarJournal { + dir: PathBuf, + path: PathBuf, + file: Option, + /// Bytes in the live file, as far as this process knows. + bytes: u64, + max_bytes: u64, + keep: usize, + /// The boot header this process wrote, repeated at the top of every rotated-in file. + boot: Option, +} + +impl SugarJournal { + pub fn new(hot_dir: &Path) -> Self { + Self::with_limits(hot_dir, MAX_BYTES, KEEP_ROTATIONS) + } + + pub fn with_limits(hot_dir: &Path, max_bytes: u64, keep: usize) -> Self { + Self { + dir: hot_dir.to_path_buf(), + path: hot_dir.join(FILE_NAME), + file: None, + bytes: 0, + max_bytes: max_bytes.max(1), + keep, + boot: None, + } + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// Write this process's boot header. Called once, when the process knows where it starts + /// (after its restore or its warm-up) and before it admits anything. + pub fn boot(&mut self, header: &BootHeader) { + let boot = header.to_json(); + self.append(&json!({ "journal": FORMAT, "boot": boot.clone() })); + // Set after the line is written: a rotation that line itself triggers must not open + // the new file with a `continues` naming a boot that is not in the journal yet. + self.boot = Some(boot); + } + + /// Append one input line. + pub fn record(&mut self, entry: &Entry<'_>) { + self.append(&entry.to_json()); + } + + /// One line, one `write` of the whole line, so a crash leaves at most a torn last line, + /// which a reader skips and the next open terminates. + fn append(&mut self, value: &Value) { + let mut line = value.to_string(); + line.push('\n'); + if self.file.is_none() && !self.open() { + return; + } + if self.bytes > 0 && self.bytes + line.len() as u64 > self.max_bytes { + self.rotate(); + if !self.open() { + return; + } + } + if let Some(file) = self.file.as_mut() { + match file.write_all(line.as_bytes()) { + Ok(()) => self.bytes += line.len() as u64, + Err(error) => { + tracing::warn!(%error, path = %self.path.display(), "could not append to the sugar journal"); + // Reopen on the next input rather than write through a broken handle. + self.file = None; + } + } + } + } + + /// Open the live file for appending. One whose last line is torn gets its newline, so the + /// next line is whole; one already at the limit is rotated by the caller's next append. + fn open(&mut self) -> bool { + let file = OpenOptions::new().create(true).read(true).append(true).open(&self.path); + let mut file = match file { + Ok(file) => file, + Err(error) => { + tracing::warn!(%error, path = %self.path.display(), "could not open the sugar journal"); + return false; + } + }; + let mut length = file.metadata().map(|m| m.len()).unwrap_or(0); + if length > 0 && !ends_with_newline(&mut file, length) && file.write_all(b"\n").is_ok() { + length += 1; + } + self.bytes = length; + let fresh = length == 0; + self.file = Some(file); + if fresh && let Some(boot) = self.boot.clone() { + // A file this process starts after a rotation says whose inputs follow. + self.append(&json!({ "journal": FORMAT, "continues": boot })); + } + true + } + + fn rotate(&mut self) { + self.file = None; + self.shift_rotations(); + } + + /// `sugar-journal.jsonl` -> `-1`, `-1` -> `-2`, ..., dropping what falls past `keep`. + fn shift_rotations(&mut self) { + if self.keep == 0 { + let _ = std::fs::remove_file(&self.path); + return; + } + let _ = std::fs::remove_file(rotation_path(&self.dir, self.keep)); + for index in (1..self.keep).rev() { + let from = rotation_path(&self.dir, index); + if from.exists() { + let _ = std::fs::rename(&from, rotation_path(&self.dir, index + 1)); + } + } + if let Err(error) = std::fs::rename(&self.path, rotation_path(&self.dir, 1)) { + tracing::warn!(%error, path = %self.path.display(), "could not rotate the sugar journal"); + } + } +} + +fn ends_with_newline(file: &mut File, length: u64) -> bool { + let mut last = [0u8; 1]; + file.seek(SeekFrom::Start(length - 1)) + .and_then(|_| file.read_exact(&mut last)) + .map(|()| last[0] == b'\n') + .unwrap_or(true) +} + +/// `sugar-journal-.jsonl`: index 1 is the newest rotation. +pub fn rotation_path(hot_dir: &Path, index: usize) -> PathBuf { + hot_dir.join(format!("sugar-journal-{index}.jsonl")) +} + +/// Is `name` the journal or one of its rotations? +pub fn is_journal_file(name: &str) -> bool { + name == FILE_NAME + || name + .strip_prefix("sugar-journal-") + .and_then(|rest| rest.strip_suffix(".jsonl")) + .is_some_and(|index| !index.is_empty() && index.bytes().all(|b| b.is_ascii_digit())) +} + +/// Remove the journal and every rotation from `hot_dir`: a reset starts a new record. Returns +/// how many files went. A missing directory is zero files. +pub fn clear(hot_dir: &Path) -> std::io::Result { + if !hot_dir.is_dir() { + return Ok(0); + } + let mut removed = 0; + for entry in std::fs::read_dir(hot_dir)?.flatten() { + if is_journal_file(&entry.file_name().to_string_lossy()) { + std::fs::remove_file(entry.path())?; + removed += 1; + } + } + Ok(removed) +} + +/// Read a journal back: every whole input line, in order. A torn or unreadable line is skipped, +/// and so is every header. +pub fn read(path: &Path) -> std::io::Result> { + let text = std::fs::read_to_string(path)?; + Ok(text + .lines() + .filter_map(|line| serde_json::from_str::(line).ok()) + .filter(|value| value.get("frame").is_some()) + .collect()) +} + +/// One process's inputs: its boot header (absent for lines written before headers existed) and +/// the inputs it admitted, in order. +#[derive(Debug, Clone, PartialEq)] +pub struct Segment { + pub boot: Option, + pub inputs: Vec, +} + +/// The whole journal of `hot_dir`, oldest rotation first, cut into per-process segments at each +/// boot header. A `continues` line keeps the segment it names open across a rotation. +pub fn read_segments(hot_dir: &Path) -> std::io::Result> { + let mut files: Vec<(usize, PathBuf)> = Vec::new(); + if hot_dir.is_dir() { + for entry in std::fs::read_dir(hot_dir)?.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if let Some(index) = name + .strip_prefix("sugar-journal-") + .and_then(|rest| rest.strip_suffix(".jsonl")) + .and_then(|index| index.parse::().ok()) + { + files.push((index, entry.path())); + } + } + } + files.sort_by(|a, b| b.0.cmp(&a.0)); + let live = hot_dir.join(FILE_NAME); + if live.exists() { + files.push((0, live)); + } + let mut segments: Vec = Vec::new(); + for (_, path) in files { + let text = std::fs::read_to_string(&path)?; + for value in text.lines().filter_map(|line| serde_json::from_str::(line).ok()) { + if let Some(boot) = value.get("boot") { + segments.push(Segment { boot: Some(boot.clone()), inputs: Vec::new() }); + } else if let Some(boot) = value.get("continues") { + let open = segments.last().is_some_and(|s| s.boot.as_ref() == Some(boot)); + if !open { + segments.push(Segment { boot: Some(boot.clone()), inputs: Vec::new() }); + } + } else if value.get("frame").is_some() { + if segments.is_empty() { + segments.push(Segment { boot: None, inputs: Vec::new() }); + } + segments.last_mut().expect("a segment").inputs.push(value); + } + } + } + Ok(segments) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn inputs_are_appended_with_their_frame_and_survive_a_reopen() { + let dir = tempfile::tempdir().expect("a temp dir"); + let mut journal = SugarJournal::new(dir.path()); + assert!( + !journal.path().exists(), + "nothing is written before an input" + ); + let sugar = Entry { + frame: 42, + brain_ms: 703.0, + input: Input::Sugar { duration_ms: 400.0 }, + by: "viewer", + source: "test", + event_id: 7, + wall_ms: 1, + }; + journal.record(&sugar); + drop(journal); + let mut journal = SugarJournal::new(dir.path()); + journal.record(&Entry { + frame: 43, + input: Input::Reward { value: 0.5 }, + event_id: 8, + ..sugar + }); + // A torn tail from a crash is skipped, not fatal. + std::fs::OpenOptions::new() + .append(true) + .open(journal.path()) + .and_then(|mut file| file.write_all(b"{\"frame\":\"44\",\"kin")) + .expect("appending a torn line"); + let lines = read(journal.path()).expect("the journal reads back"); + assert_eq!(lines.len(), 2); + assert_eq!(lines[0]["frame"], "42"); + assert_eq!(lines[0]["kind"], "sugar"); + assert_eq!(lines[0]["durationMs"], 400.0); + assert_eq!(lines[1]["frame"], "43"); + assert_eq!(lines[1]["kind"], "reward"); + assert_eq!(lines[1]["value"], 0.5); + assert_eq!(lines[1]["eventId"], 8); + } + + fn header(frame: u64, origin: &str) -> BootHeader { + BootHeader { + runtime: "flysim".to_string(), + start_frame: frame, + brain_ms: frame as f64 * 16.74, + origin: origin.to_string(), + generation: Some(frame), + compatibility: "kernel/adapter/fingerprint".to_string(), + wall_ms: 1, + } + } + + fn sugar(frame: u64, event_id: u64) -> Entry<'static> { + Entry { + frame, + brain_ms: frame as f64, + input: Input::Sugar { duration_ms: 300.0 }, + by: "viewer", + source: "test", + event_id, + wall_ms: 1, + } + } + + #[test] + fn each_process_writes_a_boot_header_that_cuts_the_journal_into_segments() { + let dir = tempfile::tempdir().unwrap(); + let mut journal = SugarJournal::new(dir.path()); + journal.boot(&header(100, "fresh start")); + journal.record(&sugar(120, 1)); + journal.record(&sugar(130, 2)); + drop(journal); + // A crash tore the last line; the next process terminates it before its header. + std::fs::OpenOptions::new() + .append(true) + .open(dir.path().join(FILE_NAME)) + .and_then(|mut file| file.write_all(b"{\"frame\":\"13")) + .unwrap(); + // The restart restored an older hot copy: its inputs start below the torn one's frame. + let mut journal = SugarJournal::new(dir.path()); + journal.boot(&header(125, "hot latest generation 125")); + journal.record(&sugar(126, 3)); + let segments = read_segments(dir.path()).unwrap(); + assert_eq!(segments.len(), 2); + assert_eq!(segments[0].boot.as_ref().unwrap()["origin"], "fresh start"); + assert_eq!(segments[0].inputs.len(), 2); + assert_eq!(segments[1].boot.as_ref().unwrap()["startFrame"], "125"); + assert_eq!(segments[1].boot.as_ref().unwrap()["generation"], 125); + assert_eq!(segments[1].inputs.len(), 1); + assert_eq!(segments[1].inputs[0]["frame"], "126"); + // The input-only reader skips headers and the torn line, as before. + let inputs = read(journal.path()).unwrap(); + assert_eq!(inputs.len(), 3); + } + + #[test] + fn the_journal_rotates_at_its_limit_and_keeps_a_bounded_number_of_files() { + let dir = tempfile::tempdir().unwrap(); + let mut journal = SugarJournal::with_limits(dir.path(), 600, 2); + journal.boot(&header(1, "fresh start")); + for event in 0..40 { + journal.record(&sugar(10 + event, event)); + } + for path in [dir.path().join(FILE_NAME), rotation_path(dir.path(), 1), rotation_path(dir.path(), 2)] { + let length = std::fs::metadata(&path).unwrap().len(); + assert!(length <= 600, "{} is {length} bytes", path.display()); + } + assert!(!rotation_path(dir.path(), 3).exists(), "only two rotations are kept"); + // Every file says whose inputs it holds, and the segments join across the rotations. + let live = std::fs::read_to_string(dir.path().join(FILE_NAME)).unwrap(); + let first: Value = serde_json::from_str(live.lines().next().unwrap()).unwrap(); + assert_eq!(first["journal"], FORMAT); + assert_eq!(first["continues"]["origin"], "fresh start", "{live}"); + let segments = read_segments(dir.path()).unwrap(); + assert_eq!(segments.len(), 1, "one process, one segment: {segments:?}"); + let frames: Vec = segments[0] + .inputs + .iter() + .map(|v| v["frame"].as_str().unwrap().parse().unwrap()) + .collect(); + assert!(frames.windows(2).all(|w| w[1] == w[0] + 1), "in order, no gap inside the kept files"); + assert_eq!(*frames.last().unwrap(), 49); + } + + #[test] + fn clear_removes_the_journal_and_its_rotations_and_nothing_else() { + let dir = tempfile::tempdir().unwrap(); + let mut journal = SugarJournal::with_limits(dir.path(), 300, 3); + journal.boot(&header(1, "fresh start")); + for event in 0..10 { + journal.record(&sugar(10 + event, event)); + } + std::fs::write(dir.path().join("manifest.json"), "{}").unwrap(); + std::fs::write(dir.path().join("sugar-journal-x.jsonl"), "").unwrap(); + let removed = clear(dir.path()).unwrap(); + assert!(removed >= 2, "{removed}"); + let left: Vec = std::fs::read_dir(dir.path()) + .unwrap() + .flatten() + .map(|e| e.file_name().to_string_lossy().to_string()) + .collect(); + let mut left = left; + left.sort(); + assert_eq!(left, vec!["manifest.json", "sugar-journal-x.jsonl"]); + assert_eq!(clear(&dir.path().join("missing")).unwrap(), 0); + assert!(read_segments(dir.path()).unwrap().is_empty()); + } +} diff --git a/services/flysim/crates/flysim-store/src/lib.rs b/services/flysim/crates/flysim-store/src/lib.rs new file mode 100644 index 0000000..0d18ad8 --- /dev/null +++ b/services/flysim/crates/flysim-store/src/lib.rs @@ -0,0 +1,12 @@ +//! The `FLYSIM01` checkpoint store and the sugar journal. +//! +//! `FLYSIM01` is the checkpoint format of record for the legacy Game Boy composition until +//! RETIRE-01 (`docs/design/session-framework/legacy-gameboy-v1.md` section 16). Two runtimes write +//! and read it: the legacy loop (`flysim`) and the session runtime (`fly-session`, STATE-02). This +//! crate is the one copy of the code both use, moved here unchanged from `flysim::store` and +//! `flysim::journal`, which re-export it, so a store written by either is the other's store: the +//! same envelope bytes, the same generations and `manifest.json`, the same milestone archives and +//! rotation, and the same restore order. + +pub mod journal; +pub mod store; diff --git a/services/flysim/crates/flysim-store/src/store.rs b/services/flysim/crates/flysim-store/src/store.rs new file mode 100644 index 0000000..586e6c0 --- /dev/null +++ b/services/flysim/crates/flysim-store/src/store.rs @@ -0,0 +1,645 @@ +//! Checkpoint persistence: the `FLYSIM01` envelope, the atomic commit, the generations and the +//! milestone archives. +//! +//! `docs/design/flysim.md` section 8, as amended by the contract override at the top of that +//! document: +//! +//! - the envelope is `flybrain-core`'s frozen `encodeEnvelope` layout with the magic `FLYSIM01`, +//! carrying the seven agent chunks plus `emulator`, `framebuffer`, `ratchetGame` and +//! `ratchetFrame`; +//! - a commit writes `.checkpoint.tmp`, fsyncs it, renames it, fsyncs the directory, and +//! then does the same for `manifest.json`. **The manifest rename is the commit point**: a +//! crash before it leaves an unreferenced file that is never loaded; +//! - durable commits go to `save_dir` every `checkpoint_seconds` (default 300) and on every +//! event that matters; a hot copy goes to `hot_dir` (tmpfs) every `hot_seconds` (default 5); +//! - the first commit at a new best rank also writes `milestone-.checkpoint`, which later +//! rotations never unlink. + +use std::collections::BTreeMap; +use std::fs::{File, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use flybrain_core::envelope::{EnvelopeParts, decode_envelope, encode_envelope}; +use flybrain_core::json::JsonValue; +use serde::{Deserialize, Serialize}; + +/// Envelope magic. Chunk names stay `[a-zA-Z]+` so the TypeScript `decodeEnvelope` can read a +/// flysim checkpoint for recap and inspection tooling. +pub const MAGIC: &str = "FLYSIM01"; + +/// Chunk names flysim adds to `flybrain-core`'s `AGENT_CHUNK_NAMES`. +pub const EMULATOR_CHUNK: &str = "emulator"; +pub const FRAMEBUFFER_CHUNK: &str = "framebuffer"; +pub const RATCHET_GAME_CHUNK: &str = "ratchetGame"; +pub const RATCHET_FRAME_CHUNK: &str = "ratchetFrame"; + +/// `manifest.json`: which generations are current, and which are archived forever. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct StoreManifest { + /// Highest generation ever allocated in this store. + pub generation: u64, + /// The generation to restore first. + pub latest: Option, + /// The generation to restore if `latest` will not load. + pub previous: Option, + /// Best-rank archives, rank to generation. Their files are never rotated away. + pub archives: BTreeMap, +} + +impl StoreManifest { + fn record(&mut self, generation: u64, archive_rank: Option) { + self.generation = self.generation.max(generation); + if self.latest != Some(generation) { + self.previous = self.latest; + self.latest = Some(generation); + } + if let Some(rank) = archive_rank { + self.archives.insert(rank, generation); + } + } + + /// Generations that must survive rotation. + fn referenced(&self) -> Vec { + let mut out: Vec = self.latest.into_iter().chain(self.previous).collect(); + out.extend(self.archives.values().copied()); + out + } +} + +/// One restore candidate, in the order it should be tried. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Candidate { + pub path: PathBuf, + /// Human description for the log and for `/status`'s fallback reporting. + pub origin: String, + pub generation: Option, +} + +/// A checkpoint directory: `.checkpoint`, `milestone-.checkpoint`, `manifest.json`. +#[derive(Debug, Clone)] +pub struct Store { + dir: PathBuf, + keep_generations: usize, +} + +impl Store { + pub fn new(dir: impl Into, keep_generations: usize) -> Self { + Self { dir: dir.into(), keep_generations: keep_generations.max(1) } + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + pub fn create(&self) -> Result<()> { + std::fs::create_dir_all(&self.dir) + .with_context(|| format!("creating checkpoint directory {}", self.dir.display())) + } + + pub fn manifest_path(&self) -> PathBuf { + self.dir.join("manifest.json") + } + + pub fn generation_path(&self, generation: u64) -> PathBuf { + self.dir.join(format!("{generation}.checkpoint")) + } + + pub fn archive_path(&self, rank: u32) -> PathBuf { + self.dir.join(format!("milestone-{rank}.checkpoint")) + } + + /// Read `manifest.json`, or `None` when it is absent or unreadable. + pub fn manifest(&self) -> Option { + let text = std::fs::read_to_string(self.manifest_path()).ok()?; + match serde_json::from_str(&text) { + Ok(manifest) => Some(manifest), + Err(error) => { + tracing::warn!(%error, path = %self.manifest_path().display(), "unreadable store manifest"); + None + } + } + } + + /// Highest generation the store has ever allocated, from the manifest and from the files on + /// disk (an unreferenced file from a crashed commit still counts, so a generation number is + /// never reused). + pub fn highest_generation(&self) -> u64 { + let mut highest = self.manifest().map_or(0, |manifest| manifest.generation); + if let Ok(entries) = std::fs::read_dir(&self.dir) { + for entry in entries.flatten() { + if let Some(generation) = parse_generation(&entry.file_name().to_string_lossy()) { + highest = highest.max(generation); + } + } + } + highest + } + + /// Restore candidates from this store, in order: latest, previous, then the archives by + /// descending rank. + pub fn candidates(&self, label: &str) -> Vec { + let Some(manifest) = self.manifest() else { + return Vec::new(); + }; + let mut out = Vec::new(); + for (kind, generation) in [("latest", manifest.latest), ("previous", manifest.previous)] { + if let Some(generation) = generation { + out.push(Candidate { + path: self.generation_path(generation), + origin: format!("{label} {kind} generation {generation}"), + generation: Some(generation), + }); + } + } + for (rank, generation) in manifest.archives.iter().rev() { + out.push(Candidate { + path: self.generation_path(*generation), + origin: format!("{label} archived generation {generation} (rank {rank})"), + generation: Some(*generation), + }); + out.push(Candidate { + path: self.archive_path(*rank), + origin: format!("{label} milestone archive rank {rank}"), + generation: Some(*generation), + }); + } + out.retain(|candidate| candidate.path.exists()); + out + } + + /// Write `bytes` as `generation`, commit it, archive it if `archive_rank` is set, then rotate. + /// + /// The sequence is exactly section 8's: payload tmp, fsync, rename, dir fsync, then manifest + /// tmp, fsync, rename, dir fsync. + pub fn commit( + &self, + generation: u64, + bytes: &[u8], + archive_rank: Option, + ) -> Result { + self.create()?; + write_atomic(&self.generation_path(generation), bytes)?; + if let Some(rank) = archive_rank { + write_atomic(&self.archive_path(rank), bytes)?; + } + let mut manifest = self.manifest().unwrap_or_default(); + manifest.record(generation, archive_rank); + let text = serde_json::to_vec_pretty(&manifest)?; + write_atomic(&self.manifest_path(), &text)?; + self.rotate(&manifest)?; + Ok(manifest) + } + + /// Stage a payload without committing it. Only the crash-simulation test uses this: it is + /// the state a `kill -9` between the tmp write and the rename leaves behind. + pub fn stage_for_test(&self, generation: u64, bytes: &[u8]) -> Result { + self.create()?; + let path = tmp_path(&self.generation_path(generation)); + write_and_sync(&path, bytes)?; + Ok(path) + } + + /// Remove generation files that the manifest no longer references, keeping the newest + /// `keep_generations` and never touching an archive. + fn rotate(&self, manifest: &StoreManifest) -> Result<()> { + let referenced = manifest.referenced(); + let mut generations: Vec = Vec::new(); + for entry in std::fs::read_dir(&self.dir)?.flatten() { + let name = entry.file_name().to_string_lossy().to_string(); + if let Some(generation) = parse_generation(&name) { + generations.push(generation); + } else if name.ends_with(".checkpoint.tmp") { + // A tmp file from an interrupted commit is never loadable; clean it up. + let _ = std::fs::remove_file(entry.path()); + } + } + generations.sort_unstable_by(|a, b| b.cmp(a)); + for (index, generation) in generations.iter().enumerate() { + if referenced.contains(generation) || index < self.keep_generations { + continue; + } + let path = self.generation_path(*generation); + if let Err(error) = std::fs::remove_file(&path) { + tracing::warn!(%error, path = %path.display(), "could not rotate a checkpoint"); + } + } + Ok(()) + } +} + +/// `milestone-.checkpoint` is an independent file, so it is not a generation. +fn parse_generation(name: &str) -> Option { + name.strip_suffix(".checkpoint")?.parse().ok() +} + +fn tmp_path(path: &Path) -> PathBuf { + let mut name = path.as_os_str().to_os_string(); + name.push(".tmp"); + PathBuf::from(name) +} + +/// tmp write, fsync, rename, directory fsync. +pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> { + let tmp = tmp_path(path); + write_and_sync(&tmp, bytes)?; + std::fs::rename(&tmp, path) + .with_context(|| format!("renaming {} to {}", tmp.display(), path.display()))?; + sync_dir(path.parent().unwrap_or(Path::new("."))) +} + +fn write_and_sync(path: &Path, bytes: &[u8]) -> Result<()> { + let mut file = OpenOptions::new() + .create(true) + .write(true) + .truncate(true) + .open(path) + .with_context(|| format!("creating {}", path.display()))?; + file.write_all(bytes)?; + file.flush()?; + file.sync_all().with_context(|| format!("fsync {}", path.display()))?; + Ok(()) +} + +fn sync_dir(dir: &Path) -> Result<()> { + // Opening a directory read-only and fsyncing it is what makes the rename durable. + File::open(dir) + .and_then(|file| file.sync_all()) + .with_context(|| format!("fsync directory {}", dir.display())) +} + +// --------------------------------------------------------------------------------------------- +// The envelope +// --------------------------------------------------------------------------------------------- + +/// Everything a checkpoint carries besides the agent's own chunks. +#[derive(Debug, Clone, PartialEq)] +pub struct RuntimeState { + pub generation: u64, + pub wall_ms: u64, + pub rom_sha256: String, + pub emulator_frame: u64, + pub compatibility: String, + pub speed: f64, + pub buttons: u32, + /// Simulated milliseconds at which the current milestone rank was reached. + pub rank_since_ms: f64, + pub last_event_id: u64, + /// The adapter's own lifetime reward state. + pub reward: serde_json::Value, + pub ratchet: flybrain_gb::RatchetState, + pub emulator: Vec, + pub framebuffer: Vec, + /// The ratchet's best safe snapshot, if it has one. + pub ratchet_game: Vec, + pub ratchet_frame: Vec, +} + +/// A decoded checkpoint: the agent half plus the runtime half. +#[derive(Debug, Clone)] +pub struct Checkpoint { + pub agent: flybrain_core::agent::AgentState, + pub runtime: RuntimeState, +} + +/// Encode an agent state plus the runtime state into one `FLYSIM01` envelope. +pub fn encode( + agent: &flybrain_core::agent::AgentState, + runtime: &RuntimeState, +) -> Result> { + let parts = flybrain_core::envelope::agent_to_chunks(agent); + let mut manifest = parts.manifest; + manifest.set("generation", (runtime.generation as f64).into()); + manifest.set("wallMs", (runtime.wall_ms as f64).into()); + manifest.set("romHash", runtime.rom_sha256.as_str().into()); + manifest.set("emulatorFrame", (runtime.emulator_frame as f64).into()); + manifest.set("compatibility", runtime.compatibility.as_str().into()); + manifest.set("speed", runtime.speed.into()); + manifest.set("buttons", f64::from(runtime.buttons).into()); + manifest.set("rankSinceMs", runtime.rank_since_ms.into()); + manifest.set("lastEventId", (runtime.last_event_id as f64).into()); + manifest.set("reward", to_json_value(&runtime.reward)?); + manifest.set("ratchet", to_json_value(&serde_json::to_value(runtime.ratchet)?)?); + + let mut chunks = parts.chunks; + chunks.push((EMULATOR_CHUNK.to_string(), runtime.emulator.clone())); + chunks.push((FRAMEBUFFER_CHUNK.to_string(), runtime.framebuffer.clone())); + chunks.push((RATCHET_GAME_CHUNK.to_string(), runtime.ratchet_game.clone())); + chunks.push((RATCHET_FRAME_CHUNK.to_string(), runtime.ratchet_frame.clone())); + + encode_envelope(MAGIC, &manifest, &chunks).map_err(|error| anyhow::anyhow!("{error}")) +} + +/// Decode and structurally validate a `FLYSIM01` envelope. +/// +/// Value-level validation belongs to the importers: `NeuralAgent::import_state` is +/// self-validating and a no-op on failure, and `Ratchet::import` rejects an impossible state. +pub fn decode(bytes: &[u8]) -> Result { + let parts: EnvelopeParts = + decode_envelope(bytes, MAGIC).map_err(|error| anyhow::anyhow!("{error}"))?; + let manifest = parts.manifest.clone(); + let agent = flybrain_core::envelope::agent_from_chunks(&manifest, &parts) + .map_err(|error| anyhow::anyhow!("{error}"))?; + + let string = |key: &str| -> Result { + manifest + .get(key) + .and_then(JsonValue::as_str) + .map(str::to_string) + .ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}")) + }; + let number = |key: &str| -> Result { + manifest + .get(key) + .and_then(JsonValue::as_f64) + .ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}")) + }; + let chunk = |name: &str| -> Result> { + parts + .chunk(name) + .map(<[u8]>::to_vec) + .ok_or_else(|| anyhow::anyhow!("checkpoint is missing the {name} chunk")) + }; + + let ratchet_json = manifest + .get("ratchet") + .ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing ratchet"))?; + let ratchet: flybrain_gb::RatchetState = serde_json::from_str(&ratchet_json.stringify()) + .context("checkpoint ratchet state is not readable")?; + let reward = manifest + .get("reward") + .map(|value| serde_json::from_str(&value.stringify())) + .transpose() + .context("checkpoint reward state is not readable")? + .unwrap_or(serde_json::Value::Null); + + Ok(Checkpoint { + agent, + runtime: RuntimeState { + generation: number("generation")? as u64, + wall_ms: number("wallMs")? as u64, + rom_sha256: string("romHash")?, + emulator_frame: number("emulatorFrame")? as u64, + compatibility: string("compatibility")?, + speed: number("speed")?, + buttons: number("buttons")? as u32, + rank_since_ms: number("rankSinceMs").unwrap_or(0.0), + last_event_id: number("lastEventId").unwrap_or(0.0) as u64, + reward, + ratchet, + emulator: chunk(EMULATOR_CHUNK)?, + framebuffer: chunk(FRAMEBUFFER_CHUNK)?, + ratchet_game: chunk(RATCHET_GAME_CHUNK)?, + ratchet_frame: chunk(RATCHET_FRAME_CHUNK)?, + }, + }) +} + +/// Read and decode a candidate, so a caller can try the next one on any failure. +pub fn load(path: &Path) -> Result { + let bytes = + std::fs::read(path).with_context(|| format!("reading checkpoint {}", path.display()))?; + decode(&bytes).with_context(|| format!("decoding checkpoint {}", path.display())) +} + +fn to_json_value(value: &serde_json::Value) -> Result { + JsonValue::parse(&serde_json::to_string(value)?).map_err(|error| anyhow::anyhow!("{error}")) +} + +/// The restore order: the tmpfs hot copy first, then the durable store. +/// +/// The hot copy is written every few seconds and the durable one every few minutes, so the hot +/// copy is normally the newest state that exists; it is a first-class candidate because it uses +/// the identical envelope and the identical atomic sequence, and not a partial dump. +/// The compatibility string the newest decodable checkpoint in `dir` carries, if any. +/// +/// The store's own `manifest.json` is only an index (generation, latest, previous, archives) — +/// the compatibility string lives in each checkpoint's own `FLYSIM01` envelope manifest, so +/// answering "what will this build refuse?" means decoding a checkpoint. Candidates are tried +/// newest first and a corrupt one is skipped, which is the same order and the same tolerance +/// `Sim::boot` restores with. +/// +/// `flysim --print-state-compatibility DIR` is this, and `infra/05-deploy.sh` compares its +/// answer with `--print-compatibility` before flipping the `current` symlink. +pub fn state_compatibility(dir: &Path) -> Option { + let store = Store::new(dir, 8); + for candidate in store.candidates("durable") { + if let Ok(checkpoint) = load(&candidate.path) { + return Some(checkpoint.runtime.compatibility); + } + } + None +} + +pub fn restore_order(hot: &Store, durable: &Store) -> Vec { + let mut out = hot.candidates("hot"); + out.extend(durable.candidates("durable")); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn runtime(generation: u64) -> RuntimeState { + RuntimeState { + generation, + wall_ms: 1_700_000_000_000, + rom_sha256: "ab".repeat(32), + emulator_frame: 12_345, + compatibility: "kernel/adapter/fingerprint".to_string(), + speed: 1.0, + buttons: 0b0001_0000, + rank_since_ms: 4_242.0, + last_event_id: 77, + reward: serde_json::json!({ "version": 3, "total": 1.25 }), + ratchet: flybrain_gb::RatchetState { best: 3, ..Default::default() }, + emulator: vec![7; 64], + framebuffer: vec![9; 32], + ratchet_game: vec![1, 2, 3], + ratchet_frame: vec![4, 5, 6], + } + } + + fn agent_state() -> flybrain_core::agent::AgentState { + use flybrain_core::decoder::DecoderState; + use flybrain_core::lif::LifState; + use flybrain_core::ordered::NumberMap; + use flybrain_core::plasticity::PlasticityState; + flybrain_core::agent::AgentState { + version: 1, + remainder: 0.75, + warmed_up: true, + network: LifState { + membrane: vec![0.5, -0.25], + refractory: vec![0, 3], + last_spike_ms: vec![-1_000_000.0, 12.0], + visual_drive: vec![0.1], + rng: -12_345, + reward_remaining: 40.0, + ms: 9_000.0, + population_rate: 1.5, + rates: NumberMap::from_pairs([("forward", 2.0), ("reward_pam", 0.5)]), + plasticity: PlasticityState { + version: "fly-kc-mbon-rstdp-v2".to_string(), + topology: 42, + enabled: true, + updates: 3.0, + signal: 0.25, + gains: vec![1.0, 0.9], + traces: vec![0.0, 0.1], + touched: vec![0.0, 8_000.0], + }, + }, + decoder: DecoderState { + version: 4, + calibrated: true, + baseline: NumberMap::from_pairs([("forward", 1.0)]), + held_until: NumberMap::new(), + next_allowed: NumberMap::new(), + next_decision: 100.0, + current: Some("a".to_string()), + fatigue: NumberMap::new(), + macro_next_decision: 0.0, + macro_current: None, + macro_fatigue: NumberMap::new(), + }, + } + } + + #[test] + fn the_envelope_round_trips_every_field_and_chunk() { + let agent = agent_state(); + let runtime = runtime(4); + let bytes = encode(&agent, &runtime).unwrap(); + assert!(bytes.starts_with(MAGIC.as_bytes())); + + let back = decode(&bytes).unwrap(); + assert_eq!(back.agent, agent); + assert_eq!(back.runtime, runtime); + + // Re-encoding the decoded state is byte-identical, so a restore-and-save cycle is stable. + assert_eq!(encode(&back.agent, &back.runtime).unwrap(), bytes); + } + + #[test] + fn a_corrupted_or_truncated_envelope_is_rejected() { + let bytes = encode(&agent_state(), &runtime(1)).unwrap(); + assert!(decode(&bytes[..bytes.len() - 1]).is_err(), "truncated"); + + let mut flipped = bytes.clone(); + let middle = flipped.len() / 2; + flipped[middle] ^= 0xff; + assert!(decode(&flipped).is_err(), "checksum"); + + let mut trailing = bytes.clone(); + trailing.push(0); + assert!(decode(&trailing).is_err(), "trailing bytes"); + + let mut wrong_magic = bytes; + wrong_magic[0] = b'X'; + assert!(decode(&wrong_magic).is_err(), "magic"); + } + + #[test] + fn a_commit_is_atomic_and_a_crash_before_the_rename_leaves_a_loadable_store() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path(), 2); + let first = encode(&agent_state(), &runtime(1)).unwrap(); + store.commit(1, &first, None).unwrap(); + + // kill -9 between the tmp write and the rename. + let mut broken = encode(&agent_state(), &runtime(2)).unwrap(); + broken.truncate(broken.len() / 2); + let staged = store.stage_for_test(2, &broken).unwrap(); + assert!(staged.exists()); + + let manifest = store.manifest().unwrap(); + assert_eq!(manifest.latest, Some(1)); + let candidates = store.candidates("durable"); + assert_eq!(candidates.len(), 1, "the staged tmp file is not a candidate: {candidates:?}"); + assert_eq!(load(&candidates[0].path).unwrap().runtime.generation, 1); + + // The next successful commit cleans the orphan up. + let second = encode(&agent_state(), &runtime(3)).unwrap(); + store.commit(3, &second, None).unwrap(); + assert!(!staged.exists()); + assert_eq!(store.manifest().unwrap().latest, Some(3)); + assert_eq!(store.manifest().unwrap().previous, Some(1)); + } + + #[test] + fn a_payload_renamed_without_its_manifest_is_never_loaded() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path(), 2); + store.commit(1, &encode(&agent_state(), &runtime(1)).unwrap(), None).unwrap(); + + // The payload rename succeeded, the manifest rename did not: the commit point is the + // manifest, so generation 2 is invisible. + write_atomic(&store.generation_path(2), b"not even an envelope").unwrap(); + let candidates = store.candidates("durable"); + assert_eq!(candidates.len(), 1); + assert_eq!(candidates[0].generation, Some(1)); + assert_eq!(store.highest_generation(), 2, "but the number is not reused"); + } + + #[test] + fn the_restore_order_is_hot_then_durable_then_archives_by_descending_rank() { + let dir = tempfile::tempdir().unwrap(); + let durable = Store::new(dir.path().join("durable"), 2); + let hot = Store::new(dir.path().join("hot"), 2); + let bytes = encode(&agent_state(), &runtime(1)).unwrap(); + + durable.commit(1, &bytes, Some(1)).unwrap(); + durable.commit(2, &bytes, Some(4)).unwrap(); + durable.commit(3, &bytes, None).unwrap(); + hot.commit(7, &bytes, None).unwrap(); + + let order: Vec = + restore_order(&hot, &durable).into_iter().map(|c| c.origin).collect(); + assert_eq!( + order, + vec![ + "hot latest generation 7", + "durable latest generation 3", + "durable previous generation 2", + "durable archived generation 2 (rank 4)", + "durable milestone archive rank 4", + "durable archived generation 1 (rank 1)", + "durable milestone archive rank 1", + ] + ); + } + + #[test] + fn rotation_keeps_the_referenced_generations_and_never_unlinks_an_archive() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path(), 2); + let bytes = encode(&agent_state(), &runtime(1)).unwrap(); + store.commit(1, &bytes, Some(2)).unwrap(); + for generation in 2..=6 { + store.commit(generation, &bytes, None).unwrap(); + } + assert!(store.generation_path(6).exists(), "latest"); + assert!(store.generation_path(5).exists(), "previous"); + assert!(store.generation_path(1).exists(), "archived generation"); + assert!(store.archive_path(2).exists(), "milestone archive"); + assert!(!store.generation_path(3).exists(), "rotated away"); + assert!(!store.generation_path(4).exists(), "rotated away"); + } + + #[test] + fn an_empty_or_manifestless_directory_offers_no_candidates() { + let dir = tempfile::tempdir().unwrap(); + let store = Store::new(dir.path().join("missing"), 2); + assert!(store.candidates("durable").is_empty()); + assert_eq!(store.highest_generation(), 0); + + let store = Store::new(dir.path(), 2); + store.create().unwrap(); + std::fs::write(store.manifest_path(), "{ not json").unwrap(); + assert!(store.candidates("durable").is_empty(), "an unreadable manifest is not fatal"); + } +} diff --git a/services/flysim/crates/flysim/Cargo.toml b/services/flysim/crates/flysim/Cargo.toml index 3884630..37d9b1b 100644 --- a/services/flysim/crates/flysim/Cargo.toml +++ b/services/flysim/crates/flysim/Cargo.toml @@ -31,6 +31,8 @@ cuda = ["flybrain-core/cuda"] flybrain-core = { path = "../flybrain-core" } flybrain-gb = { path = "../flybrain-gb" } flybus = { path = "../flybus" } +# The FLYSIM01 store and the sugar journal, shared with the session runtime (STATE-02). +flysim-store = { path = "../flysim-store" } anyhow = "1.0" axum = { version = "0.8", features = ["ws"] } diff --git a/services/flysim/crates/flysim/src/journal.rs b/services/flysim/crates/flysim/src/journal.rs index 019c54a..99073ad 100644 --- a/services/flysim/crates/flysim/src/journal.rs +++ b/services/flysim/crates/flysim/src/journal.rs @@ -1,176 +1,6 @@ //! The sugar journal: every admitted audience input, stamped with the frame it was applied before. //! -//! `sugar-journal.jsonl` in `[paths] hot_dir`, one JSON object per line, append-only. It is not -//! part of a checkpoint and nothing reads it back into the fly: it is the record a shadow run -//! (the session framework's CUT-01, `docs/design/session-framework/legacy-gameboy-v1.md` section -//! 15) replays audience input from. The legacy loop applies an admitted sugar at once, in the -//! command drain at the top of a frame, so an input is fully placed by the transition it precedes: -//! -//! ```json -//! {"frame":"6465126","brainMs":108246189,"kind":"sugar","durationMs":400,"by":"viewer","source":"twitch","eventId":81234,"wallMs":1790000000000} -//! ``` -//! -//! - `frame` is the frame counter when the input was applied, which is the `step` of the next -//! transition in the frame trace (`crate::trace`): replay applies it before that transition's -//! ticks. A restore carries the frame counter, so stamps continue across restarts. -//! - `kind` is `sugar` (a `reward-pulse` stimulation of `durationMs`, after the admission rules -//! and the clamp) or `reward` (an operator's `POST /reward`, one reinforcement of `value`). -//! - `brainMs` cross-checks the stamp; `eventId` joins the event log; `wallMs` is for people. -//! -//! Refused requests are not journalled: admission is wall-clock policy, and a replay applies what -//! was admitted. A write that fails is a warning, never a refusal: the input has already reached -//! the fly. +//! The code lives in the `flysim-store` crate, which the session runtime links too (STATE-02). +//! This module re-exports it. -use std::fs::{File, OpenOptions}; -use std::io::Write; -use std::path::{Path, PathBuf}; - -use serde_json::{Value, json}; - -/// The journal's file name inside the hot directory. -pub const FILE_NAME: &str = "sugar-journal.jsonl"; - -/// What was applied. -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum Input { - Sugar { duration_ms: f64 }, - Reward { value: f64 }, -} - -/// One journal line. -#[derive(Debug, Clone, PartialEq)] -pub struct Entry<'a> { - pub frame: u64, - pub brain_ms: f64, - pub input: Input, - pub by: &'a str, - pub source: &'a str, - pub event_id: u64, - pub wall_ms: u64, -} - -impl Entry<'_> { - pub fn to_json(&self) -> Value { - let mut line = json!({ "frame": self.frame.to_string(), "brainMs": self.brain_ms }); - let map = line.as_object_mut().expect("an object"); - match self.input { - Input::Sugar { duration_ms } => { - map.insert("kind".into(), "sugar".into()); - map.insert("durationMs".into(), json!(duration_ms)); - } - Input::Reward { value } => { - map.insert("kind".into(), "reward".into()); - map.insert("value".into(), json!(value)); - } - } - map.insert("by".into(), self.by.into()); - map.insert("source".into(), self.source.into()); - map.insert("eventId".into(), self.event_id.into()); - map.insert("wallMs".into(), self.wall_ms.into()); - line - } -} - -/// The append-only journal. Opened on the first input, so a run nobody feeds writes no file. -pub struct SugarJournal { - path: PathBuf, - file: Option, -} - -impl SugarJournal { - pub fn new(hot_dir: &Path) -> Self { - Self { - path: hot_dir.join(FILE_NAME), - file: None, - } - } - - pub fn path(&self) -> &Path { - &self.path - } - - /// Append one line. Each line is one `write` of the whole line, so a crash leaves at most a - /// torn last line, which a reader skips. - pub fn record(&mut self, entry: &Entry<'_>) { - if self.file.is_none() { - match OpenOptions::new() - .create(true) - .append(true) - .open(&self.path) - { - Ok(file) => self.file = Some(file), - Err(error) => { - tracing::warn!(%error, path = %self.path.display(), "could not open the sugar journal"); - return; - } - } - } - let mut line = entry.to_json().to_string(); - line.push('\n'); - if let Some(file) = self.file.as_mut() - && let Err(error) = file.write_all(line.as_bytes()) - { - tracing::warn!(%error, path = %self.path.display(), "could not append to the sugar journal"); - // Reopen on the next input rather than write through a broken handle. - self.file = None; - } - } -} - -/// Read a journal back: every whole line, in order. A torn or unreadable line is skipped. -pub fn read(path: &Path) -> std::io::Result> { - let text = std::fs::read_to_string(path)?; - Ok(text - .lines() - .filter_map(|line| serde_json::from_str::(line).ok()) - .filter(|value| value.get("frame").is_some()) - .collect()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn inputs_are_appended_with_their_frame_and_survive_a_reopen() { - let dir = tempfile::tempdir().expect("a temp dir"); - let mut journal = SugarJournal::new(dir.path()); - assert!( - !journal.path().exists(), - "nothing is written before an input" - ); - let sugar = Entry { - frame: 42, - brain_ms: 703.0, - input: Input::Sugar { duration_ms: 400.0 }, - by: "viewer", - source: "test", - event_id: 7, - wall_ms: 1, - }; - journal.record(&sugar); - drop(journal); - let mut journal = SugarJournal::new(dir.path()); - journal.record(&Entry { - frame: 43, - input: Input::Reward { value: 0.5 }, - event_id: 8, - ..sugar - }); - // A torn tail from a crash is skipped, not fatal. - std::fs::OpenOptions::new() - .append(true) - .open(journal.path()) - .and_then(|mut file| file.write_all(b"{\"frame\":\"44\",\"kin")) - .expect("appending a torn line"); - let lines = read(journal.path()).expect("the journal reads back"); - assert_eq!(lines.len(), 2); - assert_eq!(lines[0]["frame"], "42"); - assert_eq!(lines[0]["kind"], "sugar"); - assert_eq!(lines[0]["durationMs"], 400.0); - assert_eq!(lines[1]["frame"], "43"); - assert_eq!(lines[1]["kind"], "reward"); - assert_eq!(lines[1]["value"], 0.5); - assert_eq!(lines[1]["eventId"], 8); - } -} +pub use flysim_store::journal::*; diff --git a/services/flysim/crates/flysim/src/reset.rs b/services/flysim/crates/flysim/src/reset.rs index d610950..3256270 100644 --- a/services/flysim/crates/flysim/src/reset.rs +++ b/services/flysim/crates/flysim/src/reset.rs @@ -32,6 +32,10 @@ //! talked, reached, pushed-back) are memory-only by contract //! (`docs/design/macros.md` section 12.1: "a restored run offers every target once more"), //! so stopping flysim is what resets those and this has nothing to do. +//! 6. **clears the sugar journal** (`crate::journal::clear`): the journal and its rotations in the +//! hot store. The reset rewinds the frame counter to the rung's, so inputs stamped with the +//! abandoned run's frames would otherwise precede the new run's and read as its future. The +//! dated archive of step 1 keeps the old journal. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; @@ -161,6 +165,11 @@ pub fn reset_to_milestone( memory-only and are reset by stopping flysim)" )); + // 6. The sugar journal, copied aside in step 1. + let journals = crate::journal::clear(hot_dir) + .with_context(|| format!("clearing the sugar journal in {}", hot_dir.display()))?; + report.push(format!("cleared the sugar journal: {journals} files removed")); + Ok(report) } @@ -379,6 +388,21 @@ mod tests { }; state_dir(&durable, &[3, 5, 9, 11], spent); state_dir(&hot, &[11], spent); + // The abandoned run's sugar journal, rotated once. + let mut journal = crate::journal::SugarJournal::with_limits(&hot, 200, 3); + for frame in 0..4 { + journal.record(&crate::journal::Entry { + frame: 900 + frame, + brain_ms: 0.0, + input: crate::journal::Input::Sugar { duration_ms: 300.0 }, + by: "viewer", + source: "test", + event_id: frame, + wall_ms: 1, + }); + } + drop(journal); + assert!(crate::journal::rotation_path(&hot, 1).is_file()); let archive = tmp.path().join("archive-20260922"); let report = reset_to_milestone(&durable, &hot, 5, &archive).unwrap(); @@ -397,6 +421,11 @@ mod tests { assert!(!durable.join("events.jsonl").exists()); assert!(!durable.join("events-20260921.jsonl").exists()); assert!(!hot.join("milestone-11.checkpoint").exists()); + // The journal is cleared, and the archive keeps it. + assert!(!hot.join(crate::journal::FILE_NAME).exists()); + assert!(!crate::journal::rotation_path(&hot, 1).exists()); + assert!(archive.join("hot").join(crate::journal::FILE_NAME).is_file()); + assert!(report.iter().any(|line| line.starts_with("cleared the sugar journal: 4 files")), "{report:?}"); // Both stores restore the rung, and the counters are back. for store in [Store::new(&hot, KEEP_GENERATIONS), Store::new(&durable, KEEP_GENERATIONS)] { diff --git a/services/flysim/crates/flysim/src/simloop.rs b/services/flysim/crates/flysim/src/simloop.rs index ff04d30..7604081 100644 --- a/services/flysim/crates/flysim/src/simloop.rs +++ b/services/flysim/crates/flysim/src/simloop.rs @@ -389,6 +389,9 @@ pub struct Sim { compatibility: String, semantic_rewards: bool, restored: bool, + /// Where this process started, for the sugar journal's boot header: the restore candidate's + /// origin and generation, or a fresh start. + boot_origin: (String, Option), /// Per-phase timing, off unless `FLY_PROFILE_SECONDS` is set (`crate::profile`). profiler: Profiler, } @@ -595,6 +598,7 @@ impl Sim { compatibility, semantic_rewards, restored: false, + boot_origin: ("fresh start".to_string(), None), profiler: Profiler::from_env(now), agent, emulator, @@ -641,6 +645,17 @@ impl Sim { // the whole warm-up — or, after a restore, every neuron that has ever fired, since the // checkpoint's `lastSpikeMs` values are absolute brain milliseconds. sim.last_publish_ms = sim.agent.network.ms; + // The journal's boot header: this process's inputs start here, whatever the previous + // process journalled after the checkpoint it restored (`crate::journal`). + sim.journal.boot(&crate::journal::BootHeader { + runtime: "flysim".to_string(), + start_frame: sim.frame.frame_counter, + brain_ms: sim.agent.network.ms, + origin: sim.boot_origin.0.clone(), + generation: sim.boot_origin.1, + compatibility: sim.compatibility.clone(), + wall_ms: now_wall_ms(), + }); sim.status = FeedStatus::Running; // A durable commit immediately after startup or restore (section 8), so the 300-second // interval is a ceiling on routine loss only, and so a broken write path is found now @@ -685,6 +700,7 @@ impl Sim { "restored" ); self.restored = true; + self.boot_origin = (candidate.origin.clone(), candidate.generation); self.emit(NewEvent::new( FeedEventKind::System, format!("Restored from {}", candidate.origin), diff --git a/services/flysim/crates/flysim/src/store.rs b/services/flysim/crates/flysim/src/store.rs index 586e6c0..abea562 100644 --- a/services/flysim/crates/flysim/src/store.rs +++ b/services/flysim/crates/flysim/src/store.rs @@ -1,645 +1,8 @@ //! Checkpoint persistence: the `FLYSIM01` envelope, the atomic commit, the generations and the //! milestone archives. //! -//! `docs/design/flysim.md` section 8, as amended by the contract override at the top of that -//! document: -//! -//! - the envelope is `flybrain-core`'s frozen `encodeEnvelope` layout with the magic `FLYSIM01`, -//! carrying the seven agent chunks plus `emulator`, `framebuffer`, `ratchetGame` and -//! `ratchetFrame`; -//! - a commit writes `.checkpoint.tmp`, fsyncs it, renames it, fsyncs the directory, and -//! then does the same for `manifest.json`. **The manifest rename is the commit point**: a -//! crash before it leaves an unreferenced file that is never loaded; -//! - durable commits go to `save_dir` every `checkpoint_seconds` (default 300) and on every -//! event that matters; a hot copy goes to `hot_dir` (tmpfs) every `hot_seconds` (default 5); -//! - the first commit at a new best rank also writes `milestone-.checkpoint`, which later -//! rotations never unlink. +//! The code lives in the `flysim-store` crate, which the session runtime links too (STATE-02), so +//! both write byte-identical checkpoints into the same store. This module re-exports it, and every +//! `flysim::store` path keeps working. -use std::collections::BTreeMap; -use std::fs::{File, OpenOptions}; -use std::io::Write; -use std::path::{Path, PathBuf}; - -use anyhow::{Context, Result}; -use flybrain_core::envelope::{EnvelopeParts, decode_envelope, encode_envelope}; -use flybrain_core::json::JsonValue; -use serde::{Deserialize, Serialize}; - -/// Envelope magic. Chunk names stay `[a-zA-Z]+` so the TypeScript `decodeEnvelope` can read a -/// flysim checkpoint for recap and inspection tooling. -pub const MAGIC: &str = "FLYSIM01"; - -/// Chunk names flysim adds to `flybrain-core`'s `AGENT_CHUNK_NAMES`. -pub const EMULATOR_CHUNK: &str = "emulator"; -pub const FRAMEBUFFER_CHUNK: &str = "framebuffer"; -pub const RATCHET_GAME_CHUNK: &str = "ratchetGame"; -pub const RATCHET_FRAME_CHUNK: &str = "ratchetFrame"; - -/// `manifest.json`: which generations are current, and which are archived forever. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct StoreManifest { - /// Highest generation ever allocated in this store. - pub generation: u64, - /// The generation to restore first. - pub latest: Option, - /// The generation to restore if `latest` will not load. - pub previous: Option, - /// Best-rank archives, rank to generation. Their files are never rotated away. - pub archives: BTreeMap, -} - -impl StoreManifest { - fn record(&mut self, generation: u64, archive_rank: Option) { - self.generation = self.generation.max(generation); - if self.latest != Some(generation) { - self.previous = self.latest; - self.latest = Some(generation); - } - if let Some(rank) = archive_rank { - self.archives.insert(rank, generation); - } - } - - /// Generations that must survive rotation. - fn referenced(&self) -> Vec { - let mut out: Vec = self.latest.into_iter().chain(self.previous).collect(); - out.extend(self.archives.values().copied()); - out - } -} - -/// One restore candidate, in the order it should be tried. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Candidate { - pub path: PathBuf, - /// Human description for the log and for `/status`'s fallback reporting. - pub origin: String, - pub generation: Option, -} - -/// A checkpoint directory: `.checkpoint`, `milestone-.checkpoint`, `manifest.json`. -#[derive(Debug, Clone)] -pub struct Store { - dir: PathBuf, - keep_generations: usize, -} - -impl Store { - pub fn new(dir: impl Into, keep_generations: usize) -> Self { - Self { dir: dir.into(), keep_generations: keep_generations.max(1) } - } - - pub fn dir(&self) -> &Path { - &self.dir - } - - pub fn create(&self) -> Result<()> { - std::fs::create_dir_all(&self.dir) - .with_context(|| format!("creating checkpoint directory {}", self.dir.display())) - } - - pub fn manifest_path(&self) -> PathBuf { - self.dir.join("manifest.json") - } - - pub fn generation_path(&self, generation: u64) -> PathBuf { - self.dir.join(format!("{generation}.checkpoint")) - } - - pub fn archive_path(&self, rank: u32) -> PathBuf { - self.dir.join(format!("milestone-{rank}.checkpoint")) - } - - /// Read `manifest.json`, or `None` when it is absent or unreadable. - pub fn manifest(&self) -> Option { - let text = std::fs::read_to_string(self.manifest_path()).ok()?; - match serde_json::from_str(&text) { - Ok(manifest) => Some(manifest), - Err(error) => { - tracing::warn!(%error, path = %self.manifest_path().display(), "unreadable store manifest"); - None - } - } - } - - /// Highest generation the store has ever allocated, from the manifest and from the files on - /// disk (an unreferenced file from a crashed commit still counts, so a generation number is - /// never reused). - pub fn highest_generation(&self) -> u64 { - let mut highest = self.manifest().map_or(0, |manifest| manifest.generation); - if let Ok(entries) = std::fs::read_dir(&self.dir) { - for entry in entries.flatten() { - if let Some(generation) = parse_generation(&entry.file_name().to_string_lossy()) { - highest = highest.max(generation); - } - } - } - highest - } - - /// Restore candidates from this store, in order: latest, previous, then the archives by - /// descending rank. - pub fn candidates(&self, label: &str) -> Vec { - let Some(manifest) = self.manifest() else { - return Vec::new(); - }; - let mut out = Vec::new(); - for (kind, generation) in [("latest", manifest.latest), ("previous", manifest.previous)] { - if let Some(generation) = generation { - out.push(Candidate { - path: self.generation_path(generation), - origin: format!("{label} {kind} generation {generation}"), - generation: Some(generation), - }); - } - } - for (rank, generation) in manifest.archives.iter().rev() { - out.push(Candidate { - path: self.generation_path(*generation), - origin: format!("{label} archived generation {generation} (rank {rank})"), - generation: Some(*generation), - }); - out.push(Candidate { - path: self.archive_path(*rank), - origin: format!("{label} milestone archive rank {rank}"), - generation: Some(*generation), - }); - } - out.retain(|candidate| candidate.path.exists()); - out - } - - /// Write `bytes` as `generation`, commit it, archive it if `archive_rank` is set, then rotate. - /// - /// The sequence is exactly section 8's: payload tmp, fsync, rename, dir fsync, then manifest - /// tmp, fsync, rename, dir fsync. - pub fn commit( - &self, - generation: u64, - bytes: &[u8], - archive_rank: Option, - ) -> Result { - self.create()?; - write_atomic(&self.generation_path(generation), bytes)?; - if let Some(rank) = archive_rank { - write_atomic(&self.archive_path(rank), bytes)?; - } - let mut manifest = self.manifest().unwrap_or_default(); - manifest.record(generation, archive_rank); - let text = serde_json::to_vec_pretty(&manifest)?; - write_atomic(&self.manifest_path(), &text)?; - self.rotate(&manifest)?; - Ok(manifest) - } - - /// Stage a payload without committing it. Only the crash-simulation test uses this: it is - /// the state a `kill -9` between the tmp write and the rename leaves behind. - pub fn stage_for_test(&self, generation: u64, bytes: &[u8]) -> Result { - self.create()?; - let path = tmp_path(&self.generation_path(generation)); - write_and_sync(&path, bytes)?; - Ok(path) - } - - /// Remove generation files that the manifest no longer references, keeping the newest - /// `keep_generations` and never touching an archive. - fn rotate(&self, manifest: &StoreManifest) -> Result<()> { - let referenced = manifest.referenced(); - let mut generations: Vec = Vec::new(); - for entry in std::fs::read_dir(&self.dir)?.flatten() { - let name = entry.file_name().to_string_lossy().to_string(); - if let Some(generation) = parse_generation(&name) { - generations.push(generation); - } else if name.ends_with(".checkpoint.tmp") { - // A tmp file from an interrupted commit is never loadable; clean it up. - let _ = std::fs::remove_file(entry.path()); - } - } - generations.sort_unstable_by(|a, b| b.cmp(a)); - for (index, generation) in generations.iter().enumerate() { - if referenced.contains(generation) || index < self.keep_generations { - continue; - } - let path = self.generation_path(*generation); - if let Err(error) = std::fs::remove_file(&path) { - tracing::warn!(%error, path = %path.display(), "could not rotate a checkpoint"); - } - } - Ok(()) - } -} - -/// `milestone-.checkpoint` is an independent file, so it is not a generation. -fn parse_generation(name: &str) -> Option { - name.strip_suffix(".checkpoint")?.parse().ok() -} - -fn tmp_path(path: &Path) -> PathBuf { - let mut name = path.as_os_str().to_os_string(); - name.push(".tmp"); - PathBuf::from(name) -} - -/// tmp write, fsync, rename, directory fsync. -pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> { - let tmp = tmp_path(path); - write_and_sync(&tmp, bytes)?; - std::fs::rename(&tmp, path) - .with_context(|| format!("renaming {} to {}", tmp.display(), path.display()))?; - sync_dir(path.parent().unwrap_or(Path::new("."))) -} - -fn write_and_sync(path: &Path, bytes: &[u8]) -> Result<()> { - let mut file = OpenOptions::new() - .create(true) - .write(true) - .truncate(true) - .open(path) - .with_context(|| format!("creating {}", path.display()))?; - file.write_all(bytes)?; - file.flush()?; - file.sync_all().with_context(|| format!("fsync {}", path.display()))?; - Ok(()) -} - -fn sync_dir(dir: &Path) -> Result<()> { - // Opening a directory read-only and fsyncing it is what makes the rename durable. - File::open(dir) - .and_then(|file| file.sync_all()) - .with_context(|| format!("fsync directory {}", dir.display())) -} - -// --------------------------------------------------------------------------------------------- -// The envelope -// --------------------------------------------------------------------------------------------- - -/// Everything a checkpoint carries besides the agent's own chunks. -#[derive(Debug, Clone, PartialEq)] -pub struct RuntimeState { - pub generation: u64, - pub wall_ms: u64, - pub rom_sha256: String, - pub emulator_frame: u64, - pub compatibility: String, - pub speed: f64, - pub buttons: u32, - /// Simulated milliseconds at which the current milestone rank was reached. - pub rank_since_ms: f64, - pub last_event_id: u64, - /// The adapter's own lifetime reward state. - pub reward: serde_json::Value, - pub ratchet: flybrain_gb::RatchetState, - pub emulator: Vec, - pub framebuffer: Vec, - /// The ratchet's best safe snapshot, if it has one. - pub ratchet_game: Vec, - pub ratchet_frame: Vec, -} - -/// A decoded checkpoint: the agent half plus the runtime half. -#[derive(Debug, Clone)] -pub struct Checkpoint { - pub agent: flybrain_core::agent::AgentState, - pub runtime: RuntimeState, -} - -/// Encode an agent state plus the runtime state into one `FLYSIM01` envelope. -pub fn encode( - agent: &flybrain_core::agent::AgentState, - runtime: &RuntimeState, -) -> Result> { - let parts = flybrain_core::envelope::agent_to_chunks(agent); - let mut manifest = parts.manifest; - manifest.set("generation", (runtime.generation as f64).into()); - manifest.set("wallMs", (runtime.wall_ms as f64).into()); - manifest.set("romHash", runtime.rom_sha256.as_str().into()); - manifest.set("emulatorFrame", (runtime.emulator_frame as f64).into()); - manifest.set("compatibility", runtime.compatibility.as_str().into()); - manifest.set("speed", runtime.speed.into()); - manifest.set("buttons", f64::from(runtime.buttons).into()); - manifest.set("rankSinceMs", runtime.rank_since_ms.into()); - manifest.set("lastEventId", (runtime.last_event_id as f64).into()); - manifest.set("reward", to_json_value(&runtime.reward)?); - manifest.set("ratchet", to_json_value(&serde_json::to_value(runtime.ratchet)?)?); - - let mut chunks = parts.chunks; - chunks.push((EMULATOR_CHUNK.to_string(), runtime.emulator.clone())); - chunks.push((FRAMEBUFFER_CHUNK.to_string(), runtime.framebuffer.clone())); - chunks.push((RATCHET_GAME_CHUNK.to_string(), runtime.ratchet_game.clone())); - chunks.push((RATCHET_FRAME_CHUNK.to_string(), runtime.ratchet_frame.clone())); - - encode_envelope(MAGIC, &manifest, &chunks).map_err(|error| anyhow::anyhow!("{error}")) -} - -/// Decode and structurally validate a `FLYSIM01` envelope. -/// -/// Value-level validation belongs to the importers: `NeuralAgent::import_state` is -/// self-validating and a no-op on failure, and `Ratchet::import` rejects an impossible state. -pub fn decode(bytes: &[u8]) -> Result { - let parts: EnvelopeParts = - decode_envelope(bytes, MAGIC).map_err(|error| anyhow::anyhow!("{error}"))?; - let manifest = parts.manifest.clone(); - let agent = flybrain_core::envelope::agent_from_chunks(&manifest, &parts) - .map_err(|error| anyhow::anyhow!("{error}"))?; - - let string = |key: &str| -> Result { - manifest - .get(key) - .and_then(JsonValue::as_str) - .map(str::to_string) - .ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}")) - }; - let number = |key: &str| -> Result { - manifest - .get(key) - .and_then(JsonValue::as_f64) - .ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}")) - }; - let chunk = |name: &str| -> Result> { - parts - .chunk(name) - .map(<[u8]>::to_vec) - .ok_or_else(|| anyhow::anyhow!("checkpoint is missing the {name} chunk")) - }; - - let ratchet_json = manifest - .get("ratchet") - .ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing ratchet"))?; - let ratchet: flybrain_gb::RatchetState = serde_json::from_str(&ratchet_json.stringify()) - .context("checkpoint ratchet state is not readable")?; - let reward = manifest - .get("reward") - .map(|value| serde_json::from_str(&value.stringify())) - .transpose() - .context("checkpoint reward state is not readable")? - .unwrap_or(serde_json::Value::Null); - - Ok(Checkpoint { - agent, - runtime: RuntimeState { - generation: number("generation")? as u64, - wall_ms: number("wallMs")? as u64, - rom_sha256: string("romHash")?, - emulator_frame: number("emulatorFrame")? as u64, - compatibility: string("compatibility")?, - speed: number("speed")?, - buttons: number("buttons")? as u32, - rank_since_ms: number("rankSinceMs").unwrap_or(0.0), - last_event_id: number("lastEventId").unwrap_or(0.0) as u64, - reward, - ratchet, - emulator: chunk(EMULATOR_CHUNK)?, - framebuffer: chunk(FRAMEBUFFER_CHUNK)?, - ratchet_game: chunk(RATCHET_GAME_CHUNK)?, - ratchet_frame: chunk(RATCHET_FRAME_CHUNK)?, - }, - }) -} - -/// Read and decode a candidate, so a caller can try the next one on any failure. -pub fn load(path: &Path) -> Result { - let bytes = - std::fs::read(path).with_context(|| format!("reading checkpoint {}", path.display()))?; - decode(&bytes).with_context(|| format!("decoding checkpoint {}", path.display())) -} - -fn to_json_value(value: &serde_json::Value) -> Result { - JsonValue::parse(&serde_json::to_string(value)?).map_err(|error| anyhow::anyhow!("{error}")) -} - -/// The restore order: the tmpfs hot copy first, then the durable store. -/// -/// The hot copy is written every few seconds and the durable one every few minutes, so the hot -/// copy is normally the newest state that exists; it is a first-class candidate because it uses -/// the identical envelope and the identical atomic sequence, and not a partial dump. -/// The compatibility string the newest decodable checkpoint in `dir` carries, if any. -/// -/// The store's own `manifest.json` is only an index (generation, latest, previous, archives) — -/// the compatibility string lives in each checkpoint's own `FLYSIM01` envelope manifest, so -/// answering "what will this build refuse?" means decoding a checkpoint. Candidates are tried -/// newest first and a corrupt one is skipped, which is the same order and the same tolerance -/// `Sim::boot` restores with. -/// -/// `flysim --print-state-compatibility DIR` is this, and `infra/05-deploy.sh` compares its -/// answer with `--print-compatibility` before flipping the `current` symlink. -pub fn state_compatibility(dir: &Path) -> Option { - let store = Store::new(dir, 8); - for candidate in store.candidates("durable") { - if let Ok(checkpoint) = load(&candidate.path) { - return Some(checkpoint.runtime.compatibility); - } - } - None -} - -pub fn restore_order(hot: &Store, durable: &Store) -> Vec { - let mut out = hot.candidates("hot"); - out.extend(durable.candidates("durable")); - out -} - -#[cfg(test)] -mod tests { - use super::*; - - fn runtime(generation: u64) -> RuntimeState { - RuntimeState { - generation, - wall_ms: 1_700_000_000_000, - rom_sha256: "ab".repeat(32), - emulator_frame: 12_345, - compatibility: "kernel/adapter/fingerprint".to_string(), - speed: 1.0, - buttons: 0b0001_0000, - rank_since_ms: 4_242.0, - last_event_id: 77, - reward: serde_json::json!({ "version": 3, "total": 1.25 }), - ratchet: flybrain_gb::RatchetState { best: 3, ..Default::default() }, - emulator: vec![7; 64], - framebuffer: vec![9; 32], - ratchet_game: vec![1, 2, 3], - ratchet_frame: vec![4, 5, 6], - } - } - - fn agent_state() -> flybrain_core::agent::AgentState { - use flybrain_core::decoder::DecoderState; - use flybrain_core::lif::LifState; - use flybrain_core::ordered::NumberMap; - use flybrain_core::plasticity::PlasticityState; - flybrain_core::agent::AgentState { - version: 1, - remainder: 0.75, - warmed_up: true, - network: LifState { - membrane: vec![0.5, -0.25], - refractory: vec![0, 3], - last_spike_ms: vec![-1_000_000.0, 12.0], - visual_drive: vec![0.1], - rng: -12_345, - reward_remaining: 40.0, - ms: 9_000.0, - population_rate: 1.5, - rates: NumberMap::from_pairs([("forward", 2.0), ("reward_pam", 0.5)]), - plasticity: PlasticityState { - version: "fly-kc-mbon-rstdp-v2".to_string(), - topology: 42, - enabled: true, - updates: 3.0, - signal: 0.25, - gains: vec![1.0, 0.9], - traces: vec![0.0, 0.1], - touched: vec![0.0, 8_000.0], - }, - }, - decoder: DecoderState { - version: 4, - calibrated: true, - baseline: NumberMap::from_pairs([("forward", 1.0)]), - held_until: NumberMap::new(), - next_allowed: NumberMap::new(), - next_decision: 100.0, - current: Some("a".to_string()), - fatigue: NumberMap::new(), - macro_next_decision: 0.0, - macro_current: None, - macro_fatigue: NumberMap::new(), - }, - } - } - - #[test] - fn the_envelope_round_trips_every_field_and_chunk() { - let agent = agent_state(); - let runtime = runtime(4); - let bytes = encode(&agent, &runtime).unwrap(); - assert!(bytes.starts_with(MAGIC.as_bytes())); - - let back = decode(&bytes).unwrap(); - assert_eq!(back.agent, agent); - assert_eq!(back.runtime, runtime); - - // Re-encoding the decoded state is byte-identical, so a restore-and-save cycle is stable. - assert_eq!(encode(&back.agent, &back.runtime).unwrap(), bytes); - } - - #[test] - fn a_corrupted_or_truncated_envelope_is_rejected() { - let bytes = encode(&agent_state(), &runtime(1)).unwrap(); - assert!(decode(&bytes[..bytes.len() - 1]).is_err(), "truncated"); - - let mut flipped = bytes.clone(); - let middle = flipped.len() / 2; - flipped[middle] ^= 0xff; - assert!(decode(&flipped).is_err(), "checksum"); - - let mut trailing = bytes.clone(); - trailing.push(0); - assert!(decode(&trailing).is_err(), "trailing bytes"); - - let mut wrong_magic = bytes; - wrong_magic[0] = b'X'; - assert!(decode(&wrong_magic).is_err(), "magic"); - } - - #[test] - fn a_commit_is_atomic_and_a_crash_before_the_rename_leaves_a_loadable_store() { - let dir = tempfile::tempdir().unwrap(); - let store = Store::new(dir.path(), 2); - let first = encode(&agent_state(), &runtime(1)).unwrap(); - store.commit(1, &first, None).unwrap(); - - // kill -9 between the tmp write and the rename. - let mut broken = encode(&agent_state(), &runtime(2)).unwrap(); - broken.truncate(broken.len() / 2); - let staged = store.stage_for_test(2, &broken).unwrap(); - assert!(staged.exists()); - - let manifest = store.manifest().unwrap(); - assert_eq!(manifest.latest, Some(1)); - let candidates = store.candidates("durable"); - assert_eq!(candidates.len(), 1, "the staged tmp file is not a candidate: {candidates:?}"); - assert_eq!(load(&candidates[0].path).unwrap().runtime.generation, 1); - - // The next successful commit cleans the orphan up. - let second = encode(&agent_state(), &runtime(3)).unwrap(); - store.commit(3, &second, None).unwrap(); - assert!(!staged.exists()); - assert_eq!(store.manifest().unwrap().latest, Some(3)); - assert_eq!(store.manifest().unwrap().previous, Some(1)); - } - - #[test] - fn a_payload_renamed_without_its_manifest_is_never_loaded() { - let dir = tempfile::tempdir().unwrap(); - let store = Store::new(dir.path(), 2); - store.commit(1, &encode(&agent_state(), &runtime(1)).unwrap(), None).unwrap(); - - // The payload rename succeeded, the manifest rename did not: the commit point is the - // manifest, so generation 2 is invisible. - write_atomic(&store.generation_path(2), b"not even an envelope").unwrap(); - let candidates = store.candidates("durable"); - assert_eq!(candidates.len(), 1); - assert_eq!(candidates[0].generation, Some(1)); - assert_eq!(store.highest_generation(), 2, "but the number is not reused"); - } - - #[test] - fn the_restore_order_is_hot_then_durable_then_archives_by_descending_rank() { - let dir = tempfile::tempdir().unwrap(); - let durable = Store::new(dir.path().join("durable"), 2); - let hot = Store::new(dir.path().join("hot"), 2); - let bytes = encode(&agent_state(), &runtime(1)).unwrap(); - - durable.commit(1, &bytes, Some(1)).unwrap(); - durable.commit(2, &bytes, Some(4)).unwrap(); - durable.commit(3, &bytes, None).unwrap(); - hot.commit(7, &bytes, None).unwrap(); - - let order: Vec = - restore_order(&hot, &durable).into_iter().map(|c| c.origin).collect(); - assert_eq!( - order, - vec![ - "hot latest generation 7", - "durable latest generation 3", - "durable previous generation 2", - "durable archived generation 2 (rank 4)", - "durable milestone archive rank 4", - "durable archived generation 1 (rank 1)", - "durable milestone archive rank 1", - ] - ); - } - - #[test] - fn rotation_keeps_the_referenced_generations_and_never_unlinks_an_archive() { - let dir = tempfile::tempdir().unwrap(); - let store = Store::new(dir.path(), 2); - let bytes = encode(&agent_state(), &runtime(1)).unwrap(); - store.commit(1, &bytes, Some(2)).unwrap(); - for generation in 2..=6 { - store.commit(generation, &bytes, None).unwrap(); - } - assert!(store.generation_path(6).exists(), "latest"); - assert!(store.generation_path(5).exists(), "previous"); - assert!(store.generation_path(1).exists(), "archived generation"); - assert!(store.archive_path(2).exists(), "milestone archive"); - assert!(!store.generation_path(3).exists(), "rotated away"); - assert!(!store.generation_path(4).exists(), "rotated away"); - } - - #[test] - fn an_empty_or_manifestless_directory_offers_no_candidates() { - let dir = tempfile::tempdir().unwrap(); - let store = Store::new(dir.path().join("missing"), 2); - assert!(store.candidates("durable").is_empty()); - assert_eq!(store.highest_generation(), 0); - - let store = Store::new(dir.path(), 2); - store.create().unwrap(); - std::fs::write(store.manifest_path(), "{ not json").unwrap(); - assert!(store.candidates("durable").is_empty(), "an unreadable manifest is not fatal"); - } -} +pub use flysim_store::store::*; From 9c98281f4a1b66b22d1ba40593180d0f24f08847 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 16:26:07 +0000 Subject: [PATCH 21/26] fly-session: legacy_checkpoint, the session runtime's FLYSIM01 export, import, store policy and restore selection (STATE-02) The export assembles a FLYSIM01 file from the agent's FLYAGT01 and the world's FLYENV01 capture payloads, the task's {reward, ratchet} and the host's fields, through flysim-store's encoder. The import reads a file back into those halves. The agent payload is the shipped form of AGENT-01's prototype: learning.updates starts at plasticity.updates, and the file's framebuffer goes in an inputFrame chunk that StageRestore installs, as the legacy restore does. LegacyCheckpointer keeps the legacy loop's generations, hot and durable intervals, per-process milestone archives and writer thread. restore_from_store walks the legacy candidate order and takes the next candidate on any refusal. The agent worker's payload encoder is now one shared function, and legacy_parity seeds through the shipped import. --- services/flysim/Cargo.lock | 1 + services/flysim/crates/fly-session/Cargo.toml | 2 + services/flysim/crates/fly-session/README.md | 1 + .../crates/fly-session/src/legacy_agent.rs | 139 +- .../fly-session/src/legacy_checkpoint.rs | 1151 +++++++++++++++++ .../crates/fly-session/src/legacy_parity.rs | 100 +- services/flysim/crates/fly-session/src/lib.rs | 1 + 7 files changed, 1319 insertions(+), 76 deletions(-) create mode 100644 services/flysim/crates/fly-session/src/legacy_checkpoint.rs diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index d356eee..3c6e925 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -444,6 +444,7 @@ dependencies = [ "flybrain-core", "flybrain-gb", "flybus", + "flysim-store", "serde_json", "tempfile", "tokio", diff --git a/services/flysim/crates/fly-session/Cargo.toml b/services/flysim/crates/fly-session/Cargo.toml index ee1e7d4..1af661b 100644 --- a/services/flysim/crates/fly-session/Cargo.toml +++ b/services/flysim/crates/fly-session/Cargo.toml @@ -32,6 +32,8 @@ flybrain-core = { path = "../flybrain-core" } flybrain-gb = { path = "../flybrain-gb" } # The toy connectome fixture is written as gzipped `.binz` arrays, the dataset loader's format. flate2 = { workspace = true } +# STATE-02: the FLYSIM01 store and the sugar journal, the same code the legacy loop writes with. +flysim-store = { path = "../flysim-store" } serde_json = { workspace = true } # `rt-multi-thread` is not only for the tests: a worker process and a dedicated-thread diff --git a/services/flysim/crates/fly-session/README.md b/services/flysim/crates/fly-session/README.md index 46ef664..639ae58 100644 --- a/services/flysim/crates/fly-session/README.md +++ b/services/flysim/crates/fly-session/README.md @@ -49,6 +49,7 @@ Ready(k) ─ Prepare all agents concurrently ─────────── | `harness` | The runnable composition: router, the flies, one arena, one coordinator | | `legacy_env` | ENV-01: the legacy Game Boy environment worker over binjgb -- the one-frame setup scaffold, the joypad batch, `f32le` audio, the per-boundary memory image, `gameboy-slots-v1`, the capture payload and the world's half of `FLYSIM01` | | `legacy_env_parity` | ENV-01's parity harness: the toy cartridge, recorded scripts, the emulator driven directly in `LegacyFrame` order, the worker driven over the bus, and the replay of the service's own `FLY_TRACE` | +| `legacy_checkpoint` | STATE-02: the legacy composition's `FLYSIM01` checkpoints -- the export from the agent's and the world's capture payloads plus the task's and the host's halves, the import back (with the `learning.updates` rule), the legacy store policy (generations, hot/durable intervals, milestone archives) and the restore selection over the live store. The store code is the `flysim-store` crate, shared with `flysim` | ## Execution modes and the launcher diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index a846993..876fc8c 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -73,6 +73,10 @@ f767d48ff556fceae996e2ac73c0d0871df71101db0af414a0ffcd0bfb678489:\ /// The magic of the agent's capture payload: a `flybrain-core` checkpoint envelope whose /// manifest and chunks are exactly `agent_to_chunks`, plus one `session` manifest member. pub const PAYLOAD_MAGIC: &str = "FLYAGT01"; +/// An optional payload chunk: the frame to install as the next input when the payload is +/// staged. Only the `FLYSIM01` import writes it (STATE-02), because the legacy restore +/// re-projects the saved framebuffer rather than trusting the saved visual drive. +pub const INPUT_FRAME_CHUNK: &str = "inputFrame"; /// The layout version of the `session` member. pub const PAYLOAD_VERSION: u64 = 1; /// The attachment a Commit reply carries the transition's spike bitset under. @@ -243,6 +247,79 @@ pub fn rational_remainder_to_legacy(remainder: &RationalNs) -> Result { + pub agent_id: &'a Id, + pub checkpoint_id: &'a Id, + pub source_scope: &'a Scope, + pub committed_step: u64, + pub profile: &'a AssetRef, + pub seed: i32, + /// Reinforcement calls applied since the fly's fresh start (`learning.updates`). + pub reinforcements: u64, + /// The composition's `executor.macroChannels`, in composition order; empty in raw mode. + pub macro_channels: &'a [String], +} + +/// Encodes a `FLYAGT01` capture payload: `agent_to_chunks(state)` in `flybrain-core`'s envelope, +/// plus the `session` manifest member `State.StageRestore` reads back. `state.remainder` must +/// already be the accumulator's, as a capture sets it. +/// +/// The worker's own `State.Capture` writes exactly this, and so does the `FLYSIM01` import +/// (`crate::legacy_checkpoint`), which is why it is one function. +pub fn encode_payload( + state: &AgentState, + identity: &PayloadIdentity<'_>, + accumulator: &TickAccumulator, + context: &TypedValue, + input_frame: Option<&[u8]>, +) -> Result, String> { + let mut chunks = agent_to_chunks(state); + if let Some(frame) = input_frame { + chunks.chunks.push((INPUT_FRAME_CHUNK.to_owned(), frame.to_vec())); + } + let channels: Vec<&str> = identity.macro_channels.iter().map(String::as_str).collect(); + let session = json!({ + "payloadVersion": PAYLOAD_VERSION, + "kind": "legacy-agent", + "agentId": identity.agent_id, + "checkpointId": identity.checkpoint_id, + "sourceScope": identity.source_scope.to_json(), + "committedStep": identity.committed_step.to_string(), + "profile": identity.profile.to_json(), + "seed": identity.seed, + "reinforcements": identity.reinforcements.to_string(), + "kernelVersion": gameboy::KERNEL_VERSION, + "plasticityVersion": gameboy::PLASTICITY_VERSION, + "macroChannels": identity.macro_channels, + "decoderConfigDigest": decoder_config_digest(&gameboy_decoder_config_with_macros(&channels)), + "accumulator": { + "tickDuration": accumulator.tick_duration().to_json(), + "remainder": accumulator.remainder().to_json(), + "executedTicks": accumulator.executed_ticks().to_string(), + "warmupOffset": accumulator.warmup_offset().to_string(), + }, + "context": context.to_json(), + }); + let mut manifest = chunks.manifest; + let session = JsonValue::parse(&session.to_string()).map_err(|e| e.to_string())?; + manifest.set("session", session); + encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string()) +} + +/// The agent state a `FLYAGT01` capture payload carries, with the accumulator's remainder in it. +/// The `session` member is not validated here; `State.StageRestore` does that. +pub fn decode_payload_state(bytes: &[u8]) -> Result { + let parts = decode_envelope(bytes, PAYLOAD_MAGIC) + .map_err(|e| format!("not a {PAYLOAD_MAGIC} envelope: {e}"))?; + agent_from_chunks(&parts.manifest, &parts).map_err(|e| e.to_string()) +} + // ------------------------------------------------------------------------------------------- // The readout transient @@ -1191,43 +1268,23 @@ impl LegacyAgentWorker { // The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`). state.remainder = rational_remainder_to_legacy(&accumulator.remainder()) .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?; - let chunks = agent_to_chunks(&state); - let channels: Vec<&str> = self - .config - .macro_channels - .iter() - .map(String::as_str) - .collect(); - let session = json!({ - "payloadVersion": PAYLOAD_VERSION, - "kind": "legacy-agent", - "agentId": self.config.agent_id, - "checkpointId": checkpoint_id, - "sourceScope": scope.to_json(), - "committedStep": k.to_string(), - "profile": self.profile.asset.to_json(), - "seed": self.seed, - "reinforcements": self.reinforcements.to_string(), - "kernelVersion": gameboy::KERNEL_VERSION, - "plasticityVersion": gameboy::PLASTICITY_VERSION, - "macroChannels": self.config.macro_channels, - "decoderConfigDigest": decoder_config_digest(&gameboy_decoder_config_with_macros(&channels)), - "accumulator": { - "tickDuration": accumulator.tick_duration().to_json(), - "remainder": accumulator.remainder().to_json(), - "executedTicks": accumulator.executed_ticks().to_string(), - "warmupOffset": accumulator.warmup_offset().to_string(), + encode_payload( + &state, + &PayloadIdentity { + agent_id: &self.config.agent_id, + checkpoint_id, + source_scope: scope, + committed_step: k, + profile: &self.profile.asset, + seed: self.seed, + reinforcements: self.reinforcements, + macro_channels: &self.config.macro_channels, }, - "context": context.typed.to_json(), - }); - let mut manifest = chunks.manifest; - let session = JsonValue::parse(&session.to_string()).map_err(|e| { - DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None) - })?; - manifest.set("session", session); - encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| { - DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None) - }) + accumulator, + &context.typed, + None, + ) + .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None)) } async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { @@ -1493,6 +1550,16 @@ impl LegacyAgentWorker { agent .import_state(&state) .map_err(|e| incompatible(format!("the agent state does not import: {e}")))?; + // A payload imported from `FLYSIM01` carries the frame on screen as its next input, and + // the restore installs it, as `LegacyFrame::restore` re-projects the saved framebuffer + // (`legacy_checkpoint::agent_payload`). A worker's own capture carries none. + if let Some(frame) = parts.chunk(INPUT_FRAME_CHUNK) { + let (width, height) = (agent.frame.width, agent.frame.height); + if frame.len() != width as usize * height as usize * 4 { + return Err(incompatible("the staged input frame is not the profile's view")); + } + agent.network.set_visual_frame(frame, width, height); + } if let Some(staged) = &self.staged { return Err(DomainError::before( ErrorCode::Conflict, diff --git a/services/flysim/crates/fly-session/src/legacy_checkpoint.rs b/services/flysim/crates/fly-session/src/legacy_checkpoint.rs new file mode 100644 index 0000000..8ff27ad --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_checkpoint.rs @@ -0,0 +1,1151 @@ +//! STATE-02: the legacy Game Boy composition's checkpoints, in `FLYSIM01`, the format of record. +//! +//! `legacy-gameboy-v1` section 16 and the operator's decision of 2026-09-23: `FLYSIM01` stays +//! the format of record until RETIRE-01, and the session runtime exports a `FLYSIM01` envelope on +//! every durable save, which the current `flysim` reads under its unchanged compatibility string. +//! The deploy gate, `fly-reset-to-milestone` and `fly-loop-reset` keep working on those files. This +//! module is that export, the import back, the store policy around them and the restore selection: +//! +//! | `FLYSIM01` | Owner in the session runtime | Here | +//! | --- | --- | --- | +//! | the seven agent chunks and `remainder` | the agent (`FLYAGT01` capture payload) | [`agent_state`], [`agent_payload`] | +//! | `emulator`, `framebuffer`, `emulatorFrame`, `buttons`, `romHash`, `ratchetGame`, `ratchetFrame` | the environment (`FLYENV01`; the ratchet's snapshot is slot `best`) | [`world_state`], [`world_payload`] | +//! | `reward`, `ratchet` | the task's ledger | [`TaskHalf`] | +//! | `generation`, `wallMs`, `compatibility`, `speed`, `rankSinceMs`, `lastEventId` | the host (store, feed, rank tracking) | [`HostHalf`], [`LegacyCheckpointer`] | +//! +//! **Byte compatibility is by construction.** The envelope is written by +//! `flysim_store::store::encode`, the one function the legacy loop writes with, from the same +//! values: [`export`] builds a `RuntimeState` field for field as `Sim::snapshot_state` does. The +//! store is `flysim_store::store::Store`, so generations, `manifest.json`, `milestone-` +//! archives, `keep_generations` rotation and the restore order are the legacy store's own code. +//! The tests prove the rest on real checkpoints: legacy -> session -> legacy and session -> +//! legacy -> session round trips, and restore-then-continue against the legacy loop's +//! `FLY_TRACE`. +//! +//! **Restore is `legacy-transient-reset`** (`legacy-gameboy-v1` section 14): what `FLYSIM01` +//! carries is restored; the executor's ledgers, the running macro, the readout transient and the +//! adapter's transient observations are not in it and start cleared. +//! +//! **Declared difference, archive order** (`legacy-gameboy-v1` sections 4 and 16, operator +//! 2026-09-23): a milestone archive written by the session runtime is captured *after* that +//! boundary's slot save, so it holds the post-capture ratchet and slot (`best = r`, rung `r`'s +//! snapshot), where the legacy loop's holds `best = r-1` and rung `r-1`'s. Both are ordinary +//! `FLYSIM01` files and each runtime restores the other's. + +use std::sync::mpsc; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use fly_session_types::gameboy; +use flybrain_core::agent::AgentState; +use flybrain_gb::RatchetState; +use flysim_store::store::{self, Candidate, Checkpoint, RuntimeState, Store}; +use serde_json::Value; +use tokio::sync::oneshot; + +use crate::clock::TickAccumulator; +use crate::legacy_agent::{self, PayloadIdentity, legacy_remainder_to_rational}; +use crate::legacy_env::{Flysim01World, PayloadHeader, WorldState}; +use crate::types::*; + +pub use flysim_store::journal; +pub use flysim_store::store as flysim01; + +/// The source epoch of a payload made from a `FLYSIM01` file: the legacy file has no session +/// identity, so the imported payloads say where they came from rather than invent one. +pub const LEGACY_SOURCE_EPOCH: &str = "legacy"; + +// ------------------------------------------------------------------------------------------- +// The halves + +/// The task's half of a `FLYSIM01` checkpoint: the manifest members `reward` and `ratchet`. +/// +/// This is the `pokered-macros-v1` task ledger (`legacy-gameboy-v1` section 10: "the adapter +/// state (FLYSIM01's `reward` chunk) and the ratchet state"). The executor's ledgers are not in +/// it (`legacy-transient-reset`). +#[derive(Clone, Debug, PartialEq)] +pub struct TaskHalf { + /// `GameAdapter::export_state`, exactly as `FLYSIM01` records it; `null` for an adapter that + /// has none, which a restore then leaves alone. + pub reward: Value, + pub ratchet: RatchetState, +} + +impl TaskHalf { + /// `{reward, ratchet, slotFilled}`: the ledger value the task captures and installs. + /// `slotFilled` says whether the ratchet has a snapshot, which lives in the environment's + /// slot `best`; it is derived, never stored in `FLYSIM01`. + pub fn to_ledger(&self, slot_filled: bool) -> Value { + serde_json::json!({ + "reward": self.reward, + "ratchet": serde_json::to_value(self.ratchet).expect("a ratchet state serializes"), + "slotFilled": slot_filled, + }) + } + + pub fn from_ledger(value: &Value) -> Result { + let ratchet = value.get("ratchet").ok_or("the task ledger has no ratchet")?; + Ok(TaskHalf { + reward: value.get("reward").cloned().unwrap_or(Value::Null), + ratchet: serde_json::from_value(ratchet.clone()) + .map_err(|e| format!("the task ledger's ratchet: {e}"))?, + }) + } +} + +/// The host's half: what neither the agent, the world nor the task owns. +#[derive(Clone, Debug, PartialEq)] +pub struct HostHalf { + pub generation: u64, + pub wall_ms: u64, + /// The legacy compatibility string (`flysim --print-compatibility`), recorded, not + /// reinterpreted; it is still the restore gate (`legacy-gameboy-v1` section 12). + pub compatibility: String, + pub speed: f64, + /// Brain milliseconds at which the current ladder rank was reached. + pub rank_since_ms: f64, + /// The feed event log's watermark: the last event id issued. + pub last_event_id: u64, +} + +/// A `FLYSIM01` checkpoint read into its owners' halves. +#[derive(Clone, Debug)] +pub struct Halves { + pub agent: AgentState, + pub world: WorldState, + pub task: TaskHalf, + pub host: HostHalf, +} + +// ------------------------------------------------------------------------------------------- +// Export + +/// The agent state a `FLYAGT01` capture payload carries (its remainder is the accumulator's). +pub fn agent_state(agent_payload: &[u8]) -> Result { + legacy_agent::decode_payload_state(agent_payload) +} + +/// The world a `FLYENV01` capture payload carries. +pub fn world_state(world_payload: &[u8]) -> Result { + WorldState::decode(world_payload).map(|(_, state)| state) +} + +/// The `FLYSIM01` runtime fields of one boundary, exactly as `Sim::snapshot_state` fills them. +pub fn runtime_state( + world: &WorldState, + slot_id: &Id, + task: &TaskHalf, + host: &HostHalf, +) -> RuntimeState { + let Flysim01World { + rom_hash, + emulator_frame, + buttons, + emulator, + framebuffer, + ratchet_game, + ratchet_frame, + } = world.flysim01_chunks(slot_id); + RuntimeState { + generation: host.generation, + wall_ms: host.wall_ms, + rom_sha256: rom_hash, + emulator_frame, + compatibility: host.compatibility.clone(), + speed: host.speed, + buttons, + rank_since_ms: host.rank_since_ms, + last_event_id: host.last_event_id, + reward: task.reward.clone(), + ratchet: task.ratchet, + emulator, + framebuffer, + ratchet_game, + ratchet_frame, + } +} + +/// The `FLYSIM01` envelope of one boundary, from the agent's state, the world, the task's half +/// and the host's. +pub fn export_states( + agent: &AgentState, + world: &WorldState, + slot_id: &Id, + task: &TaskHalf, + host: &HostHalf, +) -> Result, String> { + store::encode(agent, &runtime_state(world, slot_id, task, host)).map_err(|e| format!("{e:#}")) +} + +/// The `FLYSIM01` envelope of one boundary, from the two participants' capture payloads. +pub fn export( + agent_payload: &[u8], + world_payload: &[u8], + slot_id: &Id, + task: &TaskHalf, + host: &HostHalf, +) -> Result, String> { + let agent = agent_state(agent_payload)?; + let world = world_state(world_payload)?; + export_states(&agent, &world, slot_id, task, host) +} + +// ------------------------------------------------------------------------------------------- +// Import + +/// Reads a decoded `FLYSIM01` checkpoint into its owners' halves. The world is at boundary +/// `emulatorFrame - setupFrames` with the ratchet's snapshot as slot `slot_id`. +pub fn halves( + checkpoint: &Checkpoint, + episode_id: &Id, + slot_id: &Id, + audio_sample_rate: u64, +) -> Result { + let runtime = &checkpoint.runtime; + let world = Flysim01World { + rom_hash: runtime.rom_sha256.clone(), + emulator_frame: runtime.emulator_frame, + buttons: runtime.buttons, + emulator: runtime.emulator.clone(), + framebuffer: runtime.framebuffer.clone(), + ratchet_game: runtime.ratchet_game.clone(), + ratchet_frame: runtime.ratchet_frame.clone(), + } + .into_state(episode_id, slot_id, audio_sample_rate)?; + Ok(Halves { + agent: checkpoint.agent.clone(), + world, + task: TaskHalf { + reward: runtime.reward.clone(), + ratchet: runtime.ratchet, + }, + host: HostHalf { + generation: runtime.generation, + wall_ms: runtime.wall_ms, + compatibility: runtime.compatibility.clone(), + speed: runtime.speed, + rank_since_ms: runtime.rank_since_ms, + last_event_id: runtime.last_event_id, + }, + }) +} + +/// Decodes `FLYSIM01` bytes into halves. +pub fn split( + bytes: &[u8], + episode_id: &Id, + slot_id: &Id, + audio_sample_rate: u64, +) -> Result { + let checkpoint = store::decode(bytes).map_err(|e| format!("{e:#}"))?; + halves(&checkpoint, episode_id, slot_id, audio_sample_rate) +} + +/// The reinforcement calls to start a legacy agent state's `learning.updates` at. +/// +/// `FLYSIM01` records `plasticity.updates`, the reinforcements that moved a gain, but not every +/// call, and the contract requires `learning.changed <= learning.updates`. An import that starts +/// the call count at zero makes the first telemetry unreadable (found by AGENT-01 on the row-58 +/// stream checkpoint: `changed` is in the thousands), so it starts at the recorded count, a +/// lower bound on the calls actually made (`legacy-gameboy-v1` section 13, amendment of +/// 2026-09-29). +pub fn legacy_reinforcements(state: &AgentState) -> u64 { + state.network.plasticity.updates as u64 +} + +/// The session accumulator of a legacy agent state: its exact remainder, every tick it has run +/// (`network.ms`, warm-up included) and the profile's warm-up as the offset. +pub fn legacy_accumulator(state: &AgentState) -> Result { + let ms = state.network.ms; + if !ms.is_finite() || ms < 0.0 || ms.fract() != 0.0 { + return Err(format!("the agent's brain clock {ms} ms is not a whole tick count")); + } + let ticks = ms as u64; + let warmup = if state.warmed_up { gameboy::WARMUP_MS.min(ticks) } else { 0 }; + TickAccumulator::restored( + gameboy::tick_duration(), + legacy_remainder_to_rational(state.remainder)?, + ticks, + warmup, + ) +} + +/// What the agent's imported payload is stamped with besides its state. +#[derive(Clone, Debug)] +pub struct AgentImport { + pub agent_id: Id, + pub profile: AssetRef, + pub seed: i32, + pub macro_channels: Vec, +} + +/// A `FLYAGT01` payload for `State.StageRestore` from a legacy agent state, the shipped form of +/// AGENT-01's `seed_from_legacy_state` prototype. `context` is the decision context the task +/// gives the restored agent for its next Prepare (`{boot, bound, location}` after the executor +/// observed the restored world). `frame_on_screen` is the file's `framebuffer`: the restore +/// installs it as the next input, as `LegacyFrame::restore` does, so a file whose saved visual +/// drive is not its framebuffer's projection (a survey checkpoint, say) restores to the legacy +/// outcome and not to its own bytes (`legacy-gameboy-v1` section 16 amendment of 2026-09-29). +pub fn agent_payload( + state: &AgentState, + frame_on_screen: &[u8], + import: &AgentImport, + checkpoint_id: &Id, + source_scope: &Scope, + context: &TypedValue, +) -> Result, String> { + let accumulator = legacy_accumulator(state)?; + legacy_agent::encode_payload( + state, + &PayloadIdentity { + agent_id: &import.agent_id, + checkpoint_id, + source_scope, + committed_step: source_scope.step, + profile: &import.profile, + seed: import.seed, + reinforcements: legacy_reinforcements(state), + macro_channels: &import.macro_channels, + }, + &accumulator, + context, + Some(frame_on_screen), + ) +} + +/// A `FLYENV01` payload for `State.StageRestore` from a world read out of `FLYSIM01`. +pub fn world_payload( + world: &WorldState, + worker_id: &Id, + checkpoint_id: &Id, + source_scope: &Scope, + configuration_digest: &Digest, +) -> Vec { + world.encode(&PayloadHeader { + worker_id: worker_id.clone(), + checkpoint_id: checkpoint_id.clone(), + source_scope: source_scope.clone(), + configuration_digest: configuration_digest.clone(), + }) +} + +/// The scope a payload made from a `FLYSIM01` file records as its source: the session, the +/// [`LEGACY_SOURCE_EPOCH`] and the world's boundary. +pub fn legacy_source_scope(session_id: &Id, boundary: u64) -> Scope { + scope_at(session_id, LEGACY_SOURCE_EPOCH, boundary) +} + +// ------------------------------------------------------------------------------------------- +// Restore selection + +/// What a candidate must be to be restored: the legacy loop's `try_restore` gate. +#[derive(Clone, Debug)] +pub struct RestoreGate { + pub rom_sha256: String, + /// This build's compatibility string. + pub compatibility: String, + /// The adapter ids this build's adapter migrates from (`GameAdapter::migrates_from`). + pub migrates_from: Vec, + /// `FLY_ACCEPT_ADAPTERS`, parsed (`flybrain_gb::compatibility::accepted_adapters`). + pub accepted: Vec, +} + +impl RestoreGate { + /// The gate with `FLY_ACCEPT_ADAPTERS` read from the process environment, as `try_restore` + /// reads it: a property of a deploy, not of a run. + pub fn from_env(rom_sha256: &str, compatibility: &str, migrates_from: &[&str]) -> RestoreGate { + RestoreGate { + rom_sha256: rom_sha256.to_owned(), + compatibility: compatibility.to_owned(), + migrates_from: migrates_from.iter().map(|s| (*s).to_owned()).collect(), + accepted: flybrain_gb::compatibility::accepted_adapters( + std::env::var(flybrain_gb::compatibility::ACCEPT_ADAPTERS_ENV).ok().as_deref(), + ), + } + } + + /// `Ok` for a restorable checkpoint (with the adapter it migrates from, if any), or why not. + pub fn check(&self, checkpoint: &Checkpoint) -> Result, String> { + let runtime = &checkpoint.runtime; + if runtime.rom_sha256 != self.rom_sha256 { + return Err(format!("checkpoint is for another cartridge ({})", runtime.rom_sha256)); + } + let migrates: Vec<&str> = self.migrates_from.iter().map(String::as_str).collect(); + match flybrain_gb::compatibility::decide( + &runtime.compatibility, + &self.compatibility, + &migrates, + &self.accepted, + ) { + flybrain_gb::compatibility::RestoreDecision::Exact => Ok(None), + flybrain_gb::compatibility::RestoreDecision::MigrateAdapter { from } => Ok(Some(from)), + flybrain_gb::compatibility::RestoreDecision::Refuse(reason) => Err(format!( + "compatibility mismatch: {reason}\n checkpoint: {}\n this build: {}", + runtime.compatibility, self.compatibility + )), + } + } +} + +/// One restored candidate. +#[derive(Clone, Debug)] +pub struct Restored { + pub candidate: Candidate, + /// Candidates refused before this one, with why: the legacy `restore_fallback` metric. + pub skipped: Vec<(Candidate, String)>, + pub migrated_from: Option, + pub checkpoint: Checkpoint, + pub installed: T, +} + +/// The outcome of a restore over the live store. +#[derive(Debug)] +pub enum Selection { + /// No candidate exists: warm up a fresh fly. + Fresh, + Restored(Box>), + /// Candidates exist and every one failed. The legacy loop exits non-zero here rather than + /// silently start a fresh fly over them, and so must the session runtime. + Refused(Vec<(Candidate, String)>), +} + +/// Restores from the live `FLYSIM01` stores in the legacy order -- hot latest, hot previous, +/// durable latest, durable previous, then the milestone archives by descending rank +/// (`store::restore_order`) -- trying the next candidate on *any* failure: unreadable, +/// another cartridge, refused compatibility, or `install` refusing it (a participant's +/// `State.StageRestore` or the task's validation). This is `Sim::restore_or_warm_up`. +pub async fn restore_from_store( + hot: &Store, + durable: &Store, + gate: &RestoreGate, + mut install: F, +) -> Selection +where + F: FnMut(Checkpoint) -> Fut, + Fut: std::future::Future>, +{ + let candidates = store::restore_order(hot, durable); + if candidates.is_empty() { + return Selection::Fresh; + } + let mut skipped: Vec<(Candidate, String)> = Vec::new(); + for candidate in candidates { + let checkpoint = match store::load(&candidate.path) { + Ok(checkpoint) => checkpoint, + Err(e) => { + skipped.push((candidate, format!("{e:#}"))); + continue; + } + }; + let migrated_from = match gate.check(&checkpoint) { + Ok(from) => from, + Err(reason) => { + skipped.push((candidate, reason)); + continue; + } + }; + match install(checkpoint.clone()).await { + Ok(installed) => { + return Selection::Restored(Box::new(Restored { + candidate, + skipped, + migrated_from, + checkpoint, + installed, + })); + } + Err(reason) => skipped.push((candidate, reason)), + } + } + Selection::Refused(skipped) +} + +// ------------------------------------------------------------------------------------------- +// The store policy + +/// Why a save is taken. Each maps onto the legacy loop's call site. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SaveKind { + /// `checkpoint_if_due`, the hot interval: `hot_dir`, every `hot_seconds`. + Hot, + /// A durable save: the interval (`checkpoint_seconds`), startup/restore, after a rollback, + /// a forced checkpoint, a pause and shutdown. + Durable, + /// `track_rank`: a climb to a new rank. Durable, and archived as `milestone-` when the + /// rank is above every rank this process archived. + Milestone(u32), +} + +/// A rank change the task reported, as `Sim::track_rank` sees it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RankChange { + Climbed(u32), + FellBack(u32), +} + +/// The configuration the legacy loop reads from `[paths]` and `[loop]`. +#[derive(Clone, Debug)] +pub struct CheckpointerConfig { + pub hot_dir: std::path::PathBuf, + pub durable_dir: std::path::PathBuf, + pub keep_generations: usize, + pub hot_seconds: f64, + pub checkpoint_seconds: f64, + pub compatibility: String, + pub speed: f64, + /// The environment's slot that holds the ratchet's snapshot (`best`). + pub slot_id: Id, +} + +/// One participant-coherent capture of a boundary, ready to be written. +#[derive(Clone, Debug)] +pub struct LegacyCapture { + pub boundary: u64, + pub agent_payload: Vec, + pub world_payload: Vec, + pub task: TaskHalf, +} + +/// What a committed save wrote. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SaveReport { + pub generation: u64, + pub durable: bool, + pub archive_rank: Option, + pub bytes: usize, +} + +/// A save that was queued; its reply resolves when the writer committed it (or failed). +pub struct SaveTicket { + pub generation: u64, + pub durable: bool, + pub archive_rank: Option, + pub reply: oneshot::Receiver>, +} + +struct WriteJob { + durable: bool, + archive_rank: Option, + capture: LegacyCapture, + host: HostHalf, + slot_id: Id, + reply: oneshot::Sender>, +} + +/// The session runtime's `FLYSIM01` store policy: the legacy loop's, call site for call site. +/// +/// - generations come from one counter over both stores, starting above the highest either +/// has ever allocated (`Sim::boot`); +/// - a hot copy every `hot_seconds`, a durable one every `checkpoint_seconds`, the durable +/// interval resetting the hot one (`checkpoint_if_due`); +/// - the first durable commit at a new best rank of *this process* is also written as +/// `milestone-.checkpoint` (`checkpoint_with_reply`'s `best_archived_rank`); +/// - the encoding and the fsyncs run on a writer thread, off the session's runtime. +pub struct LegacyCheckpointer { + config: CheckpointerConfig, + hot: Store, + durable: Store, + next_generation: u64, + best_archived_rank: Option, + rank: u32, + rank_since_ms: f64, + next_hot: Instant, + next_durable: Instant, + writer: Option>, + thread: Option>, +} + +impl LegacyCheckpointer { + /// Creates both store directories and starts the writer. + pub fn open(config: CheckpointerConfig) -> Result { + let durable = Store::new(&config.durable_dir, config.keep_generations); + let hot = Store::new(&config.hot_dir, config.keep_generations); + durable.create().map_err(|e| format!("{e:#}"))?; + hot.create().map_err(|e| format!("{e:#}"))?; + let next_generation = durable.highest_generation().max(hot.highest_generation()) + 1; + let (tx, rx) = mpsc::channel::(); + let (writer_hot, writer_durable) = (hot.clone(), durable.clone()); + let thread = std::thread::Builder::new() + .name("legacy-checkpoint".to_owned()) + .spawn(move || { + while let Ok(job) = rx.recv() { + let store = if job.durable { &writer_durable } else { &writer_hot }; + let generation = job.host.generation; + let result = export( + &job.capture.agent_payload, + &job.capture.world_payload, + &job.slot_id, + &job.capture.task, + &job.host, + ) + .and_then(|bytes| { + store + .commit(generation, &bytes, job.archive_rank) + .map(|_| bytes.len()) + .map_err(|e| format!("{e:#}")) + }) + .map(|bytes| SaveReport { + generation, + durable: job.durable, + archive_rank: job.archive_rank, + bytes, + }); + let _ = job.reply.send(result); + } + }) + .map_err(|e| format!("spawning the checkpoint writer: {e}"))?; + let now = Instant::now(); + Ok(LegacyCheckpointer { + config, + hot, + durable, + next_generation, + best_archived_rank: None, + rank: 0, + rank_since_ms: 0.0, + next_hot: now, + next_durable: now, + writer: Some(tx), + thread: Some(thread), + }) + } + + pub fn hot(&self) -> &Store { + &self.hot + } + + pub fn durable(&self) -> &Store { + &self.durable + } + + pub fn config(&self) -> &CheckpointerConfig { + &self.config + } + + /// The generation the next save will take. + pub fn next_generation(&self) -> u64 { + self.next_generation + } + + pub fn rank(&self) -> u32 { + self.rank + } + + pub fn rank_since_ms(&self) -> f64 { + self.rank_since_ms + } + + /// After a restore: the ladder rank the restored task reports and the checkpoint's + /// `rankSinceMs` (`Sim::try_restore`). A fresh start keeps rank 0. + pub fn restored(&mut self, rank: u32, rank_since_ms: f64) { + self.rank = rank; + self.rank_since_ms = rank_since_ms; + } + + /// Both intervals run from now: called right after the startup durable commit, as + /// `Sim::boot` does, so the loop's first boundary does not write a second one. + pub fn start_intervals(&mut self, now: Instant) { + self.next_hot = now + Duration::from_secs_f64(self.config.hot_seconds); + self.next_durable = now + Duration::from_secs_f64(self.config.checkpoint_seconds); + } + + /// `Sim::track_rank`: the rank after a transition. A climb is a milestone save. + pub fn observe_rank(&mut self, rank: u32, brain_ms: f64) -> Option { + if rank == self.rank { + return None; + } + let climbed = rank > self.rank; + self.rank = rank; + self.rank_since_ms = brain_ms; + Some(if climbed { RankChange::Climbed(rank) } else { RankChange::FellBack(rank) }) + } + + /// `Sim::checkpoint_if_due`: the interval save due now, if any. + pub fn due(&mut self, now: Instant) -> Option { + let hot_period = Duration::from_secs_f64(self.config.hot_seconds); + let durable_period = Duration::from_secs_f64(self.config.checkpoint_seconds); + if now >= self.next_durable { + self.next_durable = now + durable_period; + self.next_hot = now + hot_period; + Some(SaveKind::Durable) + } else if now >= self.next_hot { + self.next_hot = now + hot_period; + Some(SaveKind::Hot) + } else { + None + } + } + + /// Queues one save of `capture`. The generation is allocated here, on the caller's thread, + /// in call order, and a milestone archive is decided here too, exactly as + /// `Sim::checkpoint_with_reply` decides both before handing the write to its thread. + pub fn save( + &mut self, + kind: SaveKind, + capture: LegacyCapture, + last_event_id: u64, + wall_ms: u64, + ) -> Result { + let durable = kind != SaveKind::Hot; + let archive_rank = match kind { + SaveKind::Milestone(rank) => Some(rank), + _ => None, + } + .filter(|rank| durable && self.best_archived_rank.is_none_or(|best| *rank > best)); + let generation = self.next_generation; + self.next_generation += 1; + if let Some(rank) = archive_rank { + self.best_archived_rank = Some(rank); + } + let host = HostHalf { + generation, + wall_ms, + compatibility: self.config.compatibility.clone(), + speed: self.config.speed, + rank_since_ms: self.rank_since_ms, + last_event_id, + }; + let (tx, rx) = oneshot::channel(); + let job = WriteJob { + durable, + archive_rank, + capture, + host, + slot_id: self.config.slot_id.clone(), + reply: tx, + }; + self.writer + .as_ref() + .ok_or("the checkpoint writer is gone")? + .send(job) + .map_err(|_| "the checkpoint writer stopped".to_owned())?; + Ok(SaveTicket { + generation, + durable, + archive_rank, + reply: rx, + }) + } + + /// Restore candidates in the legacy order. + pub fn candidates(&self) -> Vec { + store::restore_order(&self.hot, &self.durable) + } + + /// Stops the writer after every queued save committed. + pub fn close(&mut self) { + self.writer = None; + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +impl Drop for LegacyCheckpointer { + fn drop(&mut self) { + self.close(); + } +} + +/// The current wall clock in milliseconds, for `wallMs`. +pub fn now_wall_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::legacy_env::{SlotState, sample_at, world_time_at}; + use flybrain_gb::emulator::FRAMEBUFFER_LEN; + + fn agent(ms: f64, remainder: f64, updates: f64) -> AgentState { + use flybrain_core::decoder::DecoderState; + use flybrain_core::lif::LifState; + use flybrain_core::ordered::NumberMap; + use flybrain_core::plasticity::PlasticityState; + AgentState { + version: 1, + remainder, + warmed_up: true, + network: LifState { + membrane: vec![0.5, -0.25], + refractory: vec![0, 3], + last_spike_ms: vec![-1_000_000.0, 12.0], + visual_drive: vec![0.1], + rng: -12_345, + reward_remaining: 40.0, + ms, + population_rate: 1.5, + rates: NumberMap::from_pairs([("forward", 2.0), ("reward_pam", 0.5)]), + plasticity: PlasticityState { + version: "fly-kc-mbon-rstdp-v2".to_string(), + topology: 42, + enabled: true, + updates, + signal: 0.25, + gains: vec![1.0, 0.9], + traces: vec![0.0, 0.1], + touched: vec![0.0, 8_000.0], + }, + }, + decoder: DecoderState { + version: 4, + calibrated: true, + baseline: NumberMap::from_pairs([("forward", 1.0)]), + held_until: NumberMap::new(), + next_allowed: NumberMap::new(), + next_decision: 100.0, + current: Some("a".to_string()), + fatigue: NumberMap::new(), + macro_next_decision: 0.0, + macro_current: None, + macro_fatigue: NumberMap::new(), + }, + } + } + + fn world_at(boundary: u64, slot: bool) -> WorldState { + let world_time = world_time_at(boundary).unwrap(); + WorldState { + rom_digest: "ab".repeat(32), + episode_id: id("ep1"), + boundary, + audio_next_sample: sample_at(&world_time, 48_000), + world_time, + engine_frame: boundary + 1, + buttons: 0b0001_0000, + emulator: vec![7; 64], + framebuffer: vec![9; FRAMEBUFFER_LEN], + slots: if slot { + vec![( + id("best"), + SlotState { game: vec![1, 2, 3], frame: vec![4; FRAMEBUFFER_LEN], boundary }, + )] + } else { + Vec::new() + }, + } + } + + fn task() -> TaskHalf { + TaskHalf { + reward: serde_json::json!({ "version": 3, "total": 1.25 }), + ratchet: RatchetState { best: 3, attempts: 1, ..Default::default() }, + } + } + + fn host(generation: u64) -> HostHalf { + HostHalf { + generation, + wall_ms: 1_700_000_000_000, + compatibility: "kernel/adapter/fingerprint".to_owned(), + speed: 1.0, + rank_since_ms: 4_242.0, + last_event_id: 77, + } + } + + #[test] + fn the_export_is_the_legacy_encoder_on_the_same_values_and_splits_back_into_its_halves() { + let agent = agent(9_000.0, 0.75, 3.0); + let world = world_at(12_344, true); + let bytes = export_states(&agent, &world, &id("best"), &task(), &host(4)).unwrap(); + // Field for field what `Sim::snapshot_state` builds, through the one encoder. + let legacy = store::encode( + &agent, + &RuntimeState { + generation: 4, + wall_ms: 1_700_000_000_000, + rom_sha256: "ab".repeat(32), + emulator_frame: 12_345, + compatibility: "kernel/adapter/fingerprint".to_owned(), + speed: 1.0, + buttons: 0b0001_0000, + rank_since_ms: 4_242.0, + last_event_id: 77, + reward: task().reward, + ratchet: task().ratchet, + emulator: vec![7; 64], + framebuffer: vec![9; FRAMEBUFFER_LEN], + ratchet_game: vec![1, 2, 3], + ratchet_frame: vec![4; FRAMEBUFFER_LEN], + }, + ) + .unwrap(); + assert_eq!(bytes, legacy); + let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); + assert_eq!(back.agent, agent); + assert_eq!(back.world, world); + assert_eq!(back.task, task()); + assert_eq!(back.host, host(4)); + // And no slot is an empty ratchet snapshot, both ways. + let bytes = export_states(&agent, &world_at(5, false), &id("best"), &task(), &host(1)).unwrap(); + let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); + assert!(back.world.slots.is_empty()); + } + + #[test] + fn the_export_from_capture_payloads_equals_the_export_from_states() { + let agent = agent(9_000.0, 0.75, 3.0); + let world = world_at(700, true); + let import = AgentImport { + agent_id: id("fly"), + profile: gameboy::profile_asset_ref(), + seed: 22_222, + macro_channels: vec!["macro_talk".to_owned()], + }; + let scope = legacy_source_scope(&id("s1"), world.boundary); + let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); + let agent_bytes = agent_payload(&agent, &world.framebuffer, &import, &id("c1"), &scope, &context).unwrap(); + let world_bytes = world_payload(&world, &id("world"), &id("c1"), &scope, &"cd".repeat(32)); + assert_eq!(agent_state(&agent_bytes).unwrap(), agent); + assert_eq!(world_state(&world_bytes).unwrap(), world); + assert_eq!( + export(&agent_bytes, &world_bytes, &id("best"), &task(), &host(9)).unwrap(), + export_states(&agent, &world, &id("best"), &task(), &host(9)).unwrap() + ); + assert!(export(&world_bytes, &agent_bytes, &id("best"), &task(), &host(9)).is_err()); + } + + #[test] + fn the_import_starts_the_accumulator_and_the_reinforcement_count_from_the_legacy_state() { + let state = agent(108_246_189.0, 0.75, 4_321.0); + let accumulator = legacy_accumulator(&state).unwrap(); + assert_eq!(accumulator.brain_ticks(), 108_246_189); + assert_eq!(accumulator.warmup_offset(), gameboy::WARMUP_MS); + assert_eq!( + crate::legacy_agent::rational_remainder_to_legacy(&accumulator.remainder()).unwrap(), + 0.75 + ); + assert_eq!(legacy_reinforcements(&state), 4_321); + // A clock that is not whole ticks, or a remainder that is not k/32768 ms, is refused. + assert!(legacy_accumulator(&agent(10.5, 0.0, 0.0)).is_err()); + assert!(legacy_accumulator(&agent(10.0, 0.1, 0.0)).is_err()); + let session = { + let import = AgentImport { + agent_id: id("fly"), + profile: gameboy::profile_asset_ref(), + seed: 22_222, + macro_channels: Vec::new(), + }; + let context = + gameboy::ReadoutContext { boot: true, bound: vec![], location: None }.to_typed(); + let bytes = agent_payload( + &state, + &[0; FRAMEBUFFER_LEN], + &import, + &id("c1"), + &legacy_source_scope(&id("s1"), 40), + &context, + ) + .unwrap(); + let parts = flybrain_core::envelope::decode_envelope( + &bytes, + crate::legacy_agent::PAYLOAD_MAGIC, + ) + .unwrap(); + let session: Value = + serde_json::from_str(&parts.manifest.get("session").unwrap().stringify()).unwrap(); + session + }; + assert_eq!(session["reinforcements"], "4321"); + assert_eq!(session["committedStep"], "40"); + assert_eq!(session["sourceScope"]["epoch"], LEGACY_SOURCE_EPOCH); + assert_eq!(session["accumulator"]["executedTicks"], "108246189"); + assert_eq!(session["accumulator"]["warmupOffset"], "2500"); + } + + #[test] + fn the_task_ledger_carries_exactly_the_reward_and_the_ratchet() { + let ledger = task().to_ledger(true); + assert_eq!(ledger["slotFilled"], true); + assert_eq!(TaskHalf::from_ledger(&ledger).unwrap(), task()); + assert_eq!( + ledger["ratchet"], + serde_json::to_value(task().ratchet).unwrap(), + "the FLYSIM01 manifest's own spelling" + ); + assert!(TaskHalf::from_ledger(&serde_json::json!({ "reward": null })).is_err()); + } + + fn capture(boundary: u64) -> LegacyCapture { + let agent = agent(9_000.0 + boundary as f64, 0.75, 3.0); + let world = world_at(boundary, boundary > 1); + let scope = legacy_source_scope(&id("s1"), boundary); + let import = AgentImport { + agent_id: id("fly"), + profile: gameboy::profile_asset_ref(), + seed: 22_222, + macro_channels: Vec::new(), + }; + let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); + LegacyCapture { + boundary, + agent_payload: agent_payload(&agent, &world.framebuffer, &import, &id("c"), &scope, &context) + .unwrap(), + world_payload: world_payload(&world, &id("world"), &id("c"), &scope, &"cd".repeat(32)), + task: task(), + } + } + + fn config(root: &std::path::Path) -> CheckpointerConfig { + CheckpointerConfig { + hot_dir: root.join("hot"), + durable_dir: root.join("state"), + keep_generations: 2, + hot_seconds: 5.0, + checkpoint_seconds: 300.0, + compatibility: "kernel/adapter/fingerprint".to_owned(), + speed: 1.0, + slot_id: id("best"), + } + } + + fn commit(checkpointer: &mut LegacyCheckpointer, kind: SaveKind, boundary: u64) -> SaveReport { + let ticket = checkpointer.save(kind, capture(boundary), boundary, 1).unwrap(); + ticket.reply.blocking_recv().unwrap().unwrap() + } + + #[test] + fn the_checkpointer_keeps_the_legacy_generations_archives_and_rotation() { + let dir = tempfile::tempdir().unwrap(); + // A store the legacy loop already wrote to: generation numbers are never reused. + let durable = Store::new(dir.path().join("state"), 2); + durable.create().unwrap(); + durable.stage_for_test(41, b"a crashed commit").unwrap(); + std::fs::rename( + dir.path().join("state/41.checkpoint.tmp"), + dir.path().join("state/41.checkpoint"), + ) + .unwrap(); + let mut checkpointer = LegacyCheckpointer::open(config(dir.path())).unwrap(); + assert_eq!(checkpointer.next_generation(), 42); + + let first = commit(&mut checkpointer, SaveKind::Durable, 10); + assert_eq!((first.generation, first.durable, first.archive_rank), (42, true, None)); + let hot = commit(&mut checkpointer, SaveKind::Hot, 11); + assert_eq!((hot.generation, hot.durable), (43, false)); + assert_eq!(checkpointer.hot().manifest().unwrap().latest, Some(43)); + + // A climb: rank and rankSinceMs as track_rank keeps them, and the first archive. + assert_eq!(checkpointer.observe_rank(0, 1.0), None); + assert_eq!(checkpointer.observe_rank(4, 500.0), Some(RankChange::Climbed(4))); + let archived = commit(&mut checkpointer, SaveKind::Milestone(4), 12); + assert_eq!(archived.archive_rank, Some(4)); + assert!(checkpointer.durable().archive_path(4).is_file()); + let decoded = store::load(&checkpointer.durable().archive_path(4)).unwrap(); + assert_eq!(decoded.runtime.generation, 44); + assert_eq!(decoded.runtime.rank_since_ms, 500.0); + assert_eq!(decoded.runtime.last_event_id, 12); + // Falling back and climbing to the same rank again is not a new best for this process. + assert_eq!(checkpointer.observe_rank(3, 600.0), Some(RankChange::FellBack(3))); + assert_eq!(checkpointer.observe_rank(4, 700.0), Some(RankChange::Climbed(4))); + let again = commit(&mut checkpointer, SaveKind::Milestone(4), 13); + assert_eq!((again.durable, again.archive_rank), (true, None)); + assert_eq!(store::load(&checkpointer.durable().archive_path(4)).unwrap().runtime.generation, 44); + + for boundary in 14..20 { + commit(&mut checkpointer, SaveKind::Durable, boundary); + } + let manifest = checkpointer.durable().manifest().unwrap(); + assert_eq!(manifest.archives.get(&4), Some(&44)); + assert!(checkpointer.durable().generation_path(44).is_file(), "an archived generation stays"); + assert!(!checkpointer.durable().generation_path(46).exists(), "rotated away"); + assert_eq!(manifest.previous.map(|p| p + 1), manifest.latest); + checkpointer.close(); + + // The next process allocates above everything either store holds. + let checkpointer = LegacyCheckpointer::open(config(dir.path())).unwrap(); + assert_eq!(checkpointer.next_generation(), manifest.latest.unwrap() + 1); + } + + #[test] + fn the_intervals_are_the_legacy_loops() { + let dir = tempfile::tempdir().unwrap(); + let mut checkpointer = LegacyCheckpointer::open(config(dir.path())).unwrap(); + let start = Instant::now(); + checkpointer.start_intervals(start); + assert_eq!(checkpointer.due(start + Duration::from_secs(1)), None); + assert_eq!(checkpointer.due(start + Duration::from_secs(5)), Some(SaveKind::Hot)); + assert_eq!(checkpointer.due(start + Duration::from_secs(6)), None); + assert_eq!(checkpointer.due(start + Duration::from_secs(10)), Some(SaveKind::Hot)); + // The durable interval wins and restarts the hot one. + let at = start + Duration::from_secs(300); + assert_eq!(checkpointer.due(at), Some(SaveKind::Durable)); + assert_eq!(checkpointer.due(at + Duration::from_secs(4)), None); + assert_eq!(checkpointer.due(at + Duration::from_secs(5)), Some(SaveKind::Hot)); + } + + fn gate() -> RestoreGate { + RestoreGate { + rom_sha256: "ab".repeat(32), + compatibility: "kernel/adapter/fingerprint".to_owned(), + migrates_from: Vec::new(), + accepted: Vec::new(), + } + } + + fn select( + checkpointer: &LegacyCheckpointer, + gate: &RestoreGate, + refuse: &[u64], + ) -> Selection { + let refuse = refuse.to_vec(); + let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap(); + runtime.block_on(restore_from_store(checkpointer.hot(), checkpointer.durable(), gate, |c| { + let refuse = refuse.clone(); + async move { + if refuse.contains(&c.runtime.generation) { + Err(format!("participant refused generation {}", c.runtime.generation)) + } else { + Ok(c.runtime.generation) + } + } + })) + } + + #[test] + fn restore_walks_the_legacy_order_and_takes_the_next_candidate_on_any_refusal() { + let dir = tempfile::tempdir().unwrap(); + let mut checkpointer = LegacyCheckpointer::open(config(dir.path())).unwrap(); + assert!(matches!(select(&checkpointer, &gate(), &[]), Selection::Fresh)); + commit(&mut checkpointer, SaveKind::Milestone(3), 10); // 1, archive 3 + commit(&mut checkpointer, SaveKind::Durable, 11); // 2 + commit(&mut checkpointer, SaveKind::Durable, 12); // 3 + commit(&mut checkpointer, SaveKind::Hot, 13); // 4 + commit(&mut checkpointer, SaveKind::Hot, 14); // 5 + + let Selection::Restored(first) = select(&checkpointer, &gate(), &[]) else { panic!() }; + assert_eq!((first.installed, first.candidate.origin.as_str()), (5, "hot latest generation 5")); + assert!(first.skipped.is_empty()); + + // A torn hot latest, then a participant that refuses hot previous: durable latest. + std::fs::write(checkpointer.hot().generation_path(5), b"torn").unwrap(); + let Selection::Restored(next) = select(&checkpointer, &gate(), &[4]) else { panic!() }; + assert_eq!(next.installed, 3); + assert_eq!(next.skipped.len(), 2); + // Everything above the archive refused: the archive's generation, then its own file. + let Selection::Restored(deep) = select(&checkpointer, &gate(), &[2, 3, 4]) else { panic!() }; + assert_eq!(deep.installed, 1); + assert_eq!(deep.candidate.origin, "durable archived generation 1 (rank 3)"); + + // Another cartridge or another brain: refused by name, and nothing restores. + let other = RestoreGate { rom_sha256: "cd".repeat(32), ..gate() }; + let Selection::Refused(reasons) = select(&checkpointer, &other, &[]) else { panic!() }; + assert!(reasons.iter().all(|(_, why)| why.contains("another cartridge") || why.contains("decoding"))); + let newer = RestoreGate { compatibility: "kernel/adapter-v2/fingerprint".to_owned(), ..gate() }; + assert!(matches!(select(&checkpointer, &newer, &[]), Selection::Refused(_))); + // The operator's adapter migration is the legacy decision, unchanged. + let migrating = RestoreGate { + compatibility: "kernel/adapter-v2/fingerprint".to_owned(), + migrates_from: vec!["adapter".to_owned()], + accepted: vec!["adapter".to_owned()], + ..gate() + }; + let Selection::Restored(migrated) = select(&checkpointer, &migrating, &[]) else { panic!() }; + assert_eq!(migrated.migrated_from.as_deref(), Some("adapter")); + } +} diff --git a/services/flysim/crates/fly-session/src/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs index 785b7b7..07af25f 100644 --- a/services/flysim/crates/fly-session/src/legacy_parity.rs +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -1450,10 +1450,10 @@ impl AgentDriver { /// the loop's frame remainder in it -- instead of from a warm-up, the way the stream restores /// after a restart (`legacy-transient-reset`). /// - /// This is the test side of an import nothing ships yet: the worker is initialized, its own - /// capture is taken as the template for the session member, the agent chunks and the clock - /// are replaced with `state`'s, and the result is restored into a replacement worker through - /// the ordinary `State.StageRestore` / `ActivateRestore`, which validates it like any other + /// The payload is the shipped `FLYSIM01` import's (`legacy_checkpoint::agent_payload`, STATE-02, + /// which replaced AGENT-01's prototype here): the worker is initialized, its capture names the + /// checkpoint and scope, and the import is restored into a replacement worker through the + /// ordinary `State.StageRestore` / `ActivateRestore`, which validates it like any other /// payload. `learning.updates` starts at [`legacy_reinforcements`], because `FLYSIM01` does /// not record every reinforcement call. pub async fn seed_from_legacy_state( @@ -1465,7 +1465,25 @@ impl AgentDriver { ) -> Result { self.initialize(initial_frame).await?; let template = self.capture().await?; - let bytes = legacy_state_payload(&template.bytes, state, &self.context)?; + // The shipped import (STATE-02, `legacy_checkpoint::agent_payload`); the template capture + // only supplies the checkpoint, the scope and the composition's macro channels. + let macro_channels: Vec = + serde_json::from_value(captured_session(&template.bytes)?["macroChannels"].clone()) + .map_err(|e| format!("the template's macro channels: {e}"))?; + let import = crate::legacy_checkpoint::AgentImport { + agent_id: self.agent_id.clone(), + profile: self.profile.asset.clone(), + seed: LEGACY_SEED, + macro_channels, + }; + let bytes = crate::legacy_checkpoint::agent_payload( + state, + &self.frames[initial_frame], + &import, + &template.result.checkpoint_id, + &template.scope, + &self.context, + )?; let digest = digest_of_bytes(&bytes); let artifact = crate::state::seal_payload(&self.client, &bytes, &digest) .await @@ -1483,7 +1501,11 @@ impl AgentDriver { self.restore_into(target, &seeded).await?; let after = self.capture().await?; let restored = payload_state_digest(&after.bytes)?; - if restored != state_digest(state) { + // Exact but for the visual drive, which the restore re-projects from the frame on screen + // as `LegacyFrame::restore` does (the direct reference does the same). + let mut expected = crate::legacy_checkpoint::agent_state(&after.bytes)?; + expected.network.visual_drive = state.network.visual_drive.clone(); + if state_digest(&expected) != state_digest(state) { return Err("the seeded worker's state is not the legacy state".to_owned()); } self.remainder = legacy_remainder_to_rational(state.remainder)?; @@ -1502,39 +1524,8 @@ impl AgentDriver { } } -/// The reinforcement calls to start a legacy agent state's `learning.updates` at. -/// -/// `FLYSIM01` records `plasticity.updates`, the reinforcements that moved a gain, but not every -/// call, and the contract requires `learning.changed <= learning.updates`. An import that starts -/// the call count at zero makes the first telemetry unreadable (found on the row-58 stream -/// checkpoint: `changed` is in the thousands), so it starts at the recorded count, a lower bound -/// on the calls actually made. -pub fn legacy_reinforcements(state: &flybrain_core::agent::AgentState) -> u64 { - state.network.plasticity.updates as u64 -} - -/// A worker capture with its agent chunks and clock replaced by a legacy agent state, and its -/// context by `context`: see [`AgentDriver::seed_from_legacy_state`]. -pub fn legacy_state_payload( - template: &[u8], - state: &flybrain_core::agent::AgentState, - context: &TypedValue, -) -> Result, String> { - let mut session = captured_session(template)?; - let remainder = legacy_remainder_to_rational(state.remainder)?; - session["accumulator"]["remainder"] = remainder.to_json(); - session["accumulator"]["executedTicks"] = json!((state.network.ms as u64).to_string()); - session["reinforcements"] = json!(legacy_reinforcements(state).to_string()); - session["context"] = context.to_json(); - let chunks = agent_to_chunks(state); - let mut manifest = chunks.manifest; - manifest.set( - "session", - flybrain_core::json::JsonValue::parse(&session.to_string()).map_err(|e| e.to_string())?, - ); - flybrain_core::envelope::encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks) - .map_err(|e| e.to_string()) -} +/// The shipped import's rule (`crate::legacy_checkpoint`), re-exported for the harness. +pub use crate::legacy_checkpoint::legacy_reinforcements; /// Runs a script against the rig's agent, recording what the coordinator observes. pub async fn run_on_worker( @@ -1553,6 +1544,30 @@ pub async fn run_on_worker_from( script: &LegacyScript, start: Option<&flybrain_core::agent::AgentState>, ) -> Result, String> { + run_script(rig, agent_id, script, start, false) + .await + .map(|(records, _)| records) +} + +/// [`run_on_worker_from`], then one `State.Capture` at the boundary the script ends on: the +/// records and the captured payload (STATE-02 writes a `FLYSIM01` export from it). +pub async fn run_on_worker_from_then_capture( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, + start: Option<&flybrain_core::agent::AgentState>, +) -> Result<(Vec, Vec), String> { + let (records, captured) = run_script(rig, agent_id, script, start, true).await?; + Ok((records, captured.expect("a capture was asked for"))) +} + +async fn run_script( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, + start: Option<&flybrain_core::agent::AgentState>, + capture_at_end: bool, +) -> Result<(Vec, Option>), String> { let mut driver = rig.driver(agent_id, script); let first = match start { None => driver.initialize(script.initial_frame).await?, @@ -1604,7 +1619,12 @@ pub async fn run_on_worker_from( } records.push(record); } - Ok(records) + let captured = if capture_at_end { + Some(driver.capture().await?.bytes) + } else { + None + }; + Ok((records, captured)) } fn captured_session(payload: &[u8]) -> Result { diff --git a/services/flysim/crates/fly-session/src/lib.rs b/services/flysim/crates/fly-session/src/lib.rs index 51ae391..63edd03 100644 --- a/services/flysim/crates/fly-session/src/lib.rs +++ b/services/flysim/crates/fly-session/src/lib.rs @@ -30,6 +30,7 @@ pub mod environment; pub mod harness; pub mod launcher; pub mod legacy_agent; +pub mod legacy_checkpoint; pub mod legacy_env; pub mod legacy_env_parity; pub mod legacy_parity; From 1faccd290844c318e3531625257591eb0d5e9da4 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 16:26:07 +0000 Subject: [PATCH 22/26] flysim: STATE-02 proofs: real-checkpoint round trips, restore-then-continue against FLY_TRACE, and the reset tools both ways --- .../flysim/crates/flysim/tests/state_02.rs | 825 ++++++++++++++++++ .../crates/flysim/tests/state_02_store.rs | 334 +++++++ 2 files changed, 1159 insertions(+) create mode 100644 services/flysim/crates/flysim/tests/state_02.rs create mode 100644 services/flysim/crates/flysim/tests/state_02_store.rs diff --git a/services/flysim/crates/flysim/tests/state_02.rs b/services/flysim/crates/flysim/tests/state_02.rs new file mode 100644 index 0000000..a23b39a --- /dev/null +++ b/services/flysim/crates/flysim/tests/state_02.rs @@ -0,0 +1,825 @@ +//! STATE-02: the session runtime's checkpoints are the legacy loop's `FLYSIM01`, on real +//! checkpoints and against the running legacy frame. +//! +//! Three proofs, all explicit ROM jobs (`. bin/rom-env.sh`, never a download): +//! +//! - `every_real_checkpoint_round_trips_legacy_session_legacy` (`FLY_ROM` and the rom-env +//! checkpoints): each checkpoint is read into its owners' halves by the shipped import, the +//! world is restored into the real environment worker and captured again, the agent state goes +//! through the `FLYAGT01` payload the import builds, the task half through the Pokémon adapter +//! and the ratchet, and the `FLYSIM01` export is compared with the original file byte for byte. +//! - `toy_restore_then_continue` (`FLY_ROM`): the legacy frame warms a toy fly up from power-on, +//! the legacy loop writes a checkpoint into a store, and from that store the legacy loop and +//! the session runtime each restore and run on. The session runtime's world and agent are +//! held to the legacy loop's `FLY_TRACE` transition by transition, its export at the end is +//! compared byte for byte with the legacy loop's own checkpoint of the same boundary, and that +//! export then goes session -> legacy -> session unchanged. +//! - `fafb_restore_then_continue` (also `FLY_STATE02_FAFB=1` and `data/fafb-v783`): the same +//! with the live composition, `gameboy-legacy-fafb-v783-v1` in macros mode, from a stream +//! checkpoint (`FLY_STATE02_CHECKPOINT`, else `FLY_ROW67_CHECKPOINT`), with sugar and a ratchet +//! rollback. +//! +//! The executor and the task's per-frame evaluation are TASK-01's; here the joypad masks come +//! from the trace and the task's end-of-run half from the legacy loop, which is what makes the +//! world and the agent comparable on their own. `FLY_STATE02_FRAMES` sets the run length +//! (default 600 toy, 300 FAFB). + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use fly_session::ExecutionMode; +use fly_session::fly_session_types::gameboy::{Location, ReadoutContext}; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_checkpoint::{self as lc, HostHalf, Selection, TaskHalf}; +use fly_session::legacy_env::{self, BackendConfig}; +use fly_session::legacy_env_parity::{EnvRecord, EnvRig, FlyTrace}; +use fly_session::legacy_parity::{ + self, LegacyRig, LegacyScript, RewardEvent, RigAgent, ScriptStep, TraceTransition, toy, +}; +use fly_session::types::{digest_of_bytes, id}; +use flybrain_core::agent::{AgentConfig, NeuralAgent}; +use flybrain_core::dataset::{BrainDataset, load_brain_dataset_from_dir}; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flybrain_gb::adapter::GameAdapter; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flybrain_gb::ratchet::{Ratchet, Snapshot}; +use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator}; +use flysim::config::Config; +use flysim::frame::{LegacyFrame, Parts}; +use flysim::macros::{MacroLayer, macro_layer}; +use flysim::snapshot::MacroMode; +use flysim::store::{self, Checkpoint, RuntimeState, Store}; +use flysim::trace::FrameTrace; + +const EPISODE: &str = "ep1"; + +fn rom_path() -> Option { + let Some(path) = std::env::var_os("FLY_ROM") else { + eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)"); + return None; + }; + Some(PathBuf::from(path)) +} + +fn frames(default: usize) -> usize { + std::env::var("FLY_STATE02_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +fn slot() -> fly_session::types::Id { + id(legacy_env::DEFAULT_SLOT) +} + +/// Every stream checkpoint rom-env names, once each, by variable name. +fn rom_env_checkpoints() -> Vec<(String, PathBuf)> { + let mut seen: HashMap = HashMap::new(); + for (key, value) in std::env::vars() { + if key.starts_with("FLY_") && key.ends_with("_CHECKPOINT") { + let path = PathBuf::from(value); + if path.is_file() { + seen.entry(path).or_insert(key); + } + } + } + let mut out: Vec<(String, PathBuf)> = seen.into_iter().map(|(p, k)| (k, p)).collect(); + out.sort(); + out +} + +fn context(adapter: &dyn GameAdapter, macros: Option<&MacroLayer>) -> ReadoutContext { + ReadoutContext { + boot: adapter.boot(), + bound: macros.map(MacroLayer::bound_channels).unwrap_or_default(), + location: adapter.location().map(|(area, x, y)| Location { area, x, y }), + } +} + +/// The host fields the two runtimes are given alike, so their bytes are comparable. +fn host_of(runtime: &RuntimeState, generation: u64) -> HostHalf { + HostHalf { + generation, + wall_ms: runtime.wall_ms, + compatibility: runtime.compatibility.clone(), + speed: runtime.speed, + rank_since_ms: runtime.rank_since_ms, + last_event_id: runtime.last_event_id, + } +} + +/// The field that first differs between two `FLYSIM01` files, for a readable failure. +fn first_difference(left: &[u8], right: &[u8]) -> String { + let (Ok(a), Ok(b)) = (store::decode(left), store::decode(right)) else { + return "one side does not decode".to_owned(); + }; + let checks: Vec<(&str, bool)> = vec![ + ("agent", a.agent == b.agent), + ("generation", a.runtime.generation == b.runtime.generation), + ("wallMs", a.runtime.wall_ms == b.runtime.wall_ms), + ("romHash", a.runtime.rom_sha256 == b.runtime.rom_sha256), + ("emulatorFrame", a.runtime.emulator_frame == b.runtime.emulator_frame), + ("compatibility", a.runtime.compatibility == b.runtime.compatibility), + ("speed", a.runtime.speed == b.runtime.speed), + ("buttons", a.runtime.buttons == b.runtime.buttons), + ("rankSinceMs", a.runtime.rank_since_ms == b.runtime.rank_since_ms), + ("lastEventId", a.runtime.last_event_id == b.runtime.last_event_id), + ("reward", a.runtime.reward == b.runtime.reward), + ("ratchet", a.runtime.ratchet == b.runtime.ratchet), + ("emulator", a.runtime.emulator == b.runtime.emulator), + ("framebuffer", a.runtime.framebuffer == b.runtime.framebuffer), + ("ratchetGame", a.runtime.ratchet_game == b.runtime.ratchet_game), + ("ratchetFrame", a.runtime.ratchet_frame == b.runtime.ratchet_frame), + ]; + let differing: Vec<&str> = checks.iter().filter(|(_, same)| !same).map(|(n, _)| *n).collect(); + if differing.is_empty() { + "every field decodes equal; the bytes differ in layout".to_owned() + } else { + format!("differing fields: {}", differing.join(", ")) + } +} + +/// Which world fields differ, and where the first differing emulator byte is. +fn world_difference(a: &fly_session::legacy_env::WorldState, b: &fly_session::legacy_env::WorldState) -> String { + let mut out = Vec::new(); + if a.boundary != b.boundary || a.engine_frame != b.engine_frame { + out.push(format!("boundary/frame {}/{} vs {}/{}", a.boundary, a.engine_frame, b.boundary, b.engine_frame)); + } + if a.world_time != b.world_time || a.audio_next_sample != b.audio_next_sample { + out.push("clock".to_owned()); + } + if a.buttons != b.buttons { + out.push(format!("buttons {} vs {}", a.buttons, b.buttons)); + } + if a.framebuffer != b.framebuffer { + out.push("framebuffer".to_owned()); + } + if a.slots != b.slots { + out.push("slots".to_owned()); + } + if a.emulator != b.emulator { + let first = a.emulator.iter().zip(&b.emulator).position(|(x, y)| x != y); + let count = a.emulator.iter().zip(&b.emulator).filter(|(x, y)| x != y).count(); + out.push(format!( + "emulator ({} vs {} bytes, first difference at {first:?}, {count} bytes differ)", + a.emulator.len(), + b.emulator.len() + )); + } + if a.rom_digest != b.rom_digest || a.episode_id != b.episode_id { + out.push("identity".to_owned()); + } + out.join("; ") +} + +// ------------------------------------------------------------------------------------------- +// The session runtime's world, through the environment worker + +/// The world half of `halves` restored into the environment worker through the shipped payload, +/// the worker driven by `ops`, then captured: the records and the captured payload. +async fn world_on_worker( + rig: &mut EnvRig, + halves: &lc::Halves, + ops: &[fly_session::legacy_env_parity::EnvOp], +) -> (Vec, Vec) { + use fly_session::legacy_env_parity::EnvOp; + let mut driver = rig.driver(); + let source = lc::legacy_source_scope(&rig.session_id, halves.world.boundary); + let captured = driver.payload_of(&halves.world, source.clone()).await.expect("sealed"); + // The harness's sealing is the shipped encoder with the same header. + let descriptor = legacy_env::LegacyGameboyEnvironment::descriptor_for(&BackendConfig::legacy( + &halves.world.rom_digest, + )); + assert_eq!( + captured.bytes, + lc::world_payload( + &halves.world, + &rig.worker_id, + &captured.result.checkpoint_id, + &source, + &descriptor.configuration_digest, + ), + "the world payload is the shipped import's" + ); + let target = driver.target().clone(); + let mut records = vec![driver.restore_into(target, &captured).await.expect("the world restores")]; + for op in ops { + records.push(match op { + EnvOp::Advance(mask) => driver.advance(*mask).await.expect("advance"), + EnvOp::SaveSlot(slot) => driver.save_slot(slot).await.expect("save slot"), + EnvOp::Rollback(slot) => driver.rollback(slot).await.expect("rollback"), + EnvOp::CaptureRestore => unreachable!("not in these scripts"), + }); + } + let bytes = driver.capture().await.expect("the world captures").bytes; + (records, bytes) +} + +async fn env_rig(root: &Path, rom: &Path, rom_digest: &str) -> EnvRig { + EnvRig::start(root, ExecutionMode::InProcess, rom, BackendConfig::legacy(rom_digest)) + .await + .expect("the environment rig") +} + +/// The task half through the objects TASK-01's task holds: the adapter and the ratchet. +fn task_through_adapter(task: &TaskHalf, snapshot: Option) -> TaskHalf { + let mut adapter = PokemonRedReward::new(); + if !task.reward.is_null() { + adapter.import_state(&task.reward).expect("the adapter imports its state"); + } + let mut ratchet = Ratchet::with_policy(adapter.recovery_policy()); + ratchet + .import(Some(task.ratchet), snapshot, adapter.rank_ladder().len()) + .expect("the ratchet imports its state"); + TaskHalf { + reward: adapter.export_state(), + ratchet: ratchet.state, + } +} + +// ------------------------------------------------------------------------------------------- +// 1. legacy -> session -> legacy on every real checkpoint + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn every_real_checkpoint_round_trips_legacy_session_legacy() { + let Some(rom) = rom_path() else { return }; + let checkpoints = rom_env_checkpoints(); + if checkpoints.is_empty() { + eprintln!("skipping: no FLY_*_CHECKPOINT is set (source bin/rom-env.sh)"); + return; + } + let root = tempfile::tempdir().expect("tmp"); + let mut identical = 0; + let mut semantic = Vec::new(); + for (name, path) in &checkpoints { + let original = std::fs::read(path).expect("the checkpoint reads"); + let checkpoint = store::decode(&original).expect("a FLYSIM01 checkpoint"); + let halves = lc::halves(&checkpoint, &id(EPISODE), &slot(), legacy_env::DEFAULT_AUDIO_RATE) + .expect("the halves"); + + // The world: into the real environment worker and out again. + let rig_root = root.path().join(name.to_lowercase()); + let mut rig = env_rig(&rig_root, &rom, &halves.world.rom_digest).await; + let (_, world_bytes) = world_on_worker(&mut rig, &halves, &[]).await; + rig.stop().await; + let world = lc::world_state(&world_bytes).expect("the captured world"); + + // Everything but the emulator's bytes is the file's; those are the legacy restore's + // (import, then the recorded joypad applied), compared below through the export. + let expected = fly_session::legacy_env::WorldState { + emulator: world.emulator.clone(), + ..halves.world.clone() + }; + assert!( + world == expected, + "{name}: the world restores and captures exactly: {}", + world_difference(&expected, &world) + ); + + // The agent: the FLYAGT01 payload the import builds carries exactly the legacy state. + let import = lc::AgentImport { + agent_id: id("fly"), + profile: fly_session::fly_session_types::gameboy::profile_asset_ref(), + seed: legacy_parity::LEGACY_SEED, + macro_channels: flybrain_gb::macro_channels("pokemon-red") + .iter() + .map(|c| (*c).to_owned()) + .collect(), + }; + let restored_context = ReadoutContext { boot: false, bound: vec![], location: None }; + let agent_bytes = lc::agent_payload( + &halves.agent, + &halves.world.framebuffer, + &import, + &id("c1"), + &lc::legacy_source_scope(&id("legacy"), halves.world.boundary), + &restored_context.to_typed(), + ) + .expect("the agent payload"); + + // The task: through the adapter and the ratchet, as the task object holds them. + let snapshot = (!checkpoint.runtime.ratchet_game.is_empty()).then(|| Snapshot { + game: checkpoint.runtime.ratchet_game.clone(), + frame: checkpoint.runtime.ratchet_frame.clone(), + }); + let task = task_through_adapter(&halves.task, snapshot); + + let exported = lc::export(&agent_bytes, &world_bytes, &slot(), &task, &halves.host) + .expect("the export"); + // And legacy again: the legacy store reads it and writes it back unchanged. + let back = store::decode(&exported).expect("the legacy loop reads the export"); + assert_eq!(store::encode(&back.agent, &back.runtime).unwrap(), exported); + + // The legacy loop's own restore outcome of the same file, checkpointed at once: what + // `LegacyFrame::restore` leaves in the emulator (import, then `set_buttons(buttons)`), + // the adapter (import, export) and the ratchet (import). The agent's import is exact + // (AGENT-01; the FAFB proof below restores it into both runtimes). + let rom_bytes = std::fs::read(&rom).expect("the ROM reads"); + let mut emulator = Emulator::new(&rom_bytes, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .expect("binjgb should accept the cartridge"); + emulator.import_state(&checkpoint.runtime.emulator).expect("the emulator imports"); + emulator.set_buttons(checkpoint.runtime.buttons as u8); + let snapshot = (!checkpoint.runtime.ratchet_game.is_empty()).then(|| Snapshot { + game: checkpoint.runtime.ratchet_game.clone(), + frame: checkpoint.runtime.ratchet_frame.clone(), + }); + let legacy_task = task_through_adapter(&halves.task, snapshot); + let legacy = store::encode( + &checkpoint.agent, + &RuntimeState { + emulator: emulator.export_state().expect("the emulator exports"), + reward: legacy_task.reward, + ratchet: legacy_task.ratchet, + ..checkpoint.runtime.clone() + }, + ) + .expect("the legacy encoder"); + assert!( + exported == legacy, + "{name}: the session export is not the legacy restore outcome: {}", + first_difference(&legacy, &exported) + ); + if exported == original { + identical += 1; + eprintln!("{name}: {} bytes, byte-identical to the file", original.len()); + } else { + // Both runtimes restore the same: what moved is the file's, and the reason is named. + let mut why = first_difference(&original, &exported); + if why.contains("reward") { + // Only an older adapter's state moves: the adapter's own import migration. + let adapter = checkpoint.runtime.compatibility.split('/').nth(1).unwrap_or(""); + assert_ne!(adapter, PokemonRedReward::new().id(), "{name}: {why}"); + why.push_str(&format!(" (written by adapter {adapter}, migrated on import)")); + } + eprintln!("{name}: {} bytes, the legacy restore outcome; vs the file: {why}", original.len()); + semantic.push(format!("{name} ({why})")); + } + } + eprintln!( + "legacy -> session -> legacy: {} checkpoints, every export equal to the legacy restore \ + outcome; {identical} byte-identical to the file, {} not: {semantic:?}", + checkpoints.len(), + semantic.len() + ); +} + +// ------------------------------------------------------------------------------------------- +// 2 and 3. restore then continue, against the legacy loop's trace + +/// A legacy brain and everything the legacy frame drives. +struct LegacyWorld { + agent: NeuralAgent, + emulator: Emulator, + adapter: PokemonRedReward, + ratchet: Ratchet, + frame: LegacyFrame, + macros: Option, +} + +fn legacy_world( + rom: &[u8], + data: &Arc, + mode: MacroMode, + trace: Option<&Path>, +) -> (LegacyWorld, Vec) { + let emulator = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .expect("binjgb should accept the cartridge"); + let adapter = PokemonRedReward::new(); + let ratchet = Ratchet::with_policy(adapter.recovery_policy()); + let channels = if mode.dealt() { + flybrain_gb::macro_channels("pokemon-red") + } else { + Vec::new() + }; + let preset = gameboy_decoder_config_with_macros(&channels); + let mut agent_config = AgentConfig::with_decoder(preset); + agent_config.warmup_ms = Config::default().loop_.warmup_ms; + let agent = NeuralAgent::new(Arc::clone(data), agent_config).expect("a valid agent"); + let frame = LegacyFrame::new().with_trace( + trace.map(|path| FrameTrace::create(path).expect("a trace file")), + ); + ( + LegacyWorld { agent, emulator, adapter, ratchet, frame, macros: None }, + channels.iter().map(|c| (*c).to_owned()).collect(), + ) +} + +impl LegacyWorld { + fn parts(&mut self) -> Parts<'_> { + Parts { + agent: &mut self.agent, + emulator: &mut self.emulator, + adapter: &mut self.adapter, + ratchet: &mut self.ratchet, + macros: self.macros.as_mut(), + } + } + + /// `Sim::boot` after its restore or warm-up: the macro layer, seeded from the network, and + /// one observation before the first frame. + fn deal(&mut self, mode: MacroMode) { + let mut config = Config::default(); + config.loop_.game = "pokemon-red".to_string(); + config.macros.mode = mode; + let channels = if mode.dealt() { flybrain_gb::macro_channels("pokemon-red") } else { Vec::new() }; + let preset = gameboy_decoder_config_with_macros(&channels); + let hold_ms = preset + .macros + .as_ref() + .or(preset.exclusive.as_ref()) + .expect("the preset has a group") + .hold_ms; + self.macros = macro_layer(&config, hold_ms, self.agent.network.rng_state() as u32); + if let Some(layer) = self.macros.as_mut() { + let ledger = AdapterLedger(&self.adapter); + let _ = layer.observe(&mut self.emulator, &ledger, self.agent.network.ms); + } + } + + /// `Sim::snapshot_state` with the host fields given. + fn checkpoint(&mut self, host: &HostHalf) -> Vec { + let mut agent = self.agent.export_state(); + agent.remainder = self.frame.remainder; + let runtime = RuntimeState { + generation: host.generation, + wall_ms: host.wall_ms, + rom_sha256: self.emulator.rom_sha256(), + emulator_frame: self.frame.frame_counter, + compatibility: host.compatibility.clone(), + speed: host.speed, + buttons: self.frame.buttons, + rank_since_ms: host.rank_since_ms, + last_event_id: host.last_event_id, + reward: self.adapter.export_state(), + ratchet: self.ratchet.state, + emulator: self.emulator.export_state().expect("the emulator exports"), + framebuffer: self.frame.frame_buffer.clone(), + ratchet_game: self.ratchet.game().map(<[u8]>::to_vec).unwrap_or_default(), + ratchet_frame: self.ratchet.frame().map(<[u8]>::to_vec).unwrap_or_default(), + }; + store::encode(&agent, &runtime).expect("the legacy encoder") + } + + fn task(&self) -> TaskHalf { + TaskHalf { reward: self.adapter.export_state(), ratchet: self.ratchet.state } + } +} + +/// Frames by content, so a still screen is stored once. +#[derive(Default)] +struct Pool { + frames: Vec>, + index: HashMap, +} + +impl Pool { + fn add(&mut self, frame: &[u8]) -> usize { + let digest = digest_of_bytes(frame); + *self.index.entry(digest).or_insert_with(|| { + self.frames.push(frame.to_vec()); + self.frames.len() - 1 + }) + } +} + +/// The legacy loop restored from `checkpoint` and run `n` frames with `FLY_TRACE` on: the trace, +/// the agent's script, and the legacy world at the end. +#[allow(clippy::too_many_arguments)] +fn legacy_run( + rom: &[u8], + data: &Arc, + checkpoint: &Checkpoint, + mode: MacroMode, + n: usize, + sugar: &[(usize, f64)], + rollback_at: Option, + trace_path: &Path, +) -> (LegacyWorld, LegacyScript, Vec) { + let (mut world, channels) = legacy_world(rom, data, mode, Some(trace_path)); + { + let mut frame = std::mem::replace(&mut world.frame, LegacyFrame::new()); + frame.restore(&mut world.parts(), checkpoint).expect("the checkpoint restores"); + world.frame = frame; + } + world.deal(mode); + let mut pool = Pool::default(); + let initial_frame = pool.add(&world.frame.frame_buffer); + let initial_context = context(&world.adapter, world.macros.as_ref()); + let mut steps = Vec::new(); + for k in 1..=n { + let mut admitted = Vec::new(); + for (_, duration) in sugar.iter().filter(|(at, _)| *at == k) { + world.agent.network.stimulate(*duration); + if let Some(trace) = world.frame.trace_mut() { + trace.sugar(*duration); + } + admitted.push(*duration); + } + let mut frame = std::mem::replace(&mut world.frame, LegacyFrame::new()); + let mut parts = world.parts(); + let transition = frame.transition(&mut parts, &mut ()).expect("a frame"); + // The frame this transition produced, before a rollback puts the slot's on screen. + let produced = pool.add(&frame.frame_buffer); + let rewards: Vec = transition + .evaluated + .rewards + .iter() + .map(|event| RewardEvent { value: event.value, stimulation_ms: f64::from(event.stimulation_ms) }) + .collect(); + let next_context = context(&*parts.adapter, parts.macros.as_deref()); + let boundary = frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .expect("the boundary"); + let mut rolled_back = boundary.rollback.is_some(); + if !rolled_back && rollback_at == Some(k) && parts.ratchet.game().is_some() { + frame.rollback(&mut parts).expect("the forced rollback"); + rolled_back = true; + } + let rollback_context = rolled_back.then(|| context(&*parts.adapter, parts.macros.as_deref())); + world.frame = frame; + steps.push(ScriptStep::Frame { sugar: admitted, frame: produced, rewards, next_context }); + if let Some(context) = rollback_context { + steps.push(ScriptStep::Rollback { frame: pool.add(&world.frame.frame_buffer), context }); + } + } + world.frame.finish_trace(); + let text = std::fs::read_to_string(trace_path).expect("the trace reads back"); + let trace = legacy_parity::read_frame_trace(&text).expect("a flysim-legacy-frame-trace-v1"); + let script = LegacyScript { + name: format!("state-02-{}", mode.as_str()), + macro_channels: channels, + frames: Arc::new(pool.frames), + initial_frame, + initial_context, + steps, + checkpoints: Default::default(), + }; + (world, script, trace) +} + +async fn agent_rig(root: &Path, dataset_dir: PathBuf, profile: LegacyProfileKind, channels: &[String]) -> LegacyRig { + let agent = RigAgent { + agent_id: id("fly"), + port_id: id("p1"), + dataset_dir, + profile, + macro_channels: channels.to_vec(), + worker_threads: 2, + }; + LegacyRig::start(root, ExecutionMode::InProcess, &[agent]).await.expect("the agent rig") +} + +/// What one restore-then-continue proves, for the report line. +struct Proof { + transitions: usize, + world_values: usize, + rollbacks: usize, + sugar: usize, + bytes: usize, +} + +/// The whole proof from one `FLYSIM01` start: +/// +/// 1. the start is committed into a durable store, under a torn hot copy, and the session +/// runtime selects it the legacy way; +/// 2. the legacy loop restores the same bytes and runs `n` frames with the trace on; +/// 3. the session runtime's world and agent, restored through the shipped import, run the +/// same transitions and are held to that trace; +/// 4. at the end the session runtime's `FLYSIM01` export equals the legacy loop's checkpoint of +/// the same boundary, byte for byte; +/// 5. that export restores into a fresh legacy loop, whose checkpoint is the same bytes, and +/// back into a fresh session runtime, whose export is the same bytes again. +#[allow(clippy::too_many_arguments)] +async fn restore_then_continue( + rom_path: &Path, + data: &Arc, + dataset_dir: PathBuf, + profile: LegacyProfileKind, + start: &[u8], + mode: MacroMode, + n: usize, + sugar: &[(usize, f64)], + rollback_at: Option, +) -> Proof { + let rom = std::fs::read(rom_path).expect("the ROM reads"); + let root = tempfile::tempdir().expect("tmp"); + + // 1. The live store: a durable generation under a torn hot one. + let start_checkpoint = store::decode(start).expect("the start decodes"); + let durable = Store::new(root.path().join("state"), 8); + let hot = Store::new(root.path().join("hot"), 8); + durable.commit(start_checkpoint.runtime.generation, start, None).expect("commit"); + hot.commit(start_checkpoint.runtime.generation + 1, b"torn by a crash", None).expect("commit"); + let gate = lc::RestoreGate { + rom_sha256: start_checkpoint.runtime.rom_sha256.clone(), + compatibility: start_checkpoint.runtime.compatibility.clone(), + migrates_from: Vec::new(), + accepted: Vec::new(), + }; + let selection = lc::restore_from_store(&hot, &durable, &gate, |checkpoint| async move { + lc::halves(&checkpoint, &id(EPISODE), &slot(), legacy_env::DEFAULT_AUDIO_RATE) + }) + .await; + let Selection::Restored(restored) = selection else { + panic!("the durable generation should restore: {selection:?}") + }; + assert_eq!(restored.skipped.len(), 1, "the torn hot copy is skipped"); + let halves = restored.installed; + let generation = start_checkpoint.runtime.generation + 10; + let host = host_of(&start_checkpoint.runtime, generation); + + // 2. The legacy loop from the same bytes. + let trace_path = root.path().join("trace.jsonl"); + let (mut legacy, script, trace) = + legacy_run(&rom, data, &restored.checkpoint, mode, n, sugar, rollback_at, &trace_path); + assert_eq!(trace.len(), n); + let legacy_bytes = legacy.checkpoint(&host); + + // 3a. The world, through the environment worker, driven by the trace's masks and boundary + // actions and held to its frame, WRAM and slot digests. + let fly_trace = FlyTrace::read(&trace_path, None).expect("the trace as the world reads it"); + let env_script = fly_trace.script("state-02", Arc::new(start.to_vec())); + let mut env = env_rig(&root.path().join("env"), rom_path, &halves.world.rom_digest).await; + let (records, world_bytes) = world_on_worker(&mut env, &halves, &env_script.ops).await; + let world_values = fly_trace.check(&records).expect("the world against FLY_TRACE"); + + // 3b. The agent, seeded through the shipped import and held to the trace. + let mut agents = agent_rig(&root.path().join("agent"), dataset_dir.clone(), profile, &script.macro_channels).await; + let (agent_records, agent_bytes) = legacy_parity::run_on_worker_from_then_capture( + &mut agents, + &id("fly"), + &script, + Some(&halves.agent), + ) + .await + .expect("the agent runs"); + let check = legacy_parity::check_against_trace(&script, &agent_records, &trace) + .expect("the agent against FLY_TRACE"); + + // 4. The session runtime's export at the last boundary is the legacy loop's checkpoint. + let session_bytes = + lc::export(&agent_bytes, &world_bytes, &slot(), &legacy.task(), &host).expect("the export"); + assert!( + session_bytes == legacy_bytes, + "session export vs legacy checkpoint after {n} frames: {}", + first_difference(&legacy_bytes, &session_bytes) + ); + + // 5a. session -> legacy: a fresh legacy loop restores the export and checkpoints it again. + let exported = store::decode(&session_bytes).expect("the legacy loop reads the export"); + let (mut fresh, _) = legacy_world(&rom, data, mode, None); + { + let mut frame = std::mem::replace(&mut fresh.frame, LegacyFrame::new()); + frame.restore(&mut fresh.parts(), &exported).expect("the legacy loop restores the export"); + fresh.frame = frame; + } + let host_after = host_of(&exported.runtime, exported.runtime.generation); + assert_eq!(fresh.checkpoint(&host_after), session_bytes, "session -> legacy is exact"); + + // 5b. -> session: a fresh environment and a fresh agent import it and export it again. + let again = lc::split(&session_bytes, &id(EPISODE), &slot(), legacy_env::DEFAULT_AUDIO_RATE) + .expect("the halves again"); + env.replace().await.expect("a fresh environment worker"); + let (_, world_again) = world_on_worker(&mut env, &again, &[]).await; + agents.replace(&id("fly")).await.expect("a fresh agent worker"); + // The import installs the frame on screen: the export's own. + let one_step = LegacyScript { + frames: Arc::new(vec![again.world.framebuffer.clone()]), + initial_frame: 0, + ..script.clone_shallow() + }; + let (_, agent_again) = legacy_parity::run_on_worker_from_then_capture( + &mut agents, + &id("fly"), + &one_step, + Some(&again.agent), + ) + .await + .expect("the agent imports the export"); + let round = lc::export(&agent_again, &world_again, &slot(), &again.task, &again.host) + .expect("the export again"); + assert!( + round == session_bytes, + "session -> legacy -> session: {}", + first_difference(&session_bytes, &round) + ); + env.stop().await; + agents.stop().await; + + Proof { + transitions: check.transitions, + world_values, + rollbacks: check.rollbacks, + sugar: check.sugar, + bytes: session_bytes.len(), + } +} + +trait CloneShallow { + fn clone_shallow(&self) -> LegacyScript; +} + +impl CloneShallow for LegacyScript { + fn clone_shallow(&self) -> LegacyScript { + LegacyScript { + name: self.name.clone(), + macro_channels: self.macro_channels.clone(), + frames: Arc::clone(&self.frames), + initial_frame: self.initial_frame, + initial_context: self.initial_context.clone(), + steps: Vec::new(), + checkpoints: Default::default(), + } + } +} + +fn report(what: &str, n: usize, proof: &Proof) { + eprintln!( + "{what}: {n} frames restored from the store and run on; world {} values and agent {} \ + transitions identical to FLY_TRACE ({} sugar, {} rollbacks); the {}-byte FLYSIM01 export \ + equals the legacy checkpoint of the same boundary and survives session -> legacy -> \ + session unchanged", + proof.world_values, proof.transitions, proof.sugar, proof.rollbacks, proof.bytes + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn toy_restore_then_continue() { + let Some(rom_path) = rom_path() else { return }; + let rom = std::fs::read(&rom_path).expect("the ROM reads"); + let data = Arc::new(load_brain_dataset_from_dir(toy::dir()).expect("the toy dataset")); + // A toy fly warmed up from power-on and run a while by the legacy frame: the checkpoint the + // legacy loop would write of it. + let (mut warm, _) = legacy_world(&rom, &data, MacroMode::Raw, None); + warm.frame.initialize(&mut warm.emulator, &mut warm.agent).expect("the fresh start"); + for _ in 0..120 { + let mut frame = std::mem::replace(&mut warm.frame, LegacyFrame::new()); + let mut parts = warm.parts(); + let transition = frame.transition(&mut parts, &mut ()).expect("a frame"); + frame.boundary(&mut parts, &transition.evaluated.progress, transition.ms).expect("a boundary"); + warm.frame = frame; + } + let start = warm.checkpoint(&HostHalf { + generation: 7, + wall_ms: 1_790_000_000_000, + compatibility: "toy/compat".to_owned(), + speed: 1.0, + rank_since_ms: 0.0, + last_event_id: 3, + }); + let n = frames(600); + let proof = restore_then_continue( + &rom_path, + &data, + toy::dir(), + LegacyProfileKind::Toy, + &start, + MacroMode::Raw, + n, + &[(20, 300.0), (n / 2, 500.0)], + None, + ) + .await; + report("toy raw", n, &proof); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fafb_restore_then_continue() { + let Some(rom_path) = rom_path() else { return }; + if std::env::var_os("FLY_STATE02_FAFB").is_none() { + eprintln!("skipping: FLY_STATE02_FAFB is not set"); + return; + } + let Some(dataset_dir) = legacy_parity::fafb_dir() else { + eprintln!("skipping: data/fafb-v783 is not present in this checkout"); + return; + }; + let Some(path) = std::env::var_os("FLY_STATE02_CHECKPOINT") + .or_else(|| std::env::var_os("FLY_ROW67_CHECKPOINT")) + else { + eprintln!("skipping: neither FLY_STATE02_CHECKPOINT nor FLY_ROW67_CHECKPOINT is set"); + return; + }; + let start = std::fs::read(&path).expect("the checkpoint reads"); + let data = Arc::new(load_brain_dataset_from_dir(&dataset_dir).expect("the dataset")); + let n = frames(300); + let started = std::time::Instant::now(); + let proof = restore_then_continue( + &rom_path, + &data, + dataset_dir, + LegacyProfileKind::Production, + &start, + MacroMode::Macros, + n, + &[(10, 400.0), (n / 2, 250.0)], + Some(n / 3), + ) + .await; + report( + &format!("FAFB macros from {} ({:?})", Path::new(&path).display(), started.elapsed()), + n, + &proof, + ); +} diff --git a/services/flysim/crates/flysim/tests/state_02_store.rs b/services/flysim/crates/flysim/tests/state_02_store.rs new file mode 100644 index 0000000..89b10e5 --- /dev/null +++ b/services/flysim/crates/flysim/tests/state_02_store.rs @@ -0,0 +1,334 @@ +//! STATE-02: the session runtime's `FLYSIM01` store and the operator's tools, both ways. +//! +//! `fly-reset-to-milestone` and `fly-loop-reset` must keep working on a store the session runtime +//! wrote (`legacy-gameboy-v1` section 16), and the session runtime must restore a store the +//! legacy loop wrote and the tools reset. These run the real scripts from `infra/bin` and the +//! real `flysim --reset-to-milestone` against stores in a temporary directory, with `systemctl` +//! stubbed out. No ROM and no dataset: the checkpoints are synthetic but complete envelopes. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use fly_session::fly_session_types::gameboy; +use fly_session::legacy_checkpoint::{ + self as lc, AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, + RestoreGate, SaveKind, Selection, TaskHalf, +}; +use fly_session::legacy_env::{SlotState, WorldState, sample_at, world_time_at}; +use fly_session::types::id; +use flybrain_core::agent::AgentState; +use flybrain_gb::RatchetState; +use flybrain_gb::emulator::FRAMEBUFFER_LEN; +use flysim::journal::{self, BootHeader, Entry, Input, SugarJournal}; +use flysim::store::{self, RuntimeState, Store}; + +const COMPAT: &str = "lif-1ms-f64-v2/pokered-unique8-v7/fingerprint/fly-kc-mbon-rstdp-v2"; + +fn repo() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../..") +} + +fn agent(ms: f64) -> AgentState { + use flybrain_core::decoder::DecoderState; + use flybrain_core::lif::LifState; + use flybrain_core::ordered::NumberMap; + use flybrain_core::plasticity::PlasticityState; + AgentState { + version: 1, + remainder: 0.5, + warmed_up: true, + network: LifState { + membrane: vec![0.5, -0.25], + refractory: vec![0, 3], + last_spike_ms: vec![-1_000_000.0, 12.0], + visual_drive: vec![0.1], + rng: -12_345, + reward_remaining: 0.0, + ms, + population_rate: 1.5, + rates: NumberMap::from_pairs([("forward", 2.0)]), + plasticity: PlasticityState { + version: "fly-kc-mbon-rstdp-v2".to_string(), + topology: 42, + enabled: true, + updates: 17.0, + signal: 0.25, + gains: vec![1.0, 0.9], + traces: vec![0.0, 0.1], + touched: vec![0.0, 8_000.0], + }, + }, + decoder: DecoderState { + version: 4, + calibrated: true, + baseline: NumberMap::from_pairs([("forward", 1.0)]), + held_until: NumberMap::new(), + next_allowed: NumberMap::new(), + next_decision: 100.0, + current: None, + fatigue: NumberMap::new(), + macro_next_decision: 0.0, + macro_current: None, + macro_fatigue: NumberMap::new(), + }, + } +} + +fn world(boundary: u64) -> WorldState { + let world_time = world_time_at(boundary).unwrap(); + WorldState { + rom_digest: "ab".repeat(32), + episode_id: id("ep1"), + boundary, + audio_next_sample: sample_at(&world_time, 48_000), + world_time, + engine_frame: boundary + 1, + buttons: 0, + emulator: vec![(boundary % 251) as u8; 256], + framebuffer: vec![9; FRAMEBUFFER_LEN], + slots: vec![( + id("best"), + SlotState { game: vec![1; 32], frame: vec![4; FRAMEBUFFER_LEN], boundary }, + )], + } +} + +/// A complete capture of boundary `k`, as the participants would hand it over. +fn capture(k: u64, ratchet: RatchetState) -> LegacyCapture { + let scope = lc::legacy_source_scope(&id("s1"), k); + let import = AgentImport { + agent_id: id("fly"), + profile: gameboy::profile_asset_ref(), + seed: 22_222, + macro_channels: Vec::new(), + }; + let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); + LegacyCapture { + boundary: k, + agent_payload: lc::agent_payload(&agent(9_000.0 + k as f64), &world(k).framebuffer, &import, &id("c"), &scope, &context) + .unwrap(), + world_payload: lc::world_payload(&world(k), &id("world"), &id("c"), &scope, &"cd".repeat(32)), + task: TaskHalf { reward: serde_json::Value::Null, ratchet }, + } +} + +fn config(root: &Path) -> CheckpointerConfig { + CheckpointerConfig { + hot_dir: root.join("hot"), + durable_dir: root.join("state"), + keep_generations: 8, + hot_seconds: 5.0, + checkpoint_seconds: 300.0, + compatibility: COMPAT.to_owned(), + speed: 1.0, + slot_id: id("best"), + } +} + +fn save(checkpointer: &mut LegacyCheckpointer, kind: SaveKind, k: u64, ratchet: RatchetState) { + let ticket = checkpointer.save(kind, capture(k, ratchet), k, 1_790_000_000_000).unwrap(); + ticket.reply.blocking_recv().unwrap().unwrap(); +} + +fn stub(dir: &Path, name: &str, body: &str) -> PathBuf { + use std::os::unix::fs::PermissionsExt; + let path = dir.join(name); + std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path +} + +/// A PATH whose `systemctl` says every unit is inactive, so the scripts believe flysim is stopped. +fn tools(root: &Path) -> (String, PathBuf) { + let bin = root.join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + stub(&bin, "systemctl", "exit 3"); + let flysim = stub(root, "flysim-build", &format!("[ \"$1\" = --print-compatibility ] && echo \"{COMPAT}\"")); + (format!("{}:/usr/bin:/bin", bin.display()), flysim) +} + +fn loop_reset_list(root: &Path, state: &Path) -> Vec { + let (path, flysim) = tools(root); + let env_file = root.join("fly.env"); + std::fs::write(&env_file, "").unwrap(); + let out = Command::new(repo().join("infra/bin/fly-loop-reset")) + .arg("--list") + .env_clear() + .env("PATH", path) + .env("FLY_LOOP_RESET_TEST_STATE_DIR", state) + .env("FLY_LOOP_RESET_TEST_ENV_FILE", &env_file) + .env("FLY_LOOP_RESET_TEST_FLYSIM", &flysim) + .env("FLY_LOOP_RESET_TEST_LIVE_FLYSIM", &flysim) + .output() + .expect("fly-loop-reset runs"); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout).split_whitespace().map(|r| r.parse().unwrap()).collect() +} + +fn reset_to_milestone(root: &Path, durable: &Path, hot: &Path, rank: u32) { + let (path, _) = tools(root); + let out = Command::new(repo().join("infra/bin/fly-reset-to-milestone")) + .arg(rank.to_string()) + .env_clear() + .env("PATH", path) + .env("FLY_STATE_DIR", durable) + .env("FLY_STATE_HOT_DIR", hot) + .env("FLY_BIN", env!("CARGO_BIN_EXE_flysim")) + .env("FLY_USER", "no-such-user-state02") + .output() + .expect("fly-reset-to-milestone runs"); + assert!( + out.status.success(), + "{}\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); +} + +fn gate() -> RestoreGate { + RestoreGate { + rom_sha256: "ab".repeat(32), + compatibility: COMPAT.to_owned(), + migrates_from: Vec::new(), + accepted: Vec::new(), + } +} + +fn session_restore(hot: &Path, durable: &Path) -> Box> { + let runtime = tokio::runtime::Builder::new_current_thread().build().unwrap(); + let selection = runtime.block_on(lc::restore_from_store( + &Store::new(hot, 8), + &Store::new(durable, 8), + &gate(), + |checkpoint| async move { lc::halves(&checkpoint, &id("ep1"), &id("best"), 48_000) }, + )); + match selection { + Selection::Restored(restored) => restored, + other => panic!("the session runtime should restore: {other:?}"), + } +} + +fn spent(best: u64) -> RatchetState { + RatchetState { best, attempts: 2, recoveries: 5, ..RatchetState::default() } +} + +#[test] +fn a_store_the_session_runtime_writes_is_reset_by_the_legacy_tools() { + let root = tempfile::tempdir().unwrap(); + let mut checkpointer = LegacyCheckpointer::open(config(root.path())).unwrap(); + let (hot, durable) = (root.path().join("hot"), root.path().join("state")); + + // The session runtime's own journal, with its boot header. + let mut sugar = SugarJournal::new(&hot); + sugar.boot(&BootHeader { + runtime: "fly-session".to_owned(), + start_frame: 11, + brain_ms: 9_010.0, + origin: "fresh start".to_owned(), + generation: None, + compatibility: COMPAT.to_owned(), + wall_ms: 1, + }); + sugar.record(&Entry { + frame: 40, + brain_ms: 9_040.0, + input: Input::Sugar { duration_ms: 300.0 }, + by: "viewer", + source: "test", + event_id: 1, + wall_ms: 1, + }); + + // A run: a startup save, two climbs, hot copies and durable intervals in between. + save(&mut checkpointer, SaveKind::Durable, 10, spent(2)); + assert_eq!(checkpointer.observe_rank(3, 9_020.0), Some(RankChange::Climbed(3))); + save(&mut checkpointer, SaveKind::Milestone(3), 20, spent(3)); + save(&mut checkpointer, SaveKind::Hot, 25, spent(3)); + assert_eq!(checkpointer.observe_rank(5, 9_050.0), Some(RankChange::Climbed(5))); + save(&mut checkpointer, SaveKind::Milestone(5), 50, spent(5)); + save(&mut checkpointer, SaveKind::Durable, 60, spent(5)); + save(&mut checkpointer, SaveKind::Hot, 65, spent(5)); + checkpointer.close(); + + // fly-loop-reset reads the compatibility out of the session runtime's archives. + assert_eq!(loop_reset_list(root.path(), &durable), vec![3, 5]); + // `flysim --print-state-compatibility` does too. + assert_eq!(store::state_compatibility(&durable).as_deref(), Some(COMPAT)); + + // fly-reset-to-milestone 3, the real script and the real binary. + reset_to_milestone(root.path(), &durable, &hot, 3); + assert!(!durable.join("milestone-5.checkpoint").exists()); + assert!(!hot.join(journal::FILE_NAME).exists(), "the reset clears the sugar journal"); + + // The legacy order and the session runtime agree on what comes back: rung 3, budget back. + let legacy_first = store::restore_order(&Store::new(&hot, 8), &Store::new(&durable, 8)); + let legacy = store::load(&legacy_first[0].path).unwrap(); + let restored = session_restore(&hot, &durable); + assert_eq!(restored.candidate, legacy_first[0]); + assert_eq!(restored.installed.task.ratchet.best, 3); + assert_eq!( + (restored.installed.task.ratchet.attempts, restored.installed.task.ratchet.recoveries), + (0, 0) + ); + assert_eq!(restored.installed.world.boundary, 20); + assert_eq!(restored.installed.agent, legacy.agent); + + // The session runtime carries on over the reset store: generations above everything, and + // its own first climb is archived again (a new process's best). + let mut checkpointer = LegacyCheckpointer::open(config(root.path())).unwrap(); + assert!(checkpointer.next_generation() > legacy.runtime.generation); + checkpointer.restored(3, restored.installed.host.rank_since_ms); + assert_eq!(checkpointer.observe_rank(4, 9_100.0), Some(RankChange::Climbed(4))); + save(&mut checkpointer, SaveKind::Milestone(4), 90, spent(4)); + checkpointer.close(); + assert_eq!(loop_reset_list(root.path(), &durable), vec![3, 4]); +} + +#[test] +fn a_store_the_legacy_loop_wrote_and_the_tools_reset_is_restored_by_the_session_runtime() { + let root = tempfile::tempdir().unwrap(); + let (hot, durable) = (root.path().join("hot"), root.path().join("state")); + let legacy_hot = Store::new(&hot, 8); + let legacy_durable = Store::new(&durable, 8); + // Exactly what `Sim`'s writer thread commits. + let bytes = |generation: u64, k: u64, ratchet: RatchetState| { + store::encode( + &agent(9_000.0 + k as f64), + &RuntimeState { + generation, + wall_ms: 1, + rom_sha256: "ab".repeat(32), + emulator_frame: k + 1, + compatibility: COMPAT.to_owned(), + speed: 1.0, + buttons: 0, + rank_since_ms: 0.0, + last_event_id: k, + reward: serde_json::Value::Null, + ratchet, + emulator: vec![(k % 251) as u8; 256], + framebuffer: vec![9; FRAMEBUFFER_LEN], + ratchet_game: vec![1; 32], + ratchet_frame: vec![4; FRAMEBUFFER_LEN], + }, + ) + .unwrap() + }; + legacy_durable.commit(1, &bytes(1, 10, spent(2)), None).unwrap(); + legacy_durable.commit(2, &bytes(2, 20, spent(2)), Some(2)).unwrap(); + legacy_durable.commit(3, &bytes(3, 30, spent(4)), Some(4)).unwrap(); + legacy_hot.commit(4, &bytes(4, 35, spent(4)), None).unwrap(); + + assert_eq!(loop_reset_list(root.path(), &durable), vec![2, 4]); + reset_to_milestone(root.path(), &durable, &hot, 2); + + let restored = session_restore(&hot, &durable); + assert_eq!(restored.installed.world.boundary, 20); + assert_eq!(restored.installed.task.ratchet.best, 2); + assert_eq!(restored.installed.task.ratchet.attempts, 0); + // And what the session runtime would save from it is the legacy bytes again. + let halves = &restored.installed; + let again = lc::export_states(&halves.agent, &halves.world, &id("best"), &halves.task, &halves.host) + .unwrap(); + assert_eq!(again, std::fs::read(&restored.candidate.path).unwrap()); +} From d211e53fab7a1c858bc929640adb89266133d4f3 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 16:26:07 +0000 Subject: [PATCH 23/26] docs: STATE-02 in the implementation guide and the legacy-gameboy-v1 section 16 amendment (2026-09-29) --- .../session-framework/implementation.md | 115 ++++++++++++++++++ .../session-framework/legacy-gameboy-v1.md | 33 +++++ 2 files changed, 148 insertions(+) diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index b0b02bd..ce8904c 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -353,6 +353,121 @@ for new epoch metadata; corrupt any participant and installation fails as a grou reply doesn't advance durable metadata; failure during activation cannot resume half a world. Checkpoint queue stress remains bounded; verify old media/parser data cannot cross recovery. +### STATE-02 — The legacy composition's checkpoints in `FLYSIM01` (port slice) + +**2026-09-29: built** on `port/state-02` off `port/integration` and awaiting review. The operator's +decision of 2026-09-23 makes `FLYSIM01` the format of record until RETIRE-01, and the session +runtime exports it on every durable save ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 16). +This slice is that export, the import back, the store policy and the restore selection. It adds +no `FLYSESS1` production file. Nothing in `flysim`'s frame, checkpoint bytes or compatibility +string changes. + +- **One store, two runtimes.** `flysim`'s `store.rs` and `journal.rs` move unchanged into the new + crate `flysim-store`, which `flysim` re-exports (`flysim::store`, `flysim::journal`) and + `fly-session` links. Both runtimes write through the one `store::encode` and commit through the + one `Store`, so they share the envelope bytes, the generations, `manifest.json`, the + `milestone-` archives, `keep_generations` rotation and the restore order by construction. +- **Export** (`fly-session::legacy_checkpoint`). A `FLYSIM01` file is assembled from its owners' + halves: the agent's `FLYAGT01` capture payload (the seven agent chunks, the remainder already the + accumulator's), the world's `FLYENV01` payload (emulator, frame on screen, joypad, frame + counter, cartridge digest, and slot `best` as `ratchetGame`/`ratchetFrame`), the task's + `{reward, ratchet}` and the host's `{generation, wallMs, compatibility, speed, rankSinceMs, + lastEventId}`. `runtime_state` builds the legacy `RuntimeState` field for field as + `Sim::snapshot_state` does. +- **Import.** `split`/`halves` read a `FLYSIM01` file back into those halves. `agent_payload` is + the shipped form of AGENT-01's `seed_from_legacy_state` prototype. It builds the `FLYAGT01` + payload a replacement agent stages, using the same encoder the worker's own capture uses + (`legacy_agent::encode_payload`). The accumulator is `{remainder, executedTicks = network.ms, + warmupOffset = 2500}`, and `learning.updates` starts at `plasticity.updates` + (`legacy_reinforcements`, section 13 amendment). The payload also carries the file's + `framebuffer` as an `inputFrame` chunk, which `State.StageRestore` installs as the next input. + `LegacyFrame::restore` re-projects the framebuffer and does not keep the saved visual drive, + and the two differ on the row 65 yard survey checkpoint (found here; see the section 13 + amendment). `world_payload` is ENV-01's `FLYENV01` from + the same world. The source scope of both is `(session, "legacy", emulatorFrame - 1)`. + `legacy_parity` now seeds its workers through this import. +- **Store policy.** `LegacyCheckpointer` follows `Sim` at each call site: + - one generation counter over both stores, starting above the highest either has allocated; + - a hot copy every `hot_seconds`, and a durable one every `checkpoint_seconds`, which also + restarts the hot interval; + - a durable save for a climb, archived as `milestone-` when the rank is above every rank + this process has archived (`best_archived_rank`, per process as in the legacy loop); + - rank tracking as in `track_rank`; + - encoding and fsyncs on a writer thread. +- **Restore selection.** `restore_from_store` walks `store::restore_order`: hot latest, hot + previous, durable latest, durable previous, then the archives by descending rank, each as its + generation and then as its `milestone-` file. It checks the legacy gate: the cartridge, and + `flybrain_gb::compatibility::decide` with `FLY_ACCEPT_ADAPTERS`. It moves to the next candidate + on *any* refusal, including a participant's `State.StageRestore`. It reports `Fresh` when no + candidate exists, and `Refused` when every candidate failed. In that case the runtime must exit + as `Sim::restore_or_warm_up` does. +- **Sugar journal** (the FND-01 review note, before SHADOW-01). A per-process boot header + records the runtime, start frame, brain ms, restore origin, generation and compatibility. The + journal rotates at 4 MiB and keeps three files; every rotated-in file starts with a + `continues` line. `journal::clear` removes the journal. `flysim` writes the header at boot, and + `flysim --reset-to-milestone` clears the journal after it has copied both stores aside. + `read_segments` cuts the journal into per-process segments. `read` still returns input lines + only. + +**Boundary order the session host must keep** (section 16, and section 11 step 6). At `Ready(k+1)` +the order is: + +1. `Environment.SaveSlot`, if one is due. +2. The milestone capture, if the rank climbed. +3. The rollback, if one was requested. +4. The durable capture after the rollback, then the hot and durable interval saves. + +The capture itself uses `State.Capture` on the world and the agent at the same committed +boundary, plus the task's ledger, `{reward, ratchet, slotFilled}` (`TaskHalf::to_ledger`). Wiring +it into the coordinator and the boot-time restore path is left to the legacy composition's +coordinator (TASK-01); this slice ships the pieces and proves them on the workers. + +**Proof** (flysim `tests/state_02.rs`, `tests/state_02_store.rs`; `fly-session` +`legacy_checkpoint` unit tests): + +- *legacy -> session -> legacy on 18 real checkpoints* (every distinct rom-env checkpoint, which + includes the row 64, row 65 and row 67 ones). Each file is split and the world is restored + into the real environment worker and captured again. The agent goes through the imported + `FLYAGT01` payload and the task through the Pokémon adapter and the ratchet. Every export is + byte-identical to the legacy loop's own restore outcome of the same file, checkpointed at once. + Six exports are byte-identical to the file itself. The other twelve differ in named fields + only. Eleven were written by adapters v5 or v6, and the adapter's import migrates their + `reward` state. One, a survey checkpoint, also has a joypad byte in the emulator state that + its own `buttons` field does not match; both runtimes apply `buttons` on restore. +- *Restore then continue, toy connectome, raw mode* (every ROM run). The legacy frame writes a + checkpoint. The session runtime selects it from a store whose hot copy is torn. The legacy + loop and the session runtime then each run 600 frames from it. World: 1,800 values identical + to `FLY_TRACE` (frame, WRAM). Agent: 600 transitions identical (ticks, clock, exact remainder, + rates, spikes, decision). The session runtime's export at the last boundary is byte-identical + to the legacy loop's checkpoint of that boundary. That export also survives session -> legacy + -> session unchanged: a fresh legacy loop restores it and checkpoints the same bytes, and a + fresh world and agent import it and export the same bytes. +- *The same with `gameboy-legacy-fafb-v783-v1` in macros mode* from the row 67 checkpoint, with + sugar and a ratchet rollback (`FLY_STATE02_FAFB=1`). Four checkpoints were run for 1,800 frames + each: rows 58, 64 and 67, and the row 65 yard survey. Each run has 5,400 world values and 1,800 + agent transitions identical to the trace, with 2 sugar and 1 rollback. Each export is + byte-identical to the legacy checkpoint and survives session -> legacy -> session. +- *The tools, both ways* (`tests/state_02_store.rs`, the real `infra/bin` scripts and the real + binary). `fly-loop-reset --list` and `--print-state-compatibility` read a store the session + runtime wrote. `fly-reset-to-milestone` promotes its rung with the recovery budget back and + clears the journal. The legacy order and the session runtime then choose the same candidate, + and the session runtime carries on above every generation and archives its next climb. The + other way round, the session runtime restores a store the legacy writer wrote and the tool + reset, and it would save it as the same bytes. + +**Not in this slice, and why:** + +- *The coordinator hook and the boot-time restore.* Both need the legacy composition's + bootstrap, which is TASK-01's. The restore order is Initialize-free: stage and activate the + world, have the task install `{reward, ratchet}` and observe O[k] for the first context + (`{boot, bound, location: null}`), then build the agent's payload with that context + (`agent_payload`) and stage and activate it. +- *The task's per-frame half in the proofs.* The executor and the task's evaluation are TASK-01's. + The proofs take the joypad masks from the trace and the task's end-of-run `{reward, ratchet}` + from the legacy loop. +- *Declared difference, archive order* (sections 4 and 16). A session-runtime milestone archive + holds the post-capture ratchet and slot. It is excluded from the shadow comparison. + ### PUBLISH-01 — Committed snapshots and observer isolation **Depends on:** SESSION-02, MEDIA-01; public v2 contract work is a separate prerequisite to diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 32c1410..6cd6313 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -544,6 +544,39 @@ current `flysim` reads, under the unchanged compatibility string. The deploy gat checkpoint may be written beside it, but it is not what a restore selects until RETIRE-01 says so. +**Amendment, 2026-09-29 (STATE-02).** Five readings of this section, fixed by building it +([implementation guide](implementation.md) STATE-02): + +- *"A FLYSIM01 envelope that the current `flysim` reads" means the same bytes.* The session + runtime writes through the legacy loop's own encoder and store, which now live in the crate + `flysim-store` that both link. For the same state it writes the same bytes, and it keeps the + same generations, `manifest.json`, `milestone-` archives, rotation and restore order. The + owners of the fields are: the agent (the seven agent chunks, the remainder), the environment + (`emulator`, `framebuffer`, `emulatorFrame`, `buttons`, `romHash`, and slot `best` as + `ratchetGame` and `ratchetFrame`), the task (`reward`, `ratchet`) and the host (`generation`, + `wallMs`, `compatibility`, `speed`, `rankSinceMs`, `lastEventId`). +- *The milestone archive is per process, as in the legacy loop.* A rank climb is archived when + the rank is above every rank *this process* has archived. After a restart, the first climb + rewrites `milestone-` even if an older process had archived that rank. That is the + legacy behaviour, and the reset tools rely on the newest archive of a rung. +- *A restore is the legacy restore, candidate for candidate.* The candidate order is hot latest, + hot previous, durable latest, durable previous, then the archives by descending rank. The gate + is the cartridge and the compatibility decision. A refusal at any step, including a + participant's `State.StageRestore`, moves to the next candidate. If every candidate fails, the + runtime does not start. The world applies the recorded `buttons` on restore, as + `LegacyFrame::restore` does, so a file whose emulator state disagrees with its own `buttons` + restores to the same state in both runtimes, not to the file's bytes. +- *The visual drive after a `FLYSIM01` import is the framebuffer's projection* (a correction to + section 13's *Restore*, "the two are the same values"). They are the same on stream + checkpoints. On the row 65 yard survey checkpoint they are not: the first transition's rates + and spikes differed from the legacy loop's. The import therefore carries the framebuffer in + the agent payload (chunk `inputFrame`), and `State.StageRestore` installs it after the import, + as `LegacyFrame::restore` does. A worker's own capture carries no such chunk and restores + exactly. +- *The sugar journal is the shadow run's input record.* It gets a per-process boot header, is + rotated at 4 MiB with three kept files, and `fly-reset-to-milestone` clears it + (`flysim-store::journal`). It is not a checkpoint and nothing restores from it. + ## 17. PROF-02b: MaleCNS bundles (later) Dataset manifests, original-ID mapping, anatomical roles, sensory and readout bindings, strict From d034a26be566c2bef2455c718d8666d79300e377 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 17:07:48 +0000 Subject: [PATCH 24/26] legacy_env: MEM-01's bulk read behind the image seam (ENV-01 review R1) The environment's memory image is now Emulator::read_memory_image: the register windows read $FF (legacy-gameboy-v1 section 8, MEM-01 amendment) and the read is neutral by construction, so the export/import guard is gone. The toy golden's image digests are regenerated (only 'memory' changes), the neutrality test states MEM-01's rule, and the ENV-01 guard amendment is struck in legacy-gameboy-v1 and implementation.md. The service traces still match in all three modes (rollback 3,199, climb 3,156, r58 11,043). --- .../session-framework/implementation.md | 8 +- .../session-framework/legacy-gameboy-v1.md | 11 +- .../fixtures/legacy-env/toy-cart.golden.json | 496 +++++++++--------- .../crates/fly-session/src/legacy_env.rs | 38 +- .../crates/fly-session/tests/legacy_env.rs | 26 +- 5 files changed, 287 insertions(+), 292 deletions(-) diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index b0b02bd..828283b 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -270,7 +270,7 @@ the FLYSIM01 export from the three halves (STATE-02; the world's half is **Amendment, 2026-09-29 (ENV-01).** Four readings the contract left open, fixed by this slice: -- *The image read is not state-neutral, so it is guarded.* `emulator_read_mem` of OAM, VRAM, +- ~~*The image read is not state-neutral, so it is guarded.* `emulator_read_mem` of OAM, VRAM, `FF01`/`FF02`, `FF04`-`FF06`, `IF`, `STAT` or `LY` runs binjgb's lazy synchronisation, and `export_state` afterwards differs (never, over 17,398 replayed frames, a frame or WRAM). The legacy loop reads none of these between a frame and the ratchet's capture, so an unguarded image @@ -278,7 +278,11 @@ the FLYSIM01 export from the three halves (STATE-02; the world's half is between `export_state` and `import_state` of the same bytes, which leaves the emulator exactly as the frame left it; `legacy-gameboy-v1` section 8's proof ("export before and after, compare") therefore fails for a plain 65,536-read loop and holds for the guarded one. MEM-01's bulk read - must keep that guard (or equivalent). + must keep that guard (or equivalent).~~ + *Struck 2026-09-29 (ENV-01 review, R1):* superseded by MEM-01 (legacy-gameboy-v1 section 8 + amendment). The register windows are not captured, so `legacy_env::memory_image` is MEM-01's + `Emulator::read_memory_image` with no guard, neutral by construction; the service traces still + match, and the toy golden's image digests were regenerated. - *A `FLYSIM01` world starts at `k = emulatorFrame - setupFrames`.* The legacy file has no boundary, world clock or audio position. The frame counter advances once per transition and never across a rollback, so `engineFrame = k + 1` from a fresh start on; `worldTime` is diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 32c1410..e062b5d 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -249,14 +249,21 @@ is not the environment's `contentDigest`. The emulator answers its own bank read completes before any `State.Capture` or FLYSIM01 export at that boundary (section 16). **Amendment, 2026-09-29 (ENV-01).** Two consequences of building this section, recorded in the -[implementation guide](implementation.md) ENV-01 entry: the memory image cannot be taken with a +[implementation guide](implementation.md) ENV-01 entry: ~~the memory image cannot be taken with a plain loop of `emulator_read_mem`, because reading OAM, VRAM, the serial and timer registers, `IF`, `STAT` or `LY` advances binjgb's lazy synchronisation and changes what `export_state` writes -- the environment reads it between an export and an import of the same bytes, so slots and -captures stay byte for byte the legacy loop's; and a `FLYSIM01` world is restored at boundary +captures stay byte for byte the legacy loop's;~~ and a `FLYSIM01` world is restored at boundary `emulatorFrame - 1`, its world time and audio position derived from that boundary, with the ratchet's snapshot as the slot `best`. +*Struck 2026-09-29 (ENV-01 review, R1).* The first consequence is superseded by section 8's MEM-01 +amendment of the same day: the register windows are not captured and read `$FF`, so the image is +MEM-01's one bulk read with no export/import guard around it, read-only by construction +(`legacy_env::memory_image`). With it the service's traces still reproduce every frame, WRAM and +slot-state digest (rollback 3,199, climb 3,156, r58 11,043 transitions), because the legacy +adapter and macros never read VRAM, OAM or I/O. + ## 10. Executor `pokered-macros-v1` The Pokémon Red task (reward adapter, ladder, ratchet ledger) and its action executor (the diff --git a/services/flysim/crates/fly-session/fixtures/legacy-env/toy-cart.golden.json b/services/flysim/crates/fly-session/fixtures/legacy-env/toy-cart.golden.json index 4dbca36..6e20ddf 100644 --- a/services/flysim/crates/fly-session/fixtures/legacy-env/toy-cart.golden.json +++ b/services/flysim/crates/fly-session/fixtures/legacy-env/toy-cart.golden.json @@ -13,7 +13,7 @@ }, "mask": null, "frame": "cdff586e1c1656586617e610d276b3db933e76ad27b7a79148237427ee8a7a5f", - "memory": "3407c14c51bc513a9f33022579dea167a3e24c393a2f0b0639c79fe153469acf", + "memory": "b0a9731b864ef62903d94fd5ff2b39d476e1538cef1d462d1dde38f4f0289686", "wram": "0ba149ce666205c7c800d970694d8c1bfd3c6d501f77e89044c547206a322067", "audio": null, "state": null @@ -29,7 +29,7 @@ }, "mask": 8, "frame": "ae8b59e34dfc614749c6a047ced955771319208885814b2d2e4d0dc7ea892984", - "memory": "76e41ca90d4d4964cff33b16bedabae862e97a494214c6c971e507ded8fd239d", + "memory": "9a9e12c0b052ca3817470bc339cb4627f73cba265f6db376da84f6655cac9bc1", "wram": "93b320bf9ff276d4fc80bb6a7fd5fb3d116501b8799e2e9aefe2d7f453a04687", "audio": { "firstSample": "0", @@ -50,7 +50,7 @@ }, "mask": 8, "frame": "c391eaf32fbd4a6a2313ba1c977df87487af0225937691471354b420788ae920", - "memory": "7c5d0dbd59915c2af8dbbba21a4f9da2873264a6428a192b40092ea0691ed2a4", + "memory": "0bd47bbb81bab5b493789f392da880b1516aff2d96394dd683a2fc416d34d9e1", "wram": "5856ffe6bc26bc0391ebd1930f95d527c1e3f082769c5f3fbc4ca3eee81250aa", "audio": { "firstSample": "803", @@ -71,7 +71,7 @@ }, "mask": 8, "frame": "517d9684f496617473bfa8ccdec4fc8ff317a9f123561d3c68ad171c4c8c15b2", - "memory": "96effed4e11bd694d139050e48c24e2716b1fcbd7c84693fcbcc29e8588d15f7", + "memory": "b7a9889c1fed0b1050adf7a358d95fe65d97a60d846211db544059d7ede225e4", "wram": "43451960631b8f93a7876d0ea3c1d1e921eabd0c3b9137f3487aae2cc8c55dec", "audio": { "firstSample": "1607", @@ -92,7 +92,7 @@ }, "mask": 8, "frame": "4db5a943f50ddb98d009be22c468c43713b0bd5e2f235c914e61c6a2a9c08f99", - "memory": "8de7068988170201602c4e77847338f03a86f5e55c2c38640999b23d1bdbe0ee", + "memory": "07f40beccf02e0de3507d0d7a628295eb5cbe949e3b0dcca51c0c166da19a08d", "wram": "c495ba41e55df80105ab60334afd63afca43fbb85c259fc13134b0cd6022a237", "audio": { "firstSample": "2411", @@ -113,7 +113,7 @@ }, "mask": 8, "frame": "2f695f5ffac753a184a0cae34b5778688aac5509878b8ea1a4108ca2ca1c6b7d", - "memory": "c52656bc184a4b1cfcaaec9fb63a220b249ab193e09e832e56c773bd056911be", + "memory": "93a4db8ce38b7de5c4f0fcb812591c8a02b3fd9e56a89642a03f610de6c03ea5", "wram": "9fa4af63f339bf8980db378e09cc7d7f8a5891913f2316f7b2bf1c0c4ddd878c", "audio": { "firstSample": "3214", @@ -134,7 +134,7 @@ }, "mask": 1, "frame": "55b65b34e18e43d5c6db69a577403a322bbe824a46482cd0248c5bc0f4db67fa", - "memory": "73694d53480b76539fce160ef0d76882008e598587912b355d82a74259050a3d", + "memory": "149854e34a32ffa79aca26a318ace928722f1643bba429620bdce0f98fb818a5", "wram": "299abe94613acdad71eff9c301ed9346b48218ef0669054a1ebb084bc7244c99", "audio": { "firstSample": "4018", @@ -155,7 +155,7 @@ }, "mask": 1, "frame": "85f7361cacb6ebe14a6a4930b1e43949713a59179d0e9efc73d2bd759ee597e4", - "memory": "e4fd2378c4c99569a541213ddd8e7722045a55df4e557c617b3d108e39df4a47", + "memory": "30a5b5341a9cb53066b4a0f2a1aea655a6c7ad57180d91fa4a263b8d0a3dcacd", "wram": "57433f9fc527fed6edce04d19fe0cff41b40778a2cdeaa74df1f186fe3fe8f80", "audio": { "firstSample": "4822", @@ -176,7 +176,7 @@ }, "mask": 1, "frame": "3ad1bb083cba14943f4081c74c667c914e9c08b97eb6e76bd6d501c03b50f317", - "memory": "87c58545deb969e259f1b42d3991889658c3ad5e25350ec374bc4b09cc8dffb4", + "memory": "b674764e8259bc02ed5163a4a2832c1b8749e6b4467d913f9d457dcfae55dc92", "wram": "73f909b4902c6827de0153b719d03c9fff6a1fed7668d7b0a777cf06a8f91716", "audio": { "firstSample": "5625", @@ -197,7 +197,7 @@ }, "mask": 1, "frame": "7e2144cedf0dcd6eacdebd3306b3262288013f6416b33f9497735d05f4b51d70", - "memory": "b468554d3a3a9852262265022e40a3abafb3308615ebfb7a157fabcc0d2372ad", + "memory": "f053c4f7fd59303a498b767564eca9b383a0666c08a2605ee25ef5e4bb620e6c", "wram": "b379117d38667d157d9be8f731b464046c15320e4841d24a67be7dd73c9b1ae4", "audio": { "firstSample": "6429", @@ -218,7 +218,7 @@ }, "mask": 1, "frame": "32326467932ab56f861a01daadfccdb102ef8a3e565657fbc55d6222d03ada25", - "memory": "182ea7c35614ce4fc6fde82dc3a7786ac2d831c33eea333bd16cc4efd63668ea", + "memory": "b5ac45fdcb167cabe0219e0f27f09ac54032a8b97294eea6f8331b204f154e8c", "wram": "2a04fb594c6f81b7765aa804f3b7cd4eee10f11af4fa6a8b500f787e42134f2a", "audio": { "firstSample": "7233", @@ -239,7 +239,7 @@ }, "mask": 1, "frame": "0525949510d3d85c0703416240093fdd6514434b9ee328964eeb55432b96fc41", - "memory": "bda1ffa8907e42db9c83d527e1d7a23f17492877d4e1bf02988920949d84d778", + "memory": "eb776ee7e74b4b304b93b1a55a225a88f739eb7a9277a3224737846c65e3105c", "wram": "6cae4061da252a2a80b5d56303a8f604fdcffb2fbf5fddf6131969e8b93a5bef", "audio": { "firstSample": "8036", @@ -260,7 +260,7 @@ }, "mask": 4, "frame": "43556abc8ba06dd840619f37f81cdd5ed02aa23e0430daa4ec909c1ee92e4044", - "memory": "7bf43bfb84e3feae7027ba48046a5cb9a0289da8b46d68d984e7fb0e282d7443", + "memory": "eaafed21fdd048ecd61aeac9add7fa52804e24c71a85d174e25dd094e388faaa", "wram": "062acd59080b0b3f6510f28b594bb4b6454675dec0a2ca6d8407fd6bc565cc7f", "audio": { "firstSample": "8840", @@ -281,7 +281,7 @@ }, "mask": 4, "frame": "efc792276c1275617a18b7d7e536879a5f279a2e038ed43f31a311f421636a59", - "memory": "3c1a58040b9768bc4b81fa98530a6d3a8d815d2431bcfd3314a4340fb00e6e29", + "memory": "af9b78dd579925bf3b3eb750323b6686b2ed385a0fc7d81d6d52ff375007bbc4", "wram": "61ed22a03bf5da17a09289e7ff56cee05fe18b0be472a643ce972a35ff5f85da", "audio": { "firstSample": "9644", @@ -302,7 +302,7 @@ }, "mask": 4, "frame": "84a7056520757fd6bb83213ef01fec4e5d205b70f7bdee0ddd35aefb0ee954c7", - "memory": "f46fd229a88180444b125f06383efffcfe38ffb70dd54f187594a988369b7cdc", + "memory": "b711dc80b235d4f249ef106f5cd7802cbca28b66df378d16194eb7427143da55", "wram": "a59aa5cc1de814b999a0e7405776621e48ca081eec53e90915f87fb0ad246162", "audio": { "firstSample": "10447", @@ -323,7 +323,7 @@ }, "mask": 4, "frame": "46ffe557906a6b0f735c657995377a2c4ea0cc14fddaa984d438e7208a648d39", - "memory": "2992956f96c4c0ed3e1020a1e2da2c1b130c401931b762b50f31cd68c4e8b779", + "memory": "93adba83b3d8bd820aa03d48122b31f5e7972a46c85e591b12c953949688bbf9", "wram": "963b3d0f4b007d2053a98dfe1a64360f552258ef00103a29141143672fd58347", "audio": { "firstSample": "11251", @@ -344,7 +344,7 @@ }, "mask": 4, "frame": "e480cfba81346c628c443de3308eb0fc6574cb8a8efb92086420064dafc1c9f5", - "memory": "95a662dbafc4826703f4955f6a36a82cd2b0bf91ec5dd4712d050f82999bd44f", + "memory": "fafcd989f272cbd7267ab195854abede9849159b84e69dfbb34ec29fc416f680", "wram": "a0d3ec727fd4fd2e834f8be7219e3a6e470b0db019415706152333e569d8dc97", "audio": { "firstSample": "12054", @@ -365,7 +365,7 @@ }, "mask": 4, "frame": "bd2d96681e9a17bb01829f45565fb76c898176d84b5755670d68708b373602fe", - "memory": "51ae290191f668a369dbe0dad510b4922d5ab0a20d73f501635017d567a31d0c", + "memory": "1e549dda59037fb72430a0919c0fa7d03af958290b442c0c6b56e15b6730a710", "wram": "28dcac035334b30a22c345bd97d0aa135f40a35eca4f06788bbcc0df9cd3c845", "audio": { "firstSample": "12858", @@ -386,7 +386,7 @@ }, "mask": 4, "frame": "1a3e5749c74a9f3443b79f2fe65c57e37ccaf5c4de5a44b8f3153bb2505d7f26", - "memory": "e76947bb62e242ead867f0c96775ce361e82bb3569996a795cf25ac525467a3c", + "memory": "10219f267f71fda09f2f22e3bebf885e5e78b816d5bd17e9d22689134462a770", "wram": "9c894fa65732409091e9fc159e688fad03bfcb7a5ac3f268fec78035a2d33a62", "audio": { "firstSample": "13662", @@ -407,7 +407,7 @@ }, "mask": 4, "frame": "68f717267372032b63a6076f44a63b91c31b1049d85e92a567b951496929b921", - "memory": "d9523f4791eb2a4443d1f5ad8d3297c61f2d934ad1cb05b36e7ea81cdcc9c993", + "memory": "fa46c2157b28ea940b5e4760673ba6371386d3179240c5ce83646c02a906298d", "wram": "4f8abe428f0fa4818776b2f632e1202f682672890677ba6596b149bed8dd8634", "audio": { "firstSample": "14465", @@ -428,7 +428,7 @@ }, "mask": 4, "frame": "20c3a130b5ae2beb7815bdff76a2a495142f5fb7fadb4f2eea461dc1ab2f14ba", - "memory": "1b78760076625897189b2354ceba21a99bc209b046d0f76c5bbababd18207e63", + "memory": "ce983beba7f13b489a59e398e1e401c161840a1804fac2d469d67b7400f05295", "wram": "699871b9d964ecff582654959aa1e34a9249449e5ac8d100d19a8d3642abb0b4", "audio": { "firstSample": "15269", @@ -449,7 +449,7 @@ }, "mask": 8, "frame": "1b5d0e132833cf4c638def1160561585cadc91ad31f37049cd1dffc46df64157", - "memory": "4a89fa393e10ec7b87aab4b70b3e6cd8d88d8918a92809501ab3c5bd26e20ffa", + "memory": "0306270efb9e580c507b783f39327a67895b292dac60e481142551df8e32c88e", "wram": "07bf8600d435ceb57a110cebfd21dd4831f27d456615508745fe9bc39cc928c7", "audio": { "firstSample": "16073", @@ -470,7 +470,7 @@ }, "mask": 8, "frame": "fbc72371aaf008d91add1fef4987a513d58589e1e050a50d5a215b631f85c055", - "memory": "d4209d96082b14f8678ec0d7202a3ddf5efffd693e98bb433f0f847f683b12bc", + "memory": "158a086ec48250b07baf5331b2cbfe527c1e9079e1a7b1d17eef18dfee656965", "wram": "9d46deba729e1efb3efabb568210c4960cb874f239d7cabb6c7a9b24d9fe6482", "audio": { "firstSample": "16876", @@ -491,7 +491,7 @@ }, "mask": 8, "frame": "b050b0ec00c51e0085d9e2525343254133d673a01975351ffd10de16638d6ecc", - "memory": "a229f6bd580e00713f4e86c89e4835e41dd01a4698947282cb4cb70327237399", + "memory": "6c2d2790c0117d72572ef41ee691a085e57a196f038ba4b2ca07c59137ffe12c", "wram": "286bca08f100ab6bf60b440703459ae3fca30378ac5c718ee9b5b629875de3fb", "audio": { "firstSample": "17680", @@ -512,7 +512,7 @@ }, "mask": 8, "frame": "de9cc7c4c263136f62b4da7eb4dd65fbbb1125232f3248a195de3f6fed59aab6", - "memory": "0a6d11062689d993292f25debca93574485183d5d661c8e9ed9f4b3d4c681e6d", + "memory": "f72182171e32fe4fa4c994ca9fe08af46db77e117f67d7314b36f63c9e938b2b", "wram": "07aacb020eab56d46b42474b5265a03f118176ddabcb45ac6a1e565cb1b04dcc", "audio": { "firstSample": "18484", @@ -533,7 +533,7 @@ }, "mask": 8, "frame": "c6d09ca052f3e21982da216bae98d2fd3d3c588b325cb27f8bd17abd599243cf", - "memory": "da80335b3ca30df11550502fc78e00671fcc6c95b217b0d8e9bab0cac9502196", + "memory": "353ee19a2eb64204e7cb9d109fc692ad88da1fb2972a0773d2281589290b5029", "wram": "6f0fdec1c4879b20b83761cc1b58294f65ab46ec72e0d5d1264ae4dfed430f7f", "audio": { "firstSample": "19287", @@ -554,7 +554,7 @@ }, "mask": 8, "frame": "debc5a0a4712def5eaa8f95a9014f258c4e0f6cc3319d562d426f757269e5f85", - "memory": "0a4737b1a0a43e033bbdd8d7b3e377eb0145d1892cff6eb278ab1bcaaabb1094", + "memory": "033043ab5455398cb5f0ea3bced4a3ba409ef97bd2280c8a55966736627fc696", "wram": "a694d38db7a58ed60a033cd84a8f877e546906f425e052f53e993b8f7ed03aeb", "audio": { "firstSample": "20091", @@ -575,7 +575,7 @@ }, "mask": 8, "frame": "22882827b8b6e95e5c4594bfa746daff156b228e0d2c6cdea9bc59443f9d51c2", - "memory": "a3051da16d6e0d47d5e551abe2e0b0ace5ddb330bdcecbd47b17c64b55563121", + "memory": "a375ce4b4f7a4f3a0855bb99d032d18ed7d3de8aa0ffafd0cfa7438cf5feac48", "wram": "c9f3892d4530861ababd661dddd5a4bb121ebeb56216e56d5165edaddd456d8c", "audio": { "firstSample": "20895", @@ -596,7 +596,7 @@ }, "mask": 8, "frame": "ddd6645f0d798231bd892aa38e12eeee34aaa73c3a8ad7f4064a36409cbee596", - "memory": "e43f4a04f255aedce0330c7e1c398b2c599346f207fd23c4e8eae8900fc49bfc", + "memory": "15f3c7654d99740badd1fa53a187a868db1b29e6de3eb0522f2ed542348c5f9d", "wram": "24cda2fd2de2226aca415ccc800f4f3243d5a57d4bab75d86d334755190b5e32", "audio": { "firstSample": "21698", @@ -617,7 +617,7 @@ }, "mask": 8, "frame": "48938f83b17eb573ab340182ea70e6ee14e0d18369e76dd8f78fda4455cacbdb", - "memory": "939bb78472cf9f2cdbfa5b301dd4844ff6cac82dd5eed6e618f1388c5c14e91e", + "memory": "a5c1356fea320ff56637108f5d8a481489d03078e1a8d9be0989ea01c56a7dcc", "wram": "aef2e51914a7076ebb8ed84bef179851cfcf5f18964a5a5b768614bc8a040e29", "audio": { "firstSample": "22502", @@ -638,7 +638,7 @@ }, "mask": 8, "frame": "8d846d263b0f171ea8c5adc6dc7e2bc036abcfedee7d1f9d44c849541c3024a3", - "memory": "9b62e7b02b74f5cb30692d5216e4232053e518c5ba9e62cccab59124f7c2f9da", + "memory": "ec870ea08344fc9adb4b0522e0906701b55b00305f8261a0bf387120b41e7202", "wram": "6d424492644267cbabb0f2ba6124f6233e0441a58cfef6c71fb96df1eb19bf6b", "audio": { "firstSample": "23306", @@ -659,7 +659,7 @@ }, "mask": 8, "frame": "64768d7167e34d306ba9083bb1dc7e65e6123b634079787faa19d0ef3798de86", - "memory": "66278bc8057194b81bf22fad68280b50e5035a4d8a0c5233cb8f80d172fac2d9", + "memory": "5df84a2cb48ac24e72a5ea063f24caeca2e929bbdc368306a6adf856dc07f381", "wram": "fd666c21dabe652d5a961e8b85ff4c93367d5519f588d860fbb4ba1ccf549ea4", "audio": { "firstSample": "24109", @@ -680,7 +680,7 @@ }, "mask": null, "frame": "64768d7167e34d306ba9083bb1dc7e65e6123b634079787faa19d0ef3798de86", - "memory": "66278bc8057194b81bf22fad68280b50e5035a4d8a0c5233cb8f80d172fac2d9", + "memory": "5df84a2cb48ac24e72a5ea063f24caeca2e929bbdc368306a6adf856dc07f381", "wram": "fd666c21dabe652d5a961e8b85ff4c93367d5519f588d860fbb4ba1ccf549ea4", "audio": null, "state": "a92187ebda5a7ea77d82a40566678177b8e29208b61de01e2fb6e0fb569c690e" @@ -696,7 +696,7 @@ }, "mask": 1, "frame": "a050ca382016f826839cbe4c25040e24c8c225a254da33b943c7c92f6e4fc037", - "memory": "5d275d54f384b0e8d6c156b6aa0e739927ff4d5f4ed5db5d00edb6e519987231", + "memory": "97028f96be04ea022ce16d48ba4dc64e4cac3a9a3cbd3ae19a90fad7f92ff4e3", "wram": "00f25d551cb2d5eaa17851ecad457e19b5933308f447ad6d52f5c3c65cf97c81", "audio": { "firstSample": "24913", @@ -717,7 +717,7 @@ }, "mask": 1, "frame": "d8139b0db41c1f39c72be87e25a23b40472057aa93c737a3f8f66b269952fa1d", - "memory": "406c977effc02283c4d167cc3baf1433d2c485cbfb68aa58a24b70b746e7f3b6", + "memory": "dd327e9082a24a5e89aff3d1dc2b9add47521e89602a093fa6f1d989138149df", "wram": "5270455eb61d0ada3eaf41e3f6624614c49cc65c3fe8057953902e1935974b93", "audio": { "firstSample": "25716", @@ -738,7 +738,7 @@ }, "mask": 1, "frame": "9bbefd79b32433a4e8b0428da0459326afe7efdf010d3ced5d5a17d14d180fa0", - "memory": "f9329f7f5c8acfc9c63e7093fe8ba6eae6cbb41614b443e9614d321583ce9d82", + "memory": "b0e753fe027d0bbf711b071bb954d6b46153b01772f9fc4005f048261edcff5a", "wram": "1b43d2faf5682a9a74c185b96ae1a3e8cb8c4f55de26572171b97c0eb680b3c8", "audio": { "firstSample": "26520", @@ -759,7 +759,7 @@ }, "mask": 1, "frame": "bb6238215feb130d609fe9f7e78217861b2121ec4cfaee6f36ad64eac3dde799", - "memory": "1707d900ee1791df38fc543d999471a1e875f02e35dd2aab84fe0f60a259113e", + "memory": "941492dc804fecb7934b1ff5428ea105a5bec4fb7e029483b55a3fcde83579e8", "wram": "bdeca712b01ffda68acd4a3a56f8bdf1494d030d06fb0f370d2fbd83eea8657b", "audio": { "firstSample": "27324", @@ -780,7 +780,7 @@ }, "mask": 1, "frame": "1af800af522b08b0e5a4b12e9f22d77b7def8b29ff1592d37c4b3e82fab2f0a6", - "memory": "a275f9f2107616b53ef374b55f170a2fb11ee8a717a89f084c424b3e03874feb", + "memory": "645597cf42aeacd81199de7403daeecd0b485bc25497122df782d8cc16c2caea", "wram": "45acecb148b4a974cc16ff6f5c255274e749ddb9ff5b2916b2ac24a9ca87968d", "audio": { "firstSample": "28127", @@ -801,7 +801,7 @@ }, "mask": 1, "frame": "c1ea74658fd50c82ff511669d69f2c138745c645e6e5e31cc73508bca41058e7", - "memory": "148b53b8b18330dc3d7ffb0472da0fbfc32bfc475a423a88d3c6c9531b2c7d5b", + "memory": "56f851d1f82f151451d838845aed1ceea92dc1cd533592bada0b5a9c08da7ff2", "wram": "7878fcca297a5cdf853dd733bf4368851a70bcb411b976a6b41e19fd84cf0971", "audio": { "firstSample": "28931", @@ -822,7 +822,7 @@ }, "mask": 1, "frame": "dfebb4ab61b3df55c695afc7f14ac2e046c4ae61c2177b7fe5d9121a0980dd47", - "memory": "c185bc0757179cd04306813047a56bfc6b07f0afdfc38bc9a6e20c9d0851555b", + "memory": "a61fd1c8a22f629fbfbe2731cf300ef794077c021e9cdb02412a78ab578b4850", "wram": "4746b44bb5f8888ea83e4eaa659244946afdb8c13e1bca1dcda3c743332be90c", "audio": { "firstSample": "29735", @@ -843,7 +843,7 @@ }, "mask": 1, "frame": "26ca74ae737a7a9a789d7489aadc31f3c1b47b71ffced1d437a8250037a9b58f", - "memory": "4c51674b92bec2d50cf20c9813acf33cab686160aaec66e63ad04e476d6d619f", + "memory": "20fbf7c81d6e45e4233a3f444053507ff4f3e5b131822a5bad74dd938aee57f1", "wram": "499a57c4a43835a1f5e4155b5fd01014a3a0576c74d2ca42a2f3a2004e7b4ef6", "audio": { "firstSample": "30538", @@ -864,7 +864,7 @@ }, "mask": 1, "frame": "039e8af968520b3444adb52a93d624a8767a3d58b34bcdca7e60cf6c24ea4986", - "memory": "f2359b8d86682fe75379502de15da6f51a4ce2731b81dcb1207ce10dca4eda2d", + "memory": "75af082f5b27235260369d8b8cb0bb447b4576042c350ed43fc3d57798c89547", "wram": "515153bfe02a44731c6400a2fa08c1e2d7f24636daca798bcff160cbeb886212", "audio": { "firstSample": "31342", @@ -885,7 +885,7 @@ }, "mask": 1, "frame": "18f4c2289b95e3fd6295569af945e328697f4197c8920adc3a10c084fbb53c56", - "memory": "218aa83c013bc59c1ffdbfac627a5bd4db9d3c21a57c35dc5be86f2cfcc05bc1", + "memory": "1bc85d39240d2535f8c9986e7365dfa77e469deb22e81accdce87c227e3cc498", "wram": "ff785c2649cd8bcfc8c02fa174f6408c44f97973a8b4b84a5f46ff9382751316", "audio": { "firstSample": "32146", @@ -906,7 +906,7 @@ }, "mask": 1, "frame": "200056b02ca588f5e40fa1ed7f050205e74d051518e9bf1b25450acfc5bf51ea", - "memory": "8da83def88cc25203d22b6b7c32d96b359e87ad295ed718c8dea7471034ce525", + "memory": "9ee9601706eeb26396c5181539a607ff80bbbac78c89e4ab63e86135b2635711", "wram": "dec8114b939629fb3b4d99f87759c9f07dd80d235e8f67b7fe816b9b1f6e5bf9", "audio": { "firstSample": "32949", @@ -927,7 +927,7 @@ }, "mask": 1, "frame": "2fcd46f1b520b7949e9063c4e4d74d781e3e906d6358e70fa5fd149bb0d19d06", - "memory": "1e937852c1df253d9f293c7a4762118dac2168fe50c214d1485699da39f37b7d", + "memory": "723b77fe10b2fa3d660f5b11edf682d22d28e3926f7c9ee31962dc387dc1d90c", "wram": "3cac711f86972c7bbcad5619e40898699336bfe7217f291bf8fe004921095ec1", "audio": { "firstSample": "33753", @@ -948,7 +948,7 @@ }, "mask": 1, "frame": "8c9572abe7d6b4ce97bcffe58c3ea372a72ebeed778098e32eb41048edd8d560", - "memory": "c211c33fcabe25be04431be13bf3bbab36536926b4ead01bbb5df25bd10d9e88", + "memory": "8121cfb25deaaa2b5f52ce7c367b344a548ce0f409ccae533689f8f7256503ac", "wram": "be72108bb43518a7e13ea615bc641f6f5bdf7e3e81f438cf66808ac384dc16a9", "audio": { "firstSample": "34557", @@ -969,7 +969,7 @@ }, "mask": 1, "frame": "7f22d8431f7c21182ec14bcf1bf4db85585074597797a0e08c981c0fc8b3f9a3", - "memory": "438ab1efda1aeb99fcf0a71c80db853929662e02b864300f8f5cffe0f6a5289f", + "memory": "34900c7b8e673057f80ad2129aacf6ac1096295f0d226489ba11bf443d6e7659", "wram": "67d93c6cc8c62481e281fa7538d518c27af6fc34d5027696553b19ab283d18b0", "audio": { "firstSample": "35360", @@ -990,7 +990,7 @@ }, "mask": 1, "frame": "60b84b3d90588daa7fc7b319d1f107902214ce3c3e52381371dbf4284c10660d", - "memory": "4f178169e2da1879adadb1cbddc20994ea397c663b499b28b59002c65add2ecc", + "memory": "bb9465f5f3afa6eb40612585efae4b247cb7ad24763a1f647be7ac428bcdcc30", "wram": "0d7dccaa4f517c91ddff224869a288d499f0be872da311ef075ba330af8f07fe", "audio": { "firstSample": "36164", @@ -1011,7 +1011,7 @@ }, "mask": 1, "frame": "7f22d8431f7c21182ec14bcf1bf4db85585074597797a0e08c981c0fc8b3f9a3", - "memory": "894ebedfbda45b1dba2d6b5c81b94e9a04e48aa7e2ffd87fa6c28ed4b32fe035", + "memory": "a46dd10f60ba550bd726185bc3480a590ef6502b14697f811844e3f2cf84d7f8", "wram": "56bee67b4adfa5818fc538f3bf68088312269d770ef8f934eba2920d52158894", "audio": { "firstSample": "36968", @@ -1032,7 +1032,7 @@ }, "mask": 1, "frame": "60b84b3d90588daa7fc7b319d1f107902214ce3c3e52381371dbf4284c10660d", - "memory": "af4c44f77becce4ccc6034aa3f25512a1d24fe3b3cc4427cfbe94630afb52640", + "memory": "477f008624dc3267441139f5dc137cd753cac8c6821066a15dcd31cb64d518b1", "wram": "72afca59f6a4d06f404b7bbd4ac3373e88e22fa4a5f83eec73a59720be8c5db8", "audio": { "firstSample": "37771", @@ -1053,7 +1053,7 @@ }, "mask": 1, "frame": "7f22d8431f7c21182ec14bcf1bf4db85585074597797a0e08c981c0fc8b3f9a3", - "memory": "9e2e3d03e59563156678868c6cb57a8780abfc74cd890107ee5f0cf499baae24", + "memory": "470dfd8175c846fa6e3adf68c277bb0eea9f671241544b2dc60f24bc2550752f", "wram": "5e8b5a9fa3a836649e4846352b9b2585f897fbe2dccac9075de3d99af32bcb94", "audio": { "firstSample": "38575", @@ -1074,7 +1074,7 @@ }, "mask": 2, "frame": "d4c715ee576697b4a4820bca4d01a5d292bd3e9478175662483fda6f091b9999", - "memory": "e1124940b076ecc25d12194b0368922d03960545adc775e245b368db86a00787", + "memory": "4f5712e8617498cad630e9872aa7d97aa3588d32d8256dd19d7f158cd1a77211", "wram": "10d14d0058535ba7c18f1ebf9e7b04558eb1cea66aab83db471744c7e5598889", "audio": { "firstSample": "39379", @@ -1095,7 +1095,7 @@ }, "mask": 2, "frame": "a4fb8fdb51c58b199452d45fe8176e69f17713c7fb5524852c18ec16829d21ac", - "memory": "c2fca8e9eac4df19fce34595191dc195b979ef65f09fbad5ee9bed857a2e1651", + "memory": "914c02db5181aadffedc7adf34258ae49118c8ecb1479cfabbbafa7e7964a25f", "wram": "039b4a0d24cf31e79eece9ca6d227b349e3a01f1c77650ea2914ee187ed53c22", "audio": { "firstSample": "40182", @@ -1116,7 +1116,7 @@ }, "mask": 2, "frame": "59466412ed8adbe2da60d11091ef7e1b460a712c3964b734fe79d174b0509721", - "memory": "76c52e4789d89894ad01c70cfe7ee9adc28ace963583794222143668f63cf25c", + "memory": "5063e6176a7ce3ce6e9dcd595e32d1dc36c984abfaa441c0e5b55c739ee89f97", "wram": "c6ba1291867dcb23fc75dca9ad792ea4c733a277ca754536640ea9dad655399d", "audio": { "firstSample": "40986", @@ -1137,7 +1137,7 @@ }, "mask": 2, "frame": "02f57878f15f64f4dbb64dce297ef8b666693162bc5cf635a2ec56d15bba24b7", - "memory": "4ea73a71b9e8b19a52b322879fd6337478cef829e20fbed8ce897189b447dc24", + "memory": "e0b89149c66487aec516d56098240444254b9cda80c15126de03b6df9cb30f62", "wram": "b0acb846630aafbe133e5ccb8a8e9861c071fb3efae5ae89fe34ceaeffdb9685", "audio": { "firstSample": "41789", @@ -1158,7 +1158,7 @@ }, "mask": 2, "frame": "cef6896edb6076ae9d0291bfc16ee62817d967d07d0c2a9619c36645f3518fc0", - "memory": "4e3c8512ae532c88c407780b197de6e55d47ed8b1c8d35bdae6af621b598e27a", + "memory": "788334a803d9c7d2e0aa5ae653ced8c39694805721ad12f5cc1a61c0e61d984d", "wram": "8586e560e733fae81d454b2043542c46e8a9ec7d10ad6f8e1d45fde50a5fc3d9", "audio": { "firstSample": "42593", @@ -1179,7 +1179,7 @@ }, "mask": 2, "frame": "cdc5b08a6e0b2da69e4fe9cd961ca73b2828809caadda13c9e127264e5374465", - "memory": "ff3a7adfa4a594720363868920cd4099ee7c84aa3d6c9613b3ca35e5f3b060c7", + "memory": "9a8fd94eef73eab427cf2ca0eabb20dc60bb32747b708360d739f159ca3d0604", "wram": "61e9cbe5eecb25d7a1961e82b7af0d23a0008cce1ea29d6bf2f8bc2facf1ec34", "audio": { "firstSample": "43397", @@ -1200,7 +1200,7 @@ }, "mask": 2, "frame": "f606666cc532cf8be17672bc1fd43ca7928b6d1ff5c54be611d0d4ae52ee1041", - "memory": "e056cb370d043e8ac70ad98cbaf906b4cd070749d57e31df6569d221f94e6bfc", + "memory": "74fe3bb37a458e9c7227b4276dda2d7eb5976677fc0452785d2c44a84e46f050", "wram": "2951398b9ca06155ca990b0d62a95fe7a73f4d92498a02a80c19d97d411e8a50", "audio": { "firstSample": "44200", @@ -1221,7 +1221,7 @@ }, "mask": 2, "frame": "94ba53bf422817d8dc5b142a554366e3baa4ea20df596ba2a62f97e07769e89b", - "memory": "d0ace0c488606fb08861e20d1a80d6793624b5e8a84d985a523b07e3e84097bb", + "memory": "d6d45b23d05cc429eca0963f07ec321352352644e5b0b34f495d113d76d2ea24", "wram": "ffa2427f9f9dc3f3e2cede7aa31b2fe85d18871fc5443fa60bd2ff71d3c5815d", "audio": { "firstSample": "45004", @@ -1242,7 +1242,7 @@ }, "mask": 2, "frame": "918304a0428502b5c0aafd48e5f4c617351f72c39d95a9d857c1f48cc374eabd", - "memory": "c0ae9cf9c02951364044568268e71e0ba3d702dfa38d805a3d7dcb9be99d98f8", + "memory": "1608ecf40fefd125f07afa2c80872b0e6c214165e7cb68fe70ecdaaf6676ac97", "wram": "4ff4c74f1ca0c8665848ae57014f2ebe187bd84681619afdd43f6742705269b6", "audio": { "firstSample": "45808", @@ -1263,7 +1263,7 @@ }, "mask": 32, "frame": "fff758141fce2432c52d471c1ea3d934bc7783d50fb1e1c06d3b4158373eb56b", - "memory": "7a05408993bdf68bd5cb8f384d458d5b1e329ab2379c321d94981d481afcce45", + "memory": "f5bda201499ef79e7f882e987fe69633ff7718b33dc752de5b1ab2c4deb20fb7", "wram": "229c617d30d9ffad29b7d9546391cc07d50647a8e419afb434afbc7f8e082560", "audio": { "firstSample": "46611", @@ -1284,7 +1284,7 @@ }, "mask": 32, "frame": "15677644545269f92cd30cfe2ea852717316221746cc2c803d23d76a3ef85a6d", - "memory": "a57a2ad6d523fb4cb7e6151b7fb5aa203809c08392cd8c29c313afaf76f5844a", + "memory": "c4a35e9282c6117da57993d978e833205fe899ff9b6e73c2d902c5676a5478a4", "wram": "6ecd448b6d3dc9477eb5507b8328d15032a32ea120dc75d40b9fff1f0e5a6c03", "audio": { "firstSample": "47415", @@ -1305,7 +1305,7 @@ }, "mask": 32, "frame": "e0777dce09d2b3f902ce43e5d560ef35e4fd4292f7caa185cc7366b44fdc5860", - "memory": "3148b27b8395ece513dc1971f37e8df5693b7d0122877ee04fa1845c0046a775", + "memory": "6e757543fb47c8794f51bc80d87f46fe4c471f5fc7e80687300c33b90e6a284d", "wram": "acb6c9b1338c426e45dd340355a61ceae16581fc2246215752c417f3c131f588", "audio": { "firstSample": "48219", @@ -1326,7 +1326,7 @@ }, "mask": 32, "frame": "1221b3e645e05869bd9fb35b5316f37b4307982bf1af683eb7c39af87f2a2967", - "memory": "eb208bb1c93b1c6e434777b70fee7692a4d46db4111c83030300875fd107f0b7", + "memory": "e62ba70f20c055c3f6372a11c9024d8ae49ef27a21b53a0a4e411a9e68610999", "wram": "90fe2e842a21aba9d3f543342e31752278d902ff5ec5a97d74c048f0c8e3b804", "audio": { "firstSample": "49022", @@ -1347,7 +1347,7 @@ }, "mask": 32, "frame": "29ae4b3c474123931c1eaede26b60ca3bf1a43bfe6c892dcfc4b63020c80f336", - "memory": "abdfbc9f5b2f38d888c60c9244b6ed581dc367d24b2f9f1978066ac5a4857fb4", + "memory": "6fbc45db1bdeb540bf19be9f2e8c31398b6480880183572b4aa90cde3646c163", "wram": "308c16046bdedfcb401396eba12c900d0439b096b1a14c7f928d483c6fca65a3", "audio": { "firstSample": "49826", @@ -1368,7 +1368,7 @@ }, "mask": 32, "frame": "0db81ebf53100bec4af3862a3dcf53afd3ad736e1ac7acb408f44d957469e999", - "memory": "44d13e8cfe3289effff0c5c9d376b511f6b8ef4e9cfaa370d60c1e364cc50319", + "memory": "e3a2bcb7844adc70d67f3a03e52c514b050811e835a5cdd17b7cc09fc6016c26", "wram": "5c8929e4a2ab28b74f441c6c4fd84defd107fed09923dd21dd1f346c7a8cbe97", "audio": { "firstSample": "50630", @@ -1389,7 +1389,7 @@ }, "mask": 32, "frame": "4d250a37833494955379cf48826c510b2a0cdf23eb0c00f71b9972fad25aedff", - "memory": "01ca84071eeb1201608cab606c659bdb7b14ae34a65918c2b7346cfb3d8f3280", + "memory": "3d994f4a3408f4ce53a8e3d820d3a3f0f97ad354fda6c42887ea5e150d7618ea", "wram": "fdf6fc94eea410530fdb560032dfdd292d22d627796bb81638dcace9f693ceba", "audio": { "firstSample": "51433", @@ -1410,7 +1410,7 @@ }, "mask": 32, "frame": "5882156c8cfc0a882eae507c6b9b0533f93b8113a698bc4a2577004e74e4c783", - "memory": "8c186ccb2838cd0bca8ca19dc8c97e7fac39715aa479eb9b9d38c55532f2c41c", + "memory": "b477e731620c0b66e0eae19449aba284472a00613f51b4606e0a02b3a932956f", "wram": "2b471b93355842bc6ddca559956ca31ba81735f093a315fe18b66624774ee53f", "audio": { "firstSample": "52237", @@ -1431,7 +1431,7 @@ }, "mask": 32, "frame": "bf868c6b0804c3323c0ce6b47d0d4a30d8943c891e7f83b59ca14664b402fb9b", - "memory": "5c2d5d839fc5290d970dd358bd1e29221bb269591ead076e91fccd611394b724", + "memory": "03436fa95f904c860ca4b2ca0384966cd5d4d50dad9093c33e9b7b1f44378eb5", "wram": "3349831fa3bff77c82ce40e8c21307b60b91fdb2aef9821d39d3043afd960df8", "audio": { "firstSample": "53041", @@ -1452,7 +1452,7 @@ }, "mask": 32, "frame": "1513da252d2c50920d65848a905a028d6fdcc7c544c55dd8a16e0ff94b0de3b6", - "memory": "dd7de9442f2564558691fb0dd92c8637ff47b9fa53bc93821a08f8ffbac6d774", + "memory": "ed77bfe41c4494c5e176ae50082eebcc2d642b3f8581947e18263f9def2ca181", "wram": "ad98163a1e70adaee793fc0071fbd1b454314c93fd3a05a2f165d4353884d0d1", "audio": { "firstSample": "53844", @@ -1473,7 +1473,7 @@ }, "mask": 20, "frame": "bd99a5fcf17c2892fff090db1a3280917dd4355be5bfc63550fa71a98f911e2b", - "memory": "4d41698270f59fe18f5b62d7dd5b98ee8584b311ba8b19efdc9d95bfa3e834e8", + "memory": "39ef6939ac716e21578e6082d885e3067c21da7d9de3e2f521d8add065ea7a9b", "wram": "c727af123d968426d84c84d15fa86a582941c66d716fa581c538adb0221e8fc6", "audio": { "firstSample": "54648", @@ -1494,7 +1494,7 @@ }, "mask": 20, "frame": "2254a74263113c999f8fb23968f7a25925728d6da267fcdf19df725c9b9f6409", - "memory": "0f6aea4a29de9a24adc5e2c62903fcef827756e6f0165bae94ed5ee76208726e", + "memory": "16b928cc470b11376eed155f5fe37c75f3885e4ba8c2d72b734ef9121dac1d70", "wram": "914357fe6563d531bf6d8f49a03471e0b39a547f54543b272eee45a4b3b454f9", "audio": { "firstSample": "55452", @@ -1515,7 +1515,7 @@ }, "mask": 20, "frame": "fe296bd399c71d25516fd32fd21de38c26b9fdd738e8057210dffa915383a9f7", - "memory": "c74f050abd80d6566755dbd343ef8fece5631da1f1c2ad43afa364762bd582e7", + "memory": "2a9500f1ab72744852f1fb515f6d203a02d7a9fa04ada524ec5fcb8108cbc23b", "wram": "926cefe3cbcc066e32a5bc7f6163e9134fc168edead57abe4514778035dc28c7", "audio": { "firstSample": "56255", @@ -1536,7 +1536,7 @@ }, "mask": 20, "frame": "b271a7a59f177591a8b2c6e59b4b60af9f96322b149d2e20d8b0af640b6b75ef", - "memory": "62beec6ed310d053d1f551aaf39173b9c0bfc95a739feb6093166041f126704f", + "memory": "efb91d59754b84aebc5293e997b1b794ba3ee5cd1da52575192fc2603ea72288", "wram": "9d50789b14c199c929b81224697ac367ac4f1afed5d74e4213b512bd3a045ce7", "audio": { "firstSample": "57059", @@ -1557,7 +1557,7 @@ }, "mask": 20, "frame": "94f44b0ec7dc130be97b3bc24bc312229fcce89f4c95f1a309d0e455cf70b9ab", - "memory": "0e4596fcc489f532f4b0d95cd3fc6cc88d5ef84b75e4955d6beea76d85836fb7", + "memory": "ba59f5843d11b38a17985023abd0896762e0af9872492f693db003d839ceee16", "wram": "1ed1ebf12e5c6d0b95252df02eb1b2db74bb25379bced1b43f7b2329e3b45d9d", "audio": { "firstSample": "57862", @@ -1578,7 +1578,7 @@ }, "mask": 20, "frame": "c00087978e31a8f87b88aca80ca87c43937ea4cc2cd438d464603e4a3d5a2192", - "memory": "be1bd1620fa8aa30f610b6b0d8d8c02ddd82f08272c6db68eb820cb130207415", + "memory": "9ab17a2d3a311a59e0af7747e7a6eca3c977da85f76a956f7d3d1a8d4feee50e", "wram": "2b46f3060c9df31241e15743e16c46c603b26f93b1a0ceb2023aab5076d0bd76", "audio": { "firstSample": "58666", @@ -1599,7 +1599,7 @@ }, "mask": 20, "frame": "86db5e819c85c9122f7399a39a4fb377f8ae7d77bca3428b16d8c9b584fd7e05", - "memory": "45b8f84dc1be5177d2d87dedc4080091d55acc53c0c46850832eebc34b820af5", + "memory": "fa945e44826ff38244df712ab7b8c3a4ce442d942f8fdc051c7febd9a851611f", "wram": "13c3194703d58a23bca6d3954e8fe6e97e72ff7fdfaba14302fc0bd15a2dad2c", "audio": { "firstSample": "59470", @@ -1620,7 +1620,7 @@ }, "mask": 20, "frame": "9eb66851792fce5daf4f13d2db560445cc824cc5ded6498acf7406bdb41c692f", - "memory": "c6abf076e455984df387194fcb6a576af3fbdc2798a83b4c4bcf82c7a392fa00", + "memory": "99e2afbf271916bcf877eca2d1f2f06750a61bcb3bbc3987fe35f419669e60d9", "wram": "bae05a83c6b576e97b97a948e8b33383b3c839e8656f1a08c46e76225b7d833c", "audio": { "firstSample": "60273", @@ -1641,7 +1641,7 @@ }, "mask": 20, "frame": "8f19aa8bd0bdbe67a990d40012572411c0afbbefa63f41ca9832977ea5546095", - "memory": "648f1e11ce55415b8fa6f29d2d47b0a1a9fc9acbbcec4d1e839b610de1fc9d07", + "memory": "365c9ae122d75f90e36a609ca7349ffe3216247c3218e7d1dd14cf1e076bc6a7", "wram": "15a97ba1c7a266110fe273d277857af115e037eee1839c321a33b7572fd29033", "audio": { "firstSample": "61077", @@ -1662,7 +1662,7 @@ }, "mask": 20, "frame": "ba1656c2c20fd461a15a422031b4708584ed391a44a771379f462fa0cf9a34ee", - "memory": "60b0f6b38ddc0addde4ec2ed32a6be810fc2b06b90214dc85aa8a9ed45d6a8d3", + "memory": "de15152610404213f0a79dc8eb913d3b8d2a047ae86c9f5637fc9f56bc44a938", "wram": "1bfb81ddc750ff932e7abbb00d697ae978088179f910d56af9bb105d44b8cb7f", "audio": { "firstSample": "61881", @@ -1683,7 +1683,7 @@ }, "mask": 20, "frame": "0a2037e89376b7a5989b04e4c2fabcd80cb3452eb5be9c589258455b0095e253", - "memory": "da78d6565d9b5e249de2ae3ed3b87ba2171e8aa822323d0c2c3bfb51a45555a4", + "memory": "24959dbfc1d242cce7b0d8e16232b80b873cb066dac645c3eb9a51190d50f27f", "wram": "993d3c2a0a9279e30a5f90c34a58c04f242898712569ee1104f655e024e5440c", "audio": { "firstSample": "62684", @@ -1704,7 +1704,7 @@ }, "mask": 20, "frame": "62285807ba56f3d33805d75acd53fba78005f7f2a47b52195c99d5a97bb6d88a", - "memory": "ecc8dfb02e1b61df188cfdac51ab6d71bbd7c2d5301f868ec334269e652986b0", + "memory": "415a008e623637889ecdd0911fecd8011c05d95043145c1ca31f0199b7b3ae19", "wram": "e68eb2211c9c184148e9f655ccfdfc10cde1a8c23dfeede9c43a85df277a9d27", "audio": { "firstSample": "63488", @@ -1725,7 +1725,7 @@ }, "mask": 20, "frame": "ae38a20fe906437541241276c612fb4ce067be783f02ca4ab32252c0de4d1d76", - "memory": "337d763e3dfb080ca0d5f8d6a93db841443eb33e17a18fc951e7ebde495abb2a", + "memory": "5429fbea77dfa1eebee1388685f477e6e8dafa9edb17cee565afa070c34dbacd", "wram": "c08b1a05d9138ea71788add2071e1d8d4e2e2461bc6d1eae451f0e96d966ba2b", "audio": { "firstSample": "64292", @@ -1746,7 +1746,7 @@ }, "mask": 20, "frame": "60a8c224d4b27f0a444413b3b3df048da39b792378b125dabd1aad6875c2a167", - "memory": "69d7f4289fca72bf18d372aea4c54a2e9292da7abf8974c473cf61a2dd4391ea", + "memory": "d69a60d163b1e54d53540c00905a87146e71827a7b975f191acf9821ffc8c8a9", "wram": "466867c2dded8e78e68cb354e35e0ba624622f57464c932676268544551d5ecc", "audio": { "firstSample": "65095", @@ -1767,7 +1767,7 @@ }, "mask": 20, "frame": "2e932f1dbb6e50bc5a2066087a9aa13a9d3f5b5d12ad57a670493881a30a1631", - "memory": "e2ca76243bd003afc9ff34f9e6190c6b84ca88067a57c39a75416bf53819757c", + "memory": "7361aaea414d38b0ec806119d6866d0c012feb994d33fa851bdc56fc220feead", "wram": "568a7415214043f00a59f4b9046cee3a5b4e7730f6be02c0adc1ce93a517f5ca", "audio": { "firstSample": "65899", @@ -1788,7 +1788,7 @@ }, "mask": 20, "frame": "8fff969b08bf57e097cffb8f5432e2f19aed168812905b6dea868720c8f38728", - "memory": "252fb9357c1428bd0d7f3f51745e99efba716996404b5b863ca702c944da3f38", + "memory": "3fdd1cfb572e1a0f267c2a49f76d7e96d3ba7b6ab4363ab3b2625cc2765f9e70", "wram": "2c22c48f4d47705dc072c2f70b158a9260c6a3772b33ca347ba39c6790782b8c", "audio": { "firstSample": "66703", @@ -1809,7 +1809,7 @@ }, "mask": 20, "frame": "97959e848da5f9cf084b147986a65e58cc8f53746a7c9ca85738ebe3ef46d2d8", - "memory": "696e70bc7b8beffb34e10dd8ba8e265a4bc9bbe7bd2f5946042b2ef4cd3e6b99", + "memory": "1e8bef004656ccc9b1cd6ca10edfee5c15909562b4ad592ca773c1ca0f849039", "wram": "b4efcc1054310f917cb0238ad7e79ac2f1450f07ce8ad216875682d2c3151f0b", "audio": { "firstSample": "67506", @@ -1830,7 +1830,7 @@ }, "mask": 20, "frame": "ab054f1211fc9cd7156ae7ca53d59f33ce5086d33a8cd964adfd0e8fb356f287", - "memory": "d4cb195d8e2bef02be972ac03cfaadab85e6ac2db711bd541b7af7dd59c837b1", + "memory": "8571e36159896ed6e1250a73af0c5d03323ad28d6c1d8105491db323a9bc1260", "wram": "1fabe0679663fe3afed28e186126606dfd310d51c22a7070f55cd4941724a1fe", "audio": { "firstSample": "68310", @@ -1851,7 +1851,7 @@ }, "mask": 1, "frame": "1efe9b02b9dc66a69207c7e8c2529c4d2127ab9fd4e09e16c8c9c1656c2a3d27", - "memory": "76e5fe26ae4f904f54df70b740fc1954b7209518a80263e0e403820388f650fe", + "memory": "1a8fe4a588b2ab36dfa3724aa524f8cdcda18035cadee3b3f019aed11433752b", "wram": "9573a5ef1e3ceb8066909e10810d47b32a7a611d81b9d4c845c965ee1b18d1c7", "audio": { "firstSample": "69114", @@ -1872,7 +1872,7 @@ }, "mask": 1, "frame": "bd2a22aa0f38308dd76e14102fc987dc85fc9a8e24569c6511313fa96295bca4", - "memory": "3a1c409456ca98b99a05ae6fbd33b01593191e48ff06a99e38dd57d3ffa28f11", + "memory": "e9c9df36958cd0dba6abb7553db372cb56686aeb6748c6ffabd7234506378d4e", "wram": "20b68949965c022d450a0543c15ed56a5f71243d1a4958070afea7d1832a662e", "audio": { "firstSample": "69917", @@ -1893,7 +1893,7 @@ }, "mask": 1, "frame": "64f577029bc0a1662682f3aaebd6a38c50293b23f67c45c15eb51f3141158860", - "memory": "1be4e63892f827f2e4af84330e1eb2884ff7109f616a68089f61091731112b2e", + "memory": "90c85465fd606d80c5e18101aacb851257be7ff3dbdf8a3b58e95535b27c1e93", "wram": "9e3df7942d9ab22092b212c2b8a120111120bcbb9776f4d5d132470982dc1969", "audio": { "firstSample": "70721", @@ -1914,7 +1914,7 @@ }, "mask": 1, "frame": "c47ad1b65520de092657d1d9f430db280c734c9233812eb9572b25f94196bd66", - "memory": "e142e7ec244eb0b9556a4f40c2902d181fb2915cf2cff870f6b52f85500b50d1", + "memory": "4d3f070c39780805dd58109c3bd59eeae71474b11bccbf435bb0b34274f2e8b5", "wram": "31a922f6a8eae12a21de93eae820d1882858895978f73c38e3ae054159877c3e", "audio": { "firstSample": "71524", @@ -1935,7 +1935,7 @@ }, "mask": 1, "frame": "b3932485be7c2a61d3d30e1d8a0f68ce3ced806dc20e2f6c0457dc595264d3cf", - "memory": "66fdb61a6af5eec2d8810dac27ae8bd863e3ef3ec4930257e3c6b7c7a8ca4a31", + "memory": "7a13b38cbbc0bfc434b3350ce02541bb3abe87679296842d220de25105c98fb1", "wram": "f3fc8a77841f77675a1dfcdd952629eadfa59c4a0111170272da632492eef3dd", "audio": { "firstSample": "72328", @@ -1956,7 +1956,7 @@ }, "mask": null, "frame": "64768d7167e34d306ba9083bb1dc7e65e6123b634079787faa19d0ef3798de86", - "memory": "66278bc8057194b81bf22fad68280b50e5035a4d8a0c5233cb8f80d172fac2d9", + "memory": "5df84a2cb48ac24e72a5ea063f24caeca2e929bbdc368306a6adf856dc07f381", "wram": "fd666c21dabe652d5a961e8b85ff4c93367d5519f588d860fbb4ba1ccf549ea4", "audio": null, "state": null @@ -1972,7 +1972,7 @@ }, "mask": 1, "frame": "a050ca382016f826839cbe4c25040e24c8c225a254da33b943c7c92f6e4fc037", - "memory": "5d275d54f384b0e8d6c156b6aa0e739927ff4d5f4ed5db5d00edb6e519987231", + "memory": "97028f96be04ea022ce16d48ba4dc64e4cac3a9a3cbd3ae19a90fad7f92ff4e3", "wram": "00f25d551cb2d5eaa17851ecad457e19b5933308f447ad6d52f5c3c65cf97c81", "audio": { "firstSample": "73132", @@ -1993,7 +1993,7 @@ }, "mask": 1, "frame": "d8139b0db41c1f39c72be87e25a23b40472057aa93c737a3f8f66b269952fa1d", - "memory": "406c977effc02283c4d167cc3baf1433d2c485cbfb68aa58a24b70b746e7f3b6", + "memory": "dd327e9082a24a5e89aff3d1dc2b9add47521e89602a093fa6f1d989138149df", "wram": "5270455eb61d0ada3eaf41e3f6624614c49cc65c3fe8057953902e1935974b93", "audio": { "firstSample": "73935", @@ -2014,7 +2014,7 @@ }, "mask": 1, "frame": "9bbefd79b32433a4e8b0428da0459326afe7efdf010d3ced5d5a17d14d180fa0", - "memory": "f9329f7f5c8acfc9c63e7093fe8ba6eae6cbb41614b443e9614d321583ce9d82", + "memory": "b0e753fe027d0bbf711b071bb954d6b46153b01772f9fc4005f048261edcff5a", "wram": "1b43d2faf5682a9a74c185b96ae1a3e8cb8c4f55de26572171b97c0eb680b3c8", "audio": { "firstSample": "74739", @@ -2035,7 +2035,7 @@ }, "mask": 2, "frame": "13edd4761d31e910ae1c9c7b7bc9050074d5bb82ae02f0ae4d7ebd8e3d4f88c1", - "memory": "45ef81b1e29cbb26f62558a400ab69940971febdb196d0e04bbb8171de5715f5", + "memory": "ae39993a273d2e153c15cd0357c4d8d2f02a8d183741c44bdd6ce5224ea4596c", "wram": "432819e20364e12af5f53f48feeaa144540f82d299b15fd785b4a7027253ff13", "audio": { "firstSample": "75543", @@ -2056,7 +2056,7 @@ }, "mask": 2, "frame": "05e1b148120b5aff1b54bb9bca27b5a9a54ccf18ba01e0a13e70b40ec74edcc3", - "memory": "72aa2ed99abbdc493657b1d7828d7cae0c006ce038fdb74c0c9d15c0d671534a", + "memory": "cc02c49782995cca6e105514b64619b2a1ba91470b0c0cb786fbda818a95b628", "wram": "a0c7e35457b8acbeb32ecb963a09104d624915eaacf18958c5d5fecc9ca6eee2", "audio": { "firstSample": "76346", @@ -2077,7 +2077,7 @@ }, "mask": 2, "frame": "11930e74f515e54416d1b06fed058fb8a945b1d83f17770dd9a117612b097ac1", - "memory": "8375151d48e84336c1c6b611815b39f11423a7005cbf43c44096475043239c41", + "memory": "44c0e3b78ecab86c566edddf303f47e807e3b373a42745f0f4dea7049ebe9033", "wram": "99ec77578a5c0b4aaab2edc2f4c04b392b88d4943fb66f60dcb9e843e9e4f94f", "audio": { "firstSample": "77150", @@ -2098,7 +2098,7 @@ }, "mask": 2, "frame": "f3a9b39efd9da389c8c4670f8c9417adb7134e1203dec8c31698ec9c8b0725da", - "memory": "6677b64d777e6f32eda1021d921a42d6cf732654f65efb50417f9a612540e28b", + "memory": "300c633c3e9e94b5b34419abdd3377ee11cda1c6baf2381fd784354b734df11d", "wram": "c3a2d9ec0203289d78bc18143dbcb879a13996f87355364473d04e7e976051d0", "audio": { "firstSample": "77954", @@ -2119,7 +2119,7 @@ }, "mask": 2, "frame": "297ec4e8d6bb142ca1afb7e84e0966c183286c82e896bffe769fe4759bad9bd6", - "memory": "5d70214b207a2fc6ff4ebefb444354aeddc93106f6c8445da3d3297d636dd3f5", + "memory": "ea57cc63510ce7e81f4aa483fda950bc306f16d11d4d86974bc06c59f299e001", "wram": "5a9deb34b6a73eb49245b091dcf79ea351cab2068272841ad044c77913b3867d", "audio": { "firstSample": "78757", @@ -2140,7 +2140,7 @@ }, "mask": 2, "frame": "9b4a0ceba85861be44628384b3a20a449ef5a444b9d5635d9f36f534484b1369", - "memory": "022a211088d454bfbce043ab96fd4fa4ca7315af6f9b062ed6da563b67c942c3", + "memory": "d9dea79f1f96450d59ee3e53c6ee31337f4ace4aa9a7fd264ff2f0a410c12cd6", "wram": "78c6093b304f15c8201f37114348baefbc54808939c0f5268232e291541b0295", "audio": { "firstSample": "79561", @@ -2161,7 +2161,7 @@ }, "mask": 2, "frame": "79125cfff561c5d7ecc107d2477e80f1b2fe6dae15a9f2723ba339869eae9866", - "memory": "a324936006022c915029f2d135a9c6b3e1c05c14870637045da6dc4d7fb36c16", + "memory": "bfa8cf645d5e56515e0c3660d397df9df72a6ba8577cb7ab0bd5151415c9f9c1", "wram": "efd42aac00968f22f1034de5539d966ccc0ea102baadd3c037cd7d729f847dd5", "audio": { "firstSample": "80364", @@ -2182,7 +2182,7 @@ }, "mask": 2, "frame": "1a6dbc6daaad597c3b0e3b7776dc2e4198a1df4e6a344376a97b14bf290366e2", - "memory": "2d4904fafe23818baa196edf49576a87cae333a277edbcf167fa0287e3b029f5", + "memory": "0ac70893163dc9809ded8c1c783a5eaa7f41b5e29c72094802a00c21a7cbb6b6", "wram": "14ed197c70ca361faf758f655373e0a96ceddaf1cb50d96af75a148b893968e5", "audio": { "firstSample": "81168", @@ -2203,7 +2203,7 @@ }, "mask": 2, "frame": "6a3acc16cdbe2c78dfea0d0bb1a4bbd12e1c7eb9e23ce44dffb524662a329972", - "memory": "589763e10d843e7303eaba1ac2ac2f234d3c51d06652e9ad886a84bc36b24ae1", + "memory": "9233c8cab1653a22f76db7a96cf03aed9bfa8f6cf5df8040123ebc4c78360fd0", "wram": "6b6932a48ac08ff524df4c1e220920f7725a24bdbdac387e5b4d076e21bf4924", "audio": { "firstSample": "81972", @@ -2224,7 +2224,7 @@ }, "mask": 2, "frame": "d92786aebd34ea7c95d581feb55571b0841165df66e68e3e046e24b4d0af02e0", - "memory": "7db1b193501843a11d3160a939ad0d5842859f612eeda0d088add4ad0367b184", + "memory": "c0a1cb5275ba4869fbfb9dd4a3a3d46d81c4c238555ee213d1b3cad491ea6876", "wram": "2a481482f2fc57000619bb93d0b9d468de30f8356249da9bb89ee47b7f399d96", "audio": { "firstSample": "82775", @@ -2245,7 +2245,7 @@ }, "mask": 2, "frame": "4ccd7cbe5d64fb10b904ce3d13b951bec9b603d02ff9df414d6aaa0e38ec936e", - "memory": "1988a18765fbb07694b9f3f46272e4a59416c4a6f293c90aa18711af07ff412b", + "memory": "1fe06d861cee472c161c10b3f5da80457fbfbd64c920f29bf1e9f8b0203dd573", "wram": "54f0d9527cf9b5d6d3cd0013690bf5c2e661fe5179bd3852ea52a1825fd6bcf9", "audio": { "firstSample": "83579", @@ -2266,7 +2266,7 @@ }, "mask": 2, "frame": "cceb4a06c70ab88f3c26612b867d23916adbb6bc4eee4e1946dbddda31485c4a", - "memory": "81e36bf108b4cc4b9e964fc5f48b74fc33e7e85c28b637336eea085291b9046c", + "memory": "8012778fe6bd3cdcbdeb788e91a78892dcbdf7bf87cca3a327adf3d37701d644", "wram": "041dddc5d9a79fe68f9a1d26e34f6fcb9aa697beae42025d03f73a1d5c223482", "audio": { "firstSample": "84383", @@ -2287,7 +2287,7 @@ }, "mask": 2, "frame": "187b7fa1af9f93756b1fd218095aae84db62b8f59d11826843a30c61971b646e", - "memory": "3ef3f23cfa39cb640ae1992f963329cb0a14e84fbe392bd0b9dadc91d1ebc6d8", + "memory": "5cc1624d609a68acdaeab83a937b9de07a490eb5497f39aae14fda562a27be2b", "wram": "996d2b1506bc23aaca250af34150396376d4ba5592a0781cd68070265b134fb7", "audio": { "firstSample": "85186", @@ -2308,7 +2308,7 @@ }, "mask": 0, "frame": "4dd179e5822678033fab2e35fa8b4bc0f3b581c54a42d7e8f6eb270fd7634f45", - "memory": "46cdad61b11ab57b31c70127d426999cdaa8bb2eb3f6569c490ec310cf79cba2", + "memory": "4c95201ffb5685d837869e490e5ea3c2af031e6a033121993ebd0901f607fe36", "wram": "ab651131088f592d62dcf426c4a7f1f85219ff4c4471dd4c72f6c3fc2c1ce7cf", "audio": { "firstSample": "85990", @@ -2329,7 +2329,7 @@ }, "mask": 0, "frame": "473ac086638974777ee5288fcbaaff865b9f493805bc183ee95ea8cff55ea758", - "memory": "24488e509013a8aa2eac1cd7baff5367df14eca39cad87cf21ea4a57be10bdad", + "memory": "dc430c35c47cd73f195664459d8fe3b3e0bb7f789993e4beb96b96051a4acff7", "wram": "c1b67ded2a74f6e2154f0b9fc47ec451aa743c82642b5af11605adb6bcdd815c", "audio": { "firstSample": "86794", @@ -2350,7 +2350,7 @@ }, "mask": 0, "frame": "88da2958f9061fd1a4f5f89bd6545dcf0096162361168c1c420ea26ab9f33f34", - "memory": "b900d2cfed0ff71cdc41f5e6600ce1f7609cc5ae79404abd9a2d52e1614d969e", + "memory": "eef01a4277c135a7a511337f618f79a8d68005ab6569246ba7b843932dd40741", "wram": "866a7ffece680753602470757c6adde2f3c3dc460398dcddd03053c38003bb66", "audio": { "firstSample": "87597", @@ -2371,7 +2371,7 @@ }, "mask": 0, "frame": "292d6d4254750b04c6390442c59a2582956c66fae1597966aa62f7348d76693c", - "memory": "62ea644b9b68538060534b32b3a6fd3f9ade8017722acd8e5fdc926a7a286c6c", + "memory": "8046124d52adb2c68683c47333de7ebfcc748d03ad4f3770844fea0d8aadc9e9", "wram": "d1bd4acd3eadf4c127b0d91f180f2918315df0d7625817123564e4a4fe8b74c6", "audio": { "firstSample": "88401", @@ -2392,7 +2392,7 @@ }, "mask": 0, "frame": "58dbe732d569dffe051a1059d1a606f4ccfefee87de30b8c86229795dc0aa681", - "memory": "c095af2ccc854f7c050306a9733c95d62cfbca99a38b1a12ced9a39a605dc872", + "memory": "6432bced3526f1f41ba767ae374ba1c7b41669ed98c13ae1088cfc941c31dfe0", "wram": "a91e24f9c002b0ef7788b7c75eabb30d8ef9a83821c67319e9de39cdfb4eacaf", "audio": { "firstSample": "89205", @@ -2413,7 +2413,7 @@ }, "mask": 0, "frame": "40adbd462bbcbf282a88aa01d88064dbc59a13f35a5873bb1d66101e08fc766c", - "memory": "5a2830a59b11be9ec183471fd88ce6c05f2d7b23f7031a7d1be6b1ac603e8241", + "memory": "b51e6f7c6b1561db44bc6d49ab6866e131120cad909b8895a9b6876c62915492", "wram": "daceffaeebf7a3a7a1084359a7203a15f83e5492a2b90bad53a0c941aba052ec", "audio": { "firstSample": "90008", @@ -2434,7 +2434,7 @@ }, "mask": 0, "frame": "9fd6d39a48df49b2d2aff8cfde1c9ca8a91e5cbb62792697d6539cb38d470061", - "memory": "749ad85004dbb8cc4e8776c56f95acd33b5d91b9fc72c49f11e1e13cceced2fc", + "memory": "0b222b25cdfdd5fe4b77a53f3d68160da6a7b1506a99236eff91d9dec040a55d", "wram": "fda291bec9f491040968e66085e941a9cf065996291b6a4253bc7e56ef21957f", "audio": { "firstSample": "90812", @@ -2455,7 +2455,7 @@ }, "mask": 0, "frame": "66a67f956f7b92865c88f7c97585644218aa5f98bbad8a78936a0c9a2f4003de", - "memory": "1aadf4922874d5cd4f2f6666732f06392313c1af28a978abfb78eceaaefbe2fc", + "memory": "b9ad39c34ee06efdeb2c067663cff2b107ff48b0332b5b5ca9a8f573ec5305cf", "wram": "38627e02917c67466329d172898416c01b05fc41928a66f9967ee1a669f3e524", "audio": { "firstSample": "91616", @@ -2476,7 +2476,7 @@ }, "mask": 0, "frame": "884e653fee8f8fc4ff945b85d00a5a5a6d719287d1c3f059c05936ef8ba7f401", - "memory": "7c5ab7f0497b9e9f5603ff22b258bfd41455bc7ccc0ddabc5dc099ea983c3919", + "memory": "f657b7b8bb2e1e8536aa011ff3686092620bae43cab0a9aff74cde8f6e749dd8", "wram": "fa815cba37acde7bfac485c07b84e6f5ca1b720832ec1f3f2a4f0d20066b5a04", "audio": { "firstSample": "92419", @@ -2497,7 +2497,7 @@ }, "mask": 4, "frame": "7ae87833a076ba0a75acc854385758ecaa3ef8eb65d4648af4ec9e841df7a8b3", - "memory": "ad0a2ddaa3fc6bc7f53fe7bcb877fb03618fec32f6ccc19d78ab460801a0efaf", + "memory": "846260c7acfd710c9cd213b73ddd204445673917d27ed3db4525e68f965731ed", "wram": "28877bcd41f0ac192984d53268a61c58c23b7469878a4323547391df45e103b8", "audio": { "firstSample": "93223", @@ -2518,7 +2518,7 @@ }, "mask": 4, "frame": "91625c79cf8417f0c8271748eebec4259f395b3aaed9b111c57f55c64bfe2188", - "memory": "34b4226a620f1bb69b306981ff13ed7898d37993923a69d5e50c625b84aaf988", + "memory": "6b1c5d501dabbbae93220bf709efcfc31585bff1516f8f0f44d3c4e65e3d4ebd", "wram": "bcc7ef9c4b855090a40b1716bab837eebb2b81b54b3e219bad57463ba4ae6495", "audio": { "firstSample": "94026", @@ -2539,7 +2539,7 @@ }, "mask": 4, "frame": "0ed96aa8f9e282b0fdb37d0e43c904c4db48b83de64d95647cac0ed3cc801668", - "memory": "bb0fbc55125ae076f7b1cf6f283703d842803228be28b4e013c1ebdf490ab5df", + "memory": "98eace8be45a7482bd34d70f0b47cfc4a8e5574b64cd70fe2f05215815ee881e", "wram": "bae99940100bcfcec1d6108b9a5d4495f953c6abbf375028776ec0b06e1c0018", "audio": { "firstSample": "94830", @@ -2560,7 +2560,7 @@ }, "mask": 4, "frame": "ce8d99fc9faa68c2cf164ed4ecb8da6296b14cf3c85b34b2567e55bde44802aa", - "memory": "06f9f0d37c08fd0af59eaadabc88fb054f077b724baf692fbb25717094688fbe", + "memory": "de4e8944fafcfdcbcf4062a5bdbea570fc3bac3a5849b09c1b5881388426087e", "wram": "def66f2f3a293b2c0b6eac202448d4f7ee4b1bb89b17428a26e18f2feca9180c", "audio": { "firstSample": "95634", @@ -2581,7 +2581,7 @@ }, "mask": 4, "frame": "4753fc53f7c1eea686729673e2f56105bfe210e3fa47cd6f269c530a4f2e5265", - "memory": "60066202a87c5e543afc4d730eb36b06824ba9886cc0911cd59e5caeb84224f4", + "memory": "b7b27a365b9c65a647d68013f7bc79ee490cc0bc5ac91cdf27c9ce5f5de0bb7e", "wram": "66378d77566d831f0f71472062bee6362359d67221e981586cfb5b2f5958dba6", "audio": { "firstSample": "96437", @@ -2602,7 +2602,7 @@ }, "mask": null, "frame": "4753fc53f7c1eea686729673e2f56105bfe210e3fa47cd6f269c530a4f2e5265", - "memory": "60066202a87c5e543afc4d730eb36b06824ba9886cc0911cd59e5caeb84224f4", + "memory": "b7b27a365b9c65a647d68013f7bc79ee490cc0bc5ac91cdf27c9ce5f5de0bb7e", "wram": "66378d77566d831f0f71472062bee6362359d67221e981586cfb5b2f5958dba6", "audio": null, "state": "25d098571f764336fe0f3a8e63438e749596f53a4065ccc6071868802172bd9d" @@ -2618,7 +2618,7 @@ }, "mask": null, "frame": "4753fc53f7c1eea686729673e2f56105bfe210e3fa47cd6f269c530a4f2e5265", - "memory": "60066202a87c5e543afc4d730eb36b06824ba9886cc0911cd59e5caeb84224f4", + "memory": "b7b27a365b9c65a647d68013f7bc79ee490cc0bc5ac91cdf27c9ce5f5de0bb7e", "wram": "66378d77566d831f0f71472062bee6362359d67221e981586cfb5b2f5958dba6", "audio": null, "state": null @@ -2634,7 +2634,7 @@ }, "mask": 4, "frame": "cb83fd5fd54c4c80cc18d5c2ccb4256a6a0ceda285a98d3871044dc34a735d02", - "memory": "b9e2927f347f7a653c8226c002449eaf1167d9d1ab04ab31fdd50d4d664b7210", + "memory": "bef8a8a62edaf64f1953a862d250726486f768f9f97881a23479b17749399515", "wram": "efee7a7a0f3badf16b7fce7ae11d8999de39b686d6f0ad56986c5696d68b9285", "audio": { "firstSample": "97241", @@ -2655,7 +2655,7 @@ }, "mask": 4, "frame": "9c7f2f6e72b663645ba38d633eab081b71a3e25e8b3ba4750b05f3c3da64a37c", - "memory": "24c94fa2cccea7f91de010d38bf18c50ca1a74347be7867e47fcdcf1c060b924", + "memory": "c73aa5dd06a7423858bcdcca34dab68843be8c0655fd86e8398487d00abbf7d2", "wram": "90c56df68c8c7ce34e761b95ea70ac2d931085cdf7bac66d8c649e581c094d5a", "audio": { "firstSample": "98044", @@ -2676,7 +2676,7 @@ }, "mask": 4, "frame": "a6bd164c63f378de1e421153d18cad8eeeaef9f9037a18c2bfb9813638461b00", - "memory": "b080c5bb1bbad35f911e3bd103b475540b2f7777fc070cc4238df603b0239987", + "memory": "8a5f54b1194f669514f618b3263768066e2dfb39cbc9389a2088231af8efad6d", "wram": "b526aa6e8b5774928791f5ee651c47412be7343691cff1fab0cfcbc6fe2172fe", "audio": { "firstSample": "98848", @@ -2697,7 +2697,7 @@ }, "mask": 4, "frame": "3a4f7fae899e298447aafdd2842706333528140cf3feaa8736cad9b3a53b43bf", - "memory": "4915fef2c12017f5c95e09c3550484ce2ca352e97e6ec10a870850c2eb12f527", + "memory": "72482b14272df75e409d8a1f856558dc2fd456815922d7392873a7f54932ca9e", "wram": "ee25aba1d64aabbc320a783b7c93f23a08806f04c08f53a7591ddab256714281", "audio": { "firstSample": "99651", @@ -2718,7 +2718,7 @@ }, "mask": 4, "frame": "cff49c018fabdabb8bf8865b115318be45c8cd4d2fbaed86c5d9d9840fd2ba3a", - "memory": "780e1ee6126ce6c300aa0e9932a23b81e9d67c989978a90b5beca64fae82ace6", + "memory": "4d72b66a02730d044657296959e03153d79d2208ab6fbb06cfb78863edd08120", "wram": "6cd75b8ef8ebfabd2e93d403e54f8134b6107cea1ab64ce60347d832ac0b7764", "audio": { "firstSample": "100455", @@ -2739,7 +2739,7 @@ }, "mask": 4, "frame": "8b8df5c47f9c25ebd8f6bf0dfe862821aeebc120652aef6b505bcf5b12304d6c", - "memory": "da79d60bc6233781673eabd3cc37f1677ee145cfa400cfa7fa5414de6759efa2", + "memory": "ba7cf3073d974e767ee9548c0dafb419cf674b5ad9856d0f32fb978907044377", "wram": "5ae362e5ae73633924bc0c5886234eb7834070c677f4f827030e5c876adb8d1b", "audio": { "firstSample": "101259", @@ -2760,7 +2760,7 @@ }, "mask": 4, "frame": "d4b48bc9ead761594d5f194f26efb73aa047d400e49e5a02f7ef7cf5bf78e9ec", - "memory": "d99d84c191755f22eec4d869e6adcb7a692f5f0b43a0c12186d10edc87b65caa", + "memory": "ff768a1ec139900aad4d0f25446334e1847ed9e010b1f0d91a1ad1ccf36398a0", "wram": "9a37c09bda87e6e5dcdd19cc31ed951c0978cd103eb7a6270846039228740bcf", "audio": { "firstSample": "102062", @@ -2781,7 +2781,7 @@ }, "mask": 17, "frame": "d1072a80db98b52d16e09b4b56e313edd7ca705f605ff30e6447fc7ff22ab6ca", - "memory": "6acfe50e334267044a88cd6231e6962f302f5af469fe5a061862fac822f6d0cf", + "memory": "cd560595e81211c69246e0e5d3d4112f333eb366f10f161766248dcc3b1dd6ad", "wram": "5f6863ef1fc87d1bbb6fb1f918f230ed9530db669537aa9dcdac078da5710230", "audio": { "firstSample": "102866", @@ -2802,7 +2802,7 @@ }, "mask": 17, "frame": "d22d55daaa8422af5b73ea5f2fcaa3cc78375641005fdd2d807e117ba1fd3c99", - "memory": "cb67b28e16261bbd6d3715ff55e087f32bac22ca3dda393383e5c0d86ce5b867", + "memory": "819072b04101ca8eaeb7b06043401dcd4f3d0a290beca04a26d5a8d1be991fa9", "wram": "d32fe3bc98d5c8c22b70285b03cf723768fe34af0fa7017808ad770187169807", "audio": { "firstSample": "103670", @@ -2823,7 +2823,7 @@ }, "mask": 17, "frame": "52420f37551bea49cbcb7af3733f51c365a0f6a2709cdc4d191a6b7e07b7dfdb", - "memory": "1696e63ce1517f719e74276bbedbd9e2168154bf8caea31630480b45a52306c6", + "memory": "f8016aa21b88be29066516a10ad811cc1f330c7872a9088c80f1647db80af65d", "wram": "04fd47f1b438fc8138f7345d686182ea5a62ccff2a215bc0b55181cbaf98a8c8", "audio": { "firstSample": "104473", @@ -2844,7 +2844,7 @@ }, "mask": 17, "frame": "767a91003b2c8d0258535db504b4416f9fbd9300d195cf9f9266de30a7335da3", - "memory": "c7ac89fb696a6b1225c3179946c2c2512d642bf6df3e258264217f15f7c85201", + "memory": "b7ddafb6160111a31f48580ecdfa888c91a823fbfb2940bad1c637f42a6c8fe6", "wram": "7f770b4708eb1e8eb5a339997baaf316d49d9304e2b2408ac36e2f96c5f576a4", "audio": { "firstSample": "105277", @@ -2865,7 +2865,7 @@ }, "mask": 17, "frame": "1fe46f585daf0da15f0e886aad88c813d5f545593bdc580a10d15301abf11073", - "memory": "3f202ef9017ddbd716ced4e2611ae8ea6192b07daffca8d34fa1d0072b291867", + "memory": "df5d5f2f0e94da51dcd67a351e8307c4e49299111bc882d991a19ade0fafcf0e", "wram": "5c11076edc0cc49fd818de8d9de2b0d144ea587473cedc20217bf4e7ac3c9abc", "audio": { "firstSample": "106081", @@ -2886,7 +2886,7 @@ }, "mask": 17, "frame": "ab863e28a688c4be1bf003ee87a75b5358ff4e9bf3626c7a1efcb7caea81d7b8", - "memory": "cd71feffaabe063bab943798bdfdb9b8505123758abe66d170548c2a8299b91b", + "memory": "351c61184b4a0b2030eff53b714bbc3a6dfe0fe5f51f35cddb1b2383ff884f15", "wram": "3f8a2ad5312e1b1e43e0e33c5ac52a98625e2aac91cdd8d8cc0e20742e551175", "audio": { "firstSample": "106884", @@ -2907,7 +2907,7 @@ }, "mask": 17, "frame": "92bacdddb791da4b6ee8cff9cfb0e2bf33cbede33e809d003cb06f408ed3c457", - "memory": "a23963f85fe0bf2b58495f2b7ace744cffb3025ce6f5b687266b142d432b090e", + "memory": "fcbf381fd1f7fb5083e8dd6a0c79242ebde8b7f0b1fdb9544abaf1a8ab96b5bd", "wram": "abc9000f1470627d75cddddf6209d5cc2f9e41f7378f0c40f8f9a79961ed29ea", "audio": { "firstSample": "107688", @@ -2928,7 +2928,7 @@ }, "mask": 17, "frame": "5d93b95a0338362e1142ad3d43e8650deb1fb5622d4b1ed0a78d508b54f35f6d", - "memory": "1acee75dea546407ad9dd9c88ee15dce201a0abc808084fd7356897bd2122fcb", + "memory": "1d70f0aa1b6e6c6c9ee8616a9635d40145fcdef2ebfb09b523e4bcfb839c13e6", "wram": "fa95563ded3400c9428dd8469b3ebd9deeab38b7a506d15a2873741c66fedf46", "audio": { "firstSample": "108492", @@ -2949,7 +2949,7 @@ }, "mask": 17, "frame": "144301124eaebc8c750a252227dd759f39fe199f58a0ba6c60f0f1e03302303b", - "memory": "b5e9c24b88615f3429ea771e45c745e1fd5083c2331254613d1f569589635660", + "memory": "9cdaa55c8023a273823545a665c2aae1bd6b60588593d98428572260cac90c73", "wram": "0fd6a7aecc16e7da4a903ab34d58394dcf4ba12814d15b1064d407a0cf63cb52", "audio": { "firstSample": "109295", @@ -2970,7 +2970,7 @@ }, "mask": 17, "frame": "ae89e6e64586e6d7b0405aef8ea2d833767955f94b21897b92563c4c1a46370a", - "memory": "d24a09c20ee0932e1381ae027eaaa53c888681ca5c3ff1a02006e4fcfa9d5c94", + "memory": "47b8550f20bb31f734992e85f5834828e5dafed6ffcfd9dd3141f910529f0e70", "wram": "45bbe99dabb8a24d016d29451a418c483f94c6df07036b312789553b5bd6199d", "audio": { "firstSample": "110099", @@ -2991,7 +2991,7 @@ }, "mask": 17, "frame": "b11d93574717d72faaeb3b80e8d1fe5fa70f7737a3227b7921febf159f741000", - "memory": "f1de501158161fc64330bec17573d70de0f4d251b9bb67dfbec2b012b26a739d", + "memory": "88b91cd80c78087435f3fba149efb8ce519539dfa7fd501ef57eda6f6d28f2f6", "wram": "2a330d848a68a8dd84ee4bc6e24eca4ed26d1746b1a8780819cefdf9130efb6e", "audio": { "firstSample": "110902", @@ -3012,7 +3012,7 @@ }, "mask": 17, "frame": "9c8ada350809adeef48a8b10eec0ac9f0af64473318a2eaca88ccd718380e978", - "memory": "1a9698e443d9f4ec612ea71fbf4138da5e0ce2613d18cd793108c2c43916b868", + "memory": "983f389df63ee2f13ee3e8e8b23e5611ecab007d954f4e774de3624d13acb81b", "wram": "d71b6b6035536775860c68e7638f7ecae9f824e4a539d5eece04aa47144443ae", "audio": { "firstSample": "111706", @@ -3033,7 +3033,7 @@ }, "mask": 17, "frame": "235e61ea550863f9d4e6b30ac32e9075dab7db69995642f95e2eb274a5d8f353", - "memory": "dfa2f612b5756afcb6224d4fe8fd07598891be13b3bf7aaa1a1449b58f6f926f", + "memory": "056d7c6aa418d7df4e7ff7615fc03bcff78d49f2a88dc83b173fcec14c6a559f", "wram": "b6d28f9010f8c77f9cab83a8166c2eaf8337ad45138ef8482a46cd545dc716aa", "audio": { "firstSample": "112510", @@ -3054,7 +3054,7 @@ }, "mask": 17, "frame": "512bcf2fbe031cbf38159f98ccdec0b56fda9ede8dbf8fc5459b571bc1c9e7e6", - "memory": "75ba86269f997844ca52096aed5e57b9bc9fd2f91e54d07c4898e2f182656fa8", + "memory": "1a56a5b04c1539139f78e132add526c9b49b8c2d795d7ab8e16a2a3cd369072f", "wram": "248c6690584c7531f05aa9c6c8d3712436b2b2bb377b54471c621183e7a4be8b", "audio": { "firstSample": "113313", @@ -3075,7 +3075,7 @@ }, "mask": 17, "frame": "1852caaabc7c4a244d78885be7d1eb35e87bee7d75991940244b8f15df56ad88", - "memory": "a0babf0722d5ff56e0a7fb6c5f5fc958dbcfb0375bbe19ac4abf13ab8aa41a73", + "memory": "8f82ea028216240adf490768416d7099b838d469a931854c278e02a9f2b72eff", "wram": "7647d57084bec91c9abe4c19470c161e7490d5fee6838d12cb388fac6e566c19", "audio": { "firstSample": "114117", @@ -3096,7 +3096,7 @@ }, "mask": 17, "frame": "c9c70ec1f20817ac74a1155aba06eb180f7fe874cc19a95de7f8bee5b4169fe7", - "memory": "c99d1a1dc1e763559e1f43b01b59e11d53c34b325be58d48daf55d25992f8235", + "memory": "98622128d785112f10af09a630682cf3afc7bd6374ef9462824d9cc9d8309c07", "wram": "399e066c6c0b7fe5c06f597aadbfc153a67d4da218874a6cfdb5e2555b5e4771", "audio": { "firstSample": "114921", @@ -3117,7 +3117,7 @@ }, "mask": 17, "frame": "ce98a8837fbfd123efa1d89679901dc605c8ae58885004a1e00f6c9550cf6c46", - "memory": "fadb92dcd55ed4232021c4f2aa9a092443611b307cd4fc51bc9c03699b0593cb", + "memory": "231e4be21b3c68dbadc227ac7a23a6fcff77597d43d891b9696d7a62d7d8028d", "wram": "662c86fc41aa3294b3ce426b13f2c8d4cda493db3cc57b3915fbf72160f4894f", "audio": { "firstSample": "115724", @@ -3138,7 +3138,7 @@ }, "mask": 17, "frame": "a7086cbef2215382fc0f102e90ad6f993a5ad26ce8064d9483c34287b604bfba", - "memory": "d154bb2f494bd2dcf459a40c24ea19c8e84a3b56f40a06732c6935a0c3405cf1", + "memory": "cf050c959710c3feebfc09944430dc88ae6c869234ef2ae83029104f3991bfa8", "wram": "f1e3274affb20eee09d68b9d661e248e934cea04e6ca83d8e9665f6769eb7b7e", "audio": { "firstSample": "116528", @@ -3159,7 +3159,7 @@ }, "mask": 17, "frame": "3d67728cc436ae35ce5ee0c58c6e3cb44f0d78f97f5631776dee137434870193", - "memory": "aa6acd39fd26fa063a23346a3380e436b7a54ee31066edcc847bd75b95610423", + "memory": "b4fd63b3f171d261814e57630e2a95d9ec4a9a3a4217d095dde779cb29181780", "wram": "164c401651b19cde741b0b693c559721c3d4588416c34ca058544be58f2e869d", "audio": { "firstSample": "117332", @@ -3180,7 +3180,7 @@ }, "mask": 17, "frame": "8c873a220dd0595035c8e2f78c08a078fb0a344972f91f66ac7632880e7435b8", - "memory": "38965ad00affad5f5a22a2117f51eaf65153c38edc66b70e6a782f511ed3080a", + "memory": "50c44b727914319d7cf305432886d0455f3bd448a590a3e2f3a9316404c96b7b", "wram": "24a228956b643b29178d518bbbdb2eeba5fa64ca730e53db1cb77229a6b80f18", "audio": { "firstSample": "118135", @@ -3201,7 +3201,7 @@ }, "mask": 17, "frame": "56be3ce3506612fdcd666c55f0567c54679c53733d0359d4538814ab93766e9e", - "memory": "414650543c0d1f85e99a073d6293c5b621683333150246829d3abb156b960d8c", + "memory": "228832b613569eeaf2fceaf4fd66d1a2f3324c1d66d91cc476e940082d7f88cb", "wram": "d32fc85cfd57d8826877709e392692ec6403f49bee89bcc9229451aabaf17b54", "audio": { "firstSample": "118939", @@ -3222,7 +3222,7 @@ }, "mask": 17, "frame": "5ea5e0f43635435fac0db17de68914e2b20ed665f03b2322679d20e3dd680a01", - "memory": "ca2577b8f7fb3a548f5e514b310f0e57f28fd8375920f40fb9da675716da55aa", + "memory": "dc51dc83c3bb1cffd4019a443de63fd94255e724d488c086ca73caebf320ae69", "wram": "7db42a4799ca665a4517bae2887198f8ab28b7b53a047029b67d0993d163916f", "audio": { "firstSample": "119743", @@ -3243,7 +3243,7 @@ }, "mask": 32, "frame": "4e352ebb684dad61e5a44acc1af45a6db5a457f08847d0e5a9fcfab272f898d1", - "memory": "de44819dbfa41bbbc3306a8b96dba9d9e5783217b0fae24d372636cf7de49cf7", + "memory": "6560b06eda267804944cbc8c79f66bafde47ca4ef9bc890d5721876f98c33b37", "wram": "e768e38afd8f69c68e7b9967bcf16c5a92cc63c5afc349278057d6983c20e369", "audio": { "firstSample": "120546", @@ -3264,7 +3264,7 @@ }, "mask": null, "frame": "64768d7167e34d306ba9083bb1dc7e65e6123b634079787faa19d0ef3798de86", - "memory": "66278bc8057194b81bf22fad68280b50e5035a4d8a0c5233cb8f80d172fac2d9", + "memory": "5df84a2cb48ac24e72a5ea063f24caeca2e929bbdc368306a6adf856dc07f381", "wram": "fd666c21dabe652d5a961e8b85ff4c93367d5519f588d860fbb4ba1ccf549ea4", "audio": null, "state": null @@ -3280,7 +3280,7 @@ }, "mask": 32, "frame": "753c140971ee4e9a32a1520a665ef9b0f9f7e1fa169df19d2f1b056d306aa456", - "memory": "8645ee2aee752ec082f115b3b0c2d8d9dd88817c023a04ffd5d4b067e7c0b790", + "memory": "99913ac75f748592be33444558d3c6de09be550d33a6cc18f7873a96022982bf", "wram": "8ed70c3d6a69e080cf326a85e21af3d33dabb1b48bbfea89ee9e63136e35fa1a", "audio": { "firstSample": "121350", @@ -3301,7 +3301,7 @@ }, "mask": 32, "frame": "22f1be54f37f199dcaeec1060e2e09e3a22fd5164699bc053ea0920ae7ada08c", - "memory": "48a3cd447e083e7c0f56b1d9aaf4cb79d535fc5c2b32c2ded1daa3b8b6f830fa", + "memory": "dde0f4e61c121e197d4ab73c5e88b97d88a5ce70e65121b6685d6ea1b7c0f10a", "wram": "cf90552f0e41f35efe50a321cd34868f55178c0618318ad8b147307700b85947", "audio": { "firstSample": "122153", @@ -3322,7 +3322,7 @@ }, "mask": 32, "frame": "48d2bb3924667d51dab00774d733c87e71f5116ac97a25a3c8f918a1864045a6", - "memory": "d9554b2815015fb713f2f6114c04e9d85f3e9e71e211a939c814fb642b1c1c32", + "memory": "fe821bd102e3c68719afaa3e692dd4bcd25137e38f1f37d43235002436673090", "wram": "310f01c088dba3ad815660043bd9258ef49eec536988870fde71dae14a279ca1", "audio": { "firstSample": "122957", @@ -3343,7 +3343,7 @@ }, "mask": 32, "frame": "656fdd04a80de28316c851dac094ef299232c26ca0e2262b0665cf1aa024ee15", - "memory": "36ef29cc840bd61d42df8e489392af64be85bdcbe32681e669d7523429254867", + "memory": "c9d50ef1267888680c843391f2a65f70920a66aeb7973fd50050fb2e5519e27f", "wram": "80bffa19b111cb702883eec1480718895117c14fb84a8f82cf1981dfc53c3abd", "audio": { "firstSample": "123761", @@ -3364,7 +3364,7 @@ }, "mask": 32, "frame": "e1963ddc2736e66231b0ecc309e1d2becdabb34723181ac9856be2ab24c4c41e", - "memory": "c3a2cced361cef15f59fe3c9d622483911ea4ecd94637394e960395430a1487c", + "memory": "d067395e9f5e81ff806d7fd6b7e70b7cbdd90d752df4e5eb741e35d067260913", "wram": "6e1859a7671e677868a0366b4bd7eb527edb0ecbd9befff509e7cc638bd1ba29", "audio": { "firstSample": "124564", @@ -3385,7 +3385,7 @@ }, "mask": 32, "frame": "858ad41eeb5588db26891ef3d4e9ae896fc05c7dfe0c7115bbf91d886afff4e6", - "memory": "49c6b7be04543ffa3f08b9281ce09f5195ddc515b791c41cd6b97475b80272c4", + "memory": "0bcac811b589f14287de16b489c90654cd10e3668acf35b277ec819f2cc68ca5", "wram": "9a1444f58a03ff2b0d992daade02bef2437323d67f0bd305cd3849835a7b310e", "audio": { "firstSample": "125368", @@ -3406,7 +3406,7 @@ }, "mask": 32, "frame": "3f2b3e1bf955431affb925d5189b1ac826546fba973d4934a6f288b3de55dd1c", - "memory": "08cd222cfcc4cdc854e9be99d1645c07148e92f7e0630e16c3284ce29c13ce1e", + "memory": "eb126d76c6ce673c28e5675ebd0fb932cb248124b06eaaa21754689c2ecd0e6e", "wram": "41c2ec7fa6f02c25ebb7b5e977732161bbd66106621783d7fc77a7d1bf29c5df", "audio": { "firstSample": "126172", @@ -3427,7 +3427,7 @@ }, "mask": 32, "frame": "3b9cf500bdc56a25d6fdcfb9ff23956b2e21a7bf1434fdb84ea3a080176bbeda", - "memory": "04acab946005caf77fd89d258ce2f3c240b3e1509d5e64ecbde8230a883e9b2b", + "memory": "18d4413cf635d3f357cc0b35ecfb93e62b5c83089452fa038a691c6680cbd45e", "wram": "8dc22eb8d28728267804426c31e30e498d4544de7532180afe575a52d940d40d", "audio": { "firstSample": "126975", @@ -3448,7 +3448,7 @@ }, "mask": 32, "frame": "838c3852e2722710c38cc5cd0c2548d6fdf239639c8153543cfe89db85e2fd6d", - "memory": "58df7aaa6badccdea21abae9abe872ab6eaf5dd286e9f17550c930b5bee227a2", + "memory": "e3a243eeded545df442e2eb3adc038a01138a123cec3fe4be146725baa0e914a", "wram": "81045e99cf5b1f048a0a8b03ce5130a874ef0b6abc434f250c6bb15f01075e9e", "audio": { "firstSample": "127779", @@ -3469,7 +3469,7 @@ }, "mask": 32, "frame": "6790e130d466b993be26933ec3557bbbd8ed9c5f3ac839248b43d30943535844", - "memory": "727fcdf8a7ab533f483e9ac824cfe23f905b88cb50dbfbd131f4cac127bb3167", + "memory": "437e46cea00c641a95627fb236005b7dd3bc13b54f566be50f37af33f1ae2027", "wram": "047dfc8fcc0863eb747dc285a68077036f1bf16e3cb46fb2fcd365968aa35f4b", "audio": { "firstSample": "128583", @@ -3490,7 +3490,7 @@ }, "mask": 32, "frame": "c89ca281fc5391c04a1c95b7017be6f7ab9adc8144fe28fc602b414229e2eb89", - "memory": "488c33664a92658149b85ccd329227c61c09203da7b1b385a46953028746d83c", + "memory": "16757275422c7ea7563f576d0d2bd3e13185c5befaeff60ee191fb6bbcd6c2c3", "wram": "1d3bc2c0411dec7ae3307e439f6f354d18251ad74a34c1cbd2f78c84c722dfcf", "audio": { "firstSample": "129386", @@ -3511,7 +3511,7 @@ }, "mask": 32, "frame": "776f611745ae470495c5af28b16885b291f329af636df20705613af8902e6ac5", - "memory": "21054f82a206af8f00dfcf302434e0de9b1041b0e641195fdd86e09f5a3f062a", + "memory": "83f2a128e5760a5558443f167019f67110c60cdb95388a181a665a4eabc8b80b", "wram": "c625e96526a82a12c54f1d8608384b72d9fb077d7e15ebd2292be9f4e7fb9663", "audio": { "firstSample": "130190", @@ -3532,7 +3532,7 @@ }, "mask": 32, "frame": "7ca327d262c35979d4f59df433605ea1d38af54c2520bbdb55b018e59aa1a370", - "memory": "2d0c4a5d72f06cf764dabda932756ecf8d547cbc88420d0eacdcdb232c3b2f29", + "memory": "fc56574365456b7529bf63cd9d2460727e168e3db875664618b34b30504b3c0a", "wram": "ca815a6b85a1ff5ecc12e2c6278a376f7fe4139d6076180aafd2c33eb5d3044d", "audio": { "firstSample": "130994", @@ -3553,7 +3553,7 @@ }, "mask": 0, "frame": "da9f31833723501e8f9b7e49e9ff20f3f29fb868299c56c8665a48f11ddf541b", - "memory": "d729a9c6f96171980e112315a94e057dbe81a2cd35f6f6a99667d124238836ab", + "memory": "956a35f0f626308cdf40d3d3ba410f36b71e725a7d7fb056b7eea0c57c32b9a8", "wram": "6712dc8ac2aefc58789966ebef9da93eb8dad099aa8f944ce15a45d376ff1570", "audio": { "firstSample": "131797", @@ -3574,7 +3574,7 @@ }, "mask": 0, "frame": "dcceb4875a447ac7cc594aa55c3c5d32ecfd7ac0cad4d99978dda00509911c6c", - "memory": "54ac81daf92d314f344de3d1306253a3fd49c8b7c89a114fbddbd46ba3a9e381", + "memory": "1e4b8cfa3be8d375e13d74b052b8d85cf25577db7ecb188a7ac759eb377905d6", "wram": "0f6f1dd14ce27852c4d4e46b250d230ab6aba2a40bd196180d3866e097317d48", "audio": { "firstSample": "132601", @@ -3595,7 +3595,7 @@ }, "mask": 0, "frame": "ac1a88b5ade80700b0bcee43bfd4f6aacdd146af6893fb8f86564cb6716688a7", - "memory": "c8b4e901acfafebe73eac834cbee7bc01e3bd56ab9e8fd511cbd25904bf6aeca", + "memory": "e5ad32d46a6fc46b1e01903a42a4306b750f5a40ee3036c4a37df3e6cef1ff3a", "wram": "9698529419254ffeb37f26fe46de10c7afa41103d839d118c472eb6d6463ec3b", "audio": { "firstSample": "133405", @@ -3616,7 +3616,7 @@ }, "mask": 0, "frame": "b30c33051b4ab4f4d7f29222a290a680b53f752dd05000a72ec738319de33967", - "memory": "8b1aad5aed49f774279f5a3edf34ddcd5f9c14813f69dd26b000ee8d69fd2325", + "memory": "6fadb3c5f5bad99f3113578f62aebbafbd0aca1c1162b9a38a381ced0cb65425", "wram": "87cb8e7bbca4c18337a07277b31c68ae464d0bec5877844cccbef8aa81029c5d", "audio": { "firstSample": "134208", @@ -3637,7 +3637,7 @@ }, "mask": 0, "frame": "04a24628cb2b0daf4fa5a3a72a121e025ee9b99cf5039a45bc399825e5f2f939", - "memory": "59f81c705a47aa3386ebd9c7a18ed7d9cdeb138b9125fd825d7ed782d262ae73", + "memory": "9a17563de2d5088374144578480c3cd462b0a17f56823d793911d221ab3a8ab0", "wram": "ec7bd0f711173e3da9f1c272c6e4115ef642446dfc0968c9b58891fca96a1021", "audio": { "firstSample": "135012", @@ -3658,7 +3658,7 @@ }, "mask": 0, "frame": "5615f00a2f8b8ac91b235854acef4b261c3207da0bbf1af65083ed0c38b511cd", - "memory": "686d4dce8ccb8cfcdc2804abb962f4eecb8494eb33a873da36395f44716e70df", + "memory": "0e7a272b6f9c4827b9d2c2332eb561ef0f0a2e6f25731184302a1deacb4e29b9", "wram": "630859191a19f572b45760cf52cfd45f1677d49828aae359a57b42172abb4032", "audio": { "firstSample": "135815", @@ -3679,7 +3679,7 @@ }, "mask": 0, "frame": "642d0e87ee3004c8f640ef7663de5169f1670ecb11d121b86d299a79622e009a", - "memory": "c0bf574b85a694db0d355ee84f66432391900dd101efba4f6f4ffe704d9e7cfe", + "memory": "fd57cfa692d5b081a12cb7a1cf3d059921f563a56d83fac7b32d1e2230a5144e", "wram": "09662f60776c325917920b68df31ae5f93c4511fb7eb06492dac41e507c82630", "audio": { "firstSample": "136619", @@ -3700,7 +3700,7 @@ }, "mask": 0, "frame": "8d4b7fdc73357fc7195f9492d8b26f6ef6155cb0c136953b9dde66459d318e4f", - "memory": "8d705e14f720b04677ceac8c8814571580fa63590bfd1793367e53ffe1e7dba3", + "memory": "b2b01af52e6d875cdaa43f9438a5beae6a6b733b9616886bbf7ba67fafe600c1", "wram": "7f8cd2cf7dfe0fb6f8d072c604c790132f4c52cfe666da904b7ac400e61accff", "audio": { "firstSample": "137423", @@ -3721,7 +3721,7 @@ }, "mask": 0, "frame": "137dd530a6480a8d62682affd3534dc615852ccdfc84c7cb892c3fa3e042fecb", - "memory": "b2c838f396b360bb5bf5b1bfe062c0d3db974985ceeabb5daac38773e278d29b", + "memory": "01899aafc113ecab1d11e8990ba7f8d530d426493953d66bc1ff6fe2b09a5067", "wram": "5ecfa57889df577d5ba12a0937f58a2e9d33bd8b8c51f7a32dc65d9b22309964", "audio": { "firstSample": "138227", @@ -3742,7 +3742,7 @@ }, "mask": 0, "frame": "2ca3ed99830800a8b597eed9b4b24706f46afcfc26c37fd3320c26d24cbd0a84", - "memory": "9d7698233b4c23d4300689b48b6887522e4587cdf82a4259956ea9977619aab6", + "memory": "c8e9d4ff67374016ec913b88ee82b51f104fe5849f9acb0510d03d1c54dd5840", "wram": "7bc3b1bd9860bda60f8fbad1a3d06b406f057ae9cdbb4fcfbe2fe9ac2f8fc535", "audio": { "firstSample": "139030", @@ -3763,7 +3763,7 @@ }, "mask": 0, "frame": "1c0c3bf36035f19167719a3f9cdf99919c6e0a4c988b865b0d7903ec1dda5bf3", - "memory": "9ff32adc99b128b1af716186d6ebdb539f5ff51d2ecd91c1d3552bfd9fd621f6", + "memory": "4aab8018861ceeffa1ec9601c4886118cf6dce8e39a7eb44536cd20f0014c31d", "wram": "bad793a7731fae5935bcc45ab23f7b507c360723a54d2805d75a2f94ded14a45", "audio": { "firstSample": "139834", @@ -3784,7 +3784,7 @@ }, "mask": 0, "frame": "d3e5d0dc16a361c78a2193305fb8ad61bf302e9eeb031b443b07e68be910b259", - "memory": "0f062a1315d20e7ba55be1cd83651c372e1d70c57e37507726593daf66ef0da9", + "memory": "2c0618c688772debb4a5eef3de6b5214192ea0279373344df341e7d048665866", "wram": "fde24867a82dd20e3c0f276d3c331f2c385418866f7132e11c876fdf263fe381", "audio": { "firstSample": "140638", @@ -3805,7 +3805,7 @@ }, "mask": 0, "frame": "e8fa5ebd8ce0b4bf35fee136518bb7394627f0557e7fc81ff236c60922ad9745", - "memory": "941667e580f69cd0d9699607cb73123cbe094dbcc9f104717f45b6c1f447fdd1", + "memory": "cd0df3df4eeb879cbe217b769bd0f5e625ddcab38e5b345e09d9ab7eb90cba6f", "wram": "a1c0417ea338897f845eb9a069ee5c39f57d80d25684581b61edca01917f2147", "audio": { "firstSample": "141441", @@ -3826,7 +3826,7 @@ }, "mask": 0, "frame": "07ce9fd3dc974d48760f07fa4561bb5440ef969a7e538300c169b457594a0153", - "memory": "5cf65d88375d712f74adff452201ce57801baa3bac4cb4edc44bb6044ba5582e", + "memory": "1a8fabf7867d4b3f2143630bdd2c76b1cc0813aa9b967c4fe1bc62b12095b810", "wram": "0983485f650d1e6c2bc9654dbe475a7ae5d90e5d8608cf37692e20b88fa7433d", "audio": { "firstSample": "142245", @@ -3847,7 +3847,7 @@ }, "mask": 0, "frame": "53a6da17e11a4439ef47ded75f059af8155f07511dc9d369cd93c456221dd4e4", - "memory": "cf707277a3bf1197b4939af1e09632a5d0d0c2eac702f575588a0f32aebc4e30", + "memory": "4ccd8a816fcaa9abc07bc542d94b10aaba72ae56c0035867984980547821e7fb", "wram": "71aa010e693ce96ead3ca7176f8efb11fac9cf7d4ec8e7eac9c744642af0abf3", "audio": { "firstSample": "143048", @@ -3868,7 +3868,7 @@ }, "mask": 8, "frame": "3520cd7e27556968aee9ecee57df8b1a5bbcbed90626d563e0150dfaecc85965", - "memory": "47a7c1c73558024fcd2bccfa387fe7ae4e39df3c88954b23a927dcaa1173a762", + "memory": "3e899894aa240293d4f3a46f29291522753ebf24d6ba69ef0145c697cb60953d", "wram": "98faf9f58a802c3b07a444119f261a9d84c9fe5f7d8b86bb7064dcf997b6c690", "audio": { "firstSample": "143852", @@ -3889,7 +3889,7 @@ }, "mask": 8, "frame": "53a50210db831d20c781fc40e822559e99ac1839423c7214739fe646edaa833e", - "memory": "44db19229a81262032cd3fca559f922029fde50864b9214456e71bca824f92f6", + "memory": "df34dd78a84e87f6e34e032c3de0480872c786b0b6ae174eda4389073ef2ad6d", "wram": "eb8eb48fd3f1c0a93ca5f06d190cd2eae33a46d5df33d927245d55509cedf217", "audio": { "firstSample": "144656", @@ -3910,7 +3910,7 @@ }, "mask": null, "frame": "53a50210db831d20c781fc40e822559e99ac1839423c7214739fe646edaa833e", - "memory": "44db19229a81262032cd3fca559f922029fde50864b9214456e71bca824f92f6", + "memory": "df34dd78a84e87f6e34e032c3de0480872c786b0b6ae174eda4389073ef2ad6d", "wram": "eb8eb48fd3f1c0a93ca5f06d190cd2eae33a46d5df33d927245d55509cedf217", "audio": null, "state": "eceb68ba5c8c6ba1ba4833766a468bdef834dec57d8795aa4d329a53b97cedbc" @@ -3926,7 +3926,7 @@ }, "mask": null, "frame": "53a50210db831d20c781fc40e822559e99ac1839423c7214739fe646edaa833e", - "memory": "44db19229a81262032cd3fca559f922029fde50864b9214456e71bca824f92f6", + "memory": "df34dd78a84e87f6e34e032c3de0480872c786b0b6ae174eda4389073ef2ad6d", "wram": "eb8eb48fd3f1c0a93ca5f06d190cd2eae33a46d5df33d927245d55509cedf217", "audio": null, "state": null @@ -3942,7 +3942,7 @@ }, "mask": 8, "frame": "548df337e7d6185a9c2537b48bd42ef9ede7cb25b3ae8d1c9ad6cbe082ee717f", - "memory": "f8630fbacd8c6311a069f69942dbed095f9710c555c1ec9ac55d7f9f08eb360e", + "memory": "a18803e7f49347897f0a1cba651983d53ba40502fa4b364c8d592e422bdc9ba3", "wram": "a82ebb24578ecce93955f87a0f240f3b41bd1d1b52700b935c95d8d2b6f697bc", "audio": { "firstSample": "145459", @@ -3963,7 +3963,7 @@ }, "mask": 8, "frame": "13058c26459c4909c8dcb7645083d61675a520ae26461d9d183abefdc0a9282d", - "memory": "db51f934e261be89caf50389fb3d4cd01ceeb3bde6f0e7b39d69321a896c85fc", + "memory": "e98db1a1b7f342ae26415a26d738c7cbe37e1a084c1c2c12afc61e1899c79c92", "wram": "8a3cd7bc86943ad99084b1fe420c7c81623a4b051886d8fe38d64d87f517e62d", "audio": { "firstSample": "146263", @@ -3984,7 +3984,7 @@ }, "mask": 8, "frame": "b4a8d96dc16dcfc6ac7cae71e43b96863117177577abf7cb2f72dbc0e81364c7", - "memory": "048aee733aa6ad9b885dc8ff8111cb06630e9e9b3fea74b4b6a7767af16f2cdd", + "memory": "e41355a82cf4b39d0bc33616e4f010f37893b1f97ec817c40c52852bc6207e8d", "wram": "2a916fbdfb4cb5f94299eac4e04a70c1183231df65cb7dfa207b312ff451c66e", "audio": { "firstSample": "147067", @@ -4005,7 +4005,7 @@ }, "mask": 8, "frame": "c40d9409de1693dec77fb788f2ed6b5b5d5e24954e82feab6b69becbe14179cd", - "memory": "200880bc20bf4244e8384ff889bfdb16f9f9d9c70c3828648e563d1be3d3e587", + "memory": "1888ace3c14cb099e550b13a361eec9ccd665f3053e76ce516a2618e31b41e73", "wram": "9af982ef521366e4cb33d5f0a85354963075716ca3228421455ac74ac853c31f", "audio": { "firstSample": "147870", @@ -4026,7 +4026,7 @@ }, "mask": 8, "frame": "70688798b946e301195645495b30f225f73e51301de3e3ced9422ffa901345cb", - "memory": "7c0a729ce7b730628f0d82a82752f6d35baadf9f3e86560ec5c7747c283a6e6e", + "memory": "44c8552edcd1b433686738c9256073dabc5768a30371c06cd3b7b954101244ad", "wram": "49e92231dd03bb89472789b84086421d7e5efa22e51de87e28038103b234db35", "audio": { "firstSample": "148674", @@ -4047,7 +4047,7 @@ }, "mask": 8, "frame": "39801c72df6d19efd63feba9f39675256fc41761e5122e7cef14ab716b7dba22", - "memory": "2c33158bebf61d1e019a11c39c4c0c2234f7b7ad2fdbbbadcb21f99ee64dac00", + "memory": "32b6d3282b21800bf026064885647a9567e57ceb174432b0dbb71f9d8cb7e75b", "wram": "69092e9a8ede10457018edd9386313214db5d4329c2c6de54132fec346a253ca", "audio": { "firstSample": "149477", @@ -4068,7 +4068,7 @@ }, "mask": 8, "frame": "b3fa87634c5a8810a0952c5cc141fa02d21b28344fb7286b24a76b17b70b97c0", - "memory": "72e2a6e5a8dfec5dc45d63744d1d400ddc18abb2475597c5f37f717dfac62e0f", + "memory": "ebd7db66a5c807f4b5a61a29bc949f34c0bc45a39a756869628ef73b3253b571", "wram": "187c1441e67c64c4bfd62ba6bd12491d0fc4bf86d3b8d033fbd64d07de99b08a", "audio": { "firstSample": "150281", @@ -4089,7 +4089,7 @@ }, "mask": 8, "frame": "4259a86dece8fba61c9fdecbd72961ea9c1b0bbee17022e3386324cf4310e486", - "memory": "3e92ebb4a94f9e4998e339807dbf0a509e255e8c7d999e530fb060d495082bd8", + "memory": "c700dd0a9e2ee351a4c42534b74fdd9c172a965cbd88b017a38c8b6de1921db5", "wram": "ba18f7c0c8cda7412e64952bf30c574736efa10c3235fa684d3d3b03c39ab2b2", "audio": { "firstSample": "151085", @@ -4110,7 +4110,7 @@ }, "mask": 8, "frame": "0578f3afea601bb050a32076fb626b0349ccbf10b5a6144abf10ee09105a1ce6", - "memory": "0a18f23693e4dd8df07fbcb4eac8c0a0dfcce26ef8b7809ce8db34abd6cef35c", + "memory": "79d3798cd77e79a363e3364ab1c05929065530569b524acedb5b58e239049721", "wram": "bbeebd23e2004f74a024b609b198cc596e9c8b650e2bd0e6991dfeaad50ae888", "audio": { "firstSample": "151888", @@ -4131,7 +4131,7 @@ }, "mask": 8, "frame": "0e7819724dd54c89f90fd85deaa891fb82d2edd325e0c23018ca73d3095b4435", - "memory": "cd02f2ed251f2fa629495481b598a3f81f49216b6fc5b06f354beb8fa99dff28", + "memory": "2d06eaf1de62ff744a4aa16dc657d6af5c071727c749cd821da32c3ec28bc91d", "wram": "eae713cf0222ca2cfaceeb77f44fb52d7012ad9884b0545d2b97d81761fe7e31", "audio": { "firstSample": "152692", @@ -4152,7 +4152,7 @@ }, "mask": 8, "frame": "156ba76c4775c10937039ec74ab181b32747e56811b8faf4448672f0ac505a6b", - "memory": "c33c7260620895f90b48e555d45624bf587f1c5f04f73efc6587ed13d4d04382", + "memory": "49d44390cb6381ef9c5d1520b522ef378ff9087669047f3a7d221edc503dd4c7", "wram": "1662fd2ee13b06b8dac9c2efaed2fe78ede441815257c13719ddd3a98e17ee55", "audio": { "firstSample": "153496", @@ -4173,7 +4173,7 @@ }, "mask": 8, "frame": "0904f8f1d625c12cf0532f0bc6bd412158660918df7466436397b458587a4f9b", - "memory": "8823f9d32b2352673d833616511db008f92f406a8a4164bd238880f8d3223e58", + "memory": "db1f0603a68a42e08262b79d78fc98657b2614d48a05de502815561b0b9d1058", "wram": "ada336e932af820388833209a489f19508ff1ad8633b5e63080f7bacff11de6b", "audio": { "firstSample": "154299", @@ -4194,7 +4194,7 @@ }, "mask": 8, "frame": "ece1e3d022b097fdea91d62eb879f06e156a2a613c462473e2a1da35dcf1d332", - "memory": "88178ea295bc8ae93aa268fb6f2e77e16cb389dfe28edf4d84739d9da5fd0a35", + "memory": "3a0ba40870d9fa1c4ca7f01f4ec13d9e608212d057040a425e4636b05942f1d4", "wram": "e7a3d8c2a08456067412f40e658ccd42ca53f5b988cfcb2b7855b42d11f60abe", "audio": { "firstSample": "155103", @@ -4215,7 +4215,7 @@ }, "mask": 8, "frame": "12df6484dcb1804ae862f4337129ef5af0a4ca4a8468e4a49dee65f35b123dbf", - "memory": "6c2a891e46aaa8c2fe733d9efb3008ef4dfb50ca16526913bee7db3987375d1b", + "memory": "db8e4b16f60de6cd322d85251ae18879ae592ca0f9ab338d76094ff0216d9fe4", "wram": "650104c4e26c0ce5a5c661f41c49cc76690317fa90fbb7f2f778ab77aaa10b30", "audio": { "firstSample": "155907", @@ -4236,7 +4236,7 @@ }, "mask": 8, "frame": "ee7c3ce7e021086feb4773ff45e8fb9b2feb1b3d5e90333fb0d9981b4ea306f1", - "memory": "807646a17789fc13ed011d175687539ef37c815365cc683c722b187679b9a466", + "memory": "43367e1d96780dddfde72eaa7f2533817885b44446714f8b871207ab4c59062a", "wram": "16affdc887ae6ab3226b048e038746bf378971fbbce90618f8b41c1147eb6b03", "audio": { "firstSample": "156710", @@ -4257,7 +4257,7 @@ }, "mask": 8, "frame": "26f0b75df6674e3df6fd62d29dd4dc55752e3b05fdbbfc5850cab3e28cb96285", - "memory": "e14bcd233397bed95fa2b7d2e6a7d39ccee7418c6de6bfe77ac8ef600291b6c3", + "memory": "2bcfcb1240dc114a1ce06f3a93192ac9dc09454e239540a7ebdb14129b7fc442", "wram": "768b97568ed2c11c2cd36150a874927e427bc55396e84149bde0832dfb88b46e", "audio": { "firstSample": "157514", @@ -4278,7 +4278,7 @@ }, "mask": 8, "frame": "070b78b62de183d7270e8dd5d609cac5baa25cf7990f7fc786b8f4069374fd66", - "memory": "b43ad218e2e9c1cceb207c7453b300330f03e33bfa8b2607fe4a814c74fc22bc", + "memory": "6b134910b534affdc25848e14f47815834797e26c0a78882cf36b34ffcc23ce4", "wram": "1bd9f0184b38eee91b4a980a8eca84958b4373fca904c989a08ddc5049848afb", "audio": { "firstSample": "158318", @@ -4299,7 +4299,7 @@ }, "mask": 1, "frame": "9acd3e040056d43fe1f1ef83417bc5fab487235db5011b1b4dc5e2ddd8ef5738", - "memory": "000560f1252b7b6271ab9f1abbaef0d435ce8fd672270c5e479e4cbeb9023ae4", + "memory": "593c0e0ed2137fe1683726dc9783706e7edc3290176b900e0c12ec49aa1b3116", "wram": "c596d5ba664d46aceaf1dceb162523db94ead09a325480277a6332924b6f89e6", "audio": { "firstSample": "159121", @@ -4320,7 +4320,7 @@ }, "mask": 1, "frame": "8d5950e22b3cc0730f9e06fb61fbed0be0f4189abec6304eaf22511e2be586fa", - "memory": "1d56a4a449da0e5ce1a6fb070ca4269f7b551013a8ef6c60f91abda515cf85a8", + "memory": "4cdcc64176452001359cdb15312dc6376af8abbda99990252919f9b7b2d559f7", "wram": "ad90606b6e2214b92f19b681779a5f4bc0a1980cfe7f13785a82f0e5e646735b", "audio": { "firstSample": "159925", @@ -4341,7 +4341,7 @@ }, "mask": 1, "frame": "91b83e3540d1d45ad18df668cd082ba5cb0b8dec5bdc93be129497ef7b9037a3", - "memory": "428aa464ca87ce9e644b806d6af150aded749c0cac7cde5a3840380c47a767d7", + "memory": "2c9c26db7638d4b8c2bcc1f8f3b3178cbee22c57e97241e63ffea03409ecf4f0", "wram": "baae0d745a85483dd09b35539e3fbe411ec3b71c553ea85991e6c01f0eccf1df", "audio": { "firstSample": "160729", @@ -4362,7 +4362,7 @@ }, "mask": 1, "frame": "074e2a99fe0958f3ed098775329a4da4fef1d0c0d753a3139204899c864e911e", - "memory": "5707051431a9d4cbe3cebcc137cf0e7b51dc119590baf70acfda9baf080c60f9", + "memory": "bc69ee60755d86476f35952b3b5f9b95a43a3b03098a20742871180717166850", "wram": "dbda4bd3ece56b9f40fefa8319bf1ea0e98bc3b82cbef28972550c7808f1e80d", "audio": { "firstSample": "161532", @@ -4383,7 +4383,7 @@ }, "mask": 1, "frame": "6f13c04473521a0fc23c2f373da8eea8e9917198d448d3b51c9febf6ac2ec172", - "memory": "c146cbb3694d9221dffb988f78145034dea01f3511dd2034ef16d50c744f0a41", + "memory": "c8fa1595204597b959a235f984ec56f31a1751796269f12c4d9d396add7d9b0d", "wram": "f0170356ccf561cf2fa6a3f968f685908494577245fcbe7151c1c7721f0d2259", "audio": { "firstSample": "162336", @@ -4404,7 +4404,7 @@ }, "mask": 8, "frame": "57d6df661171ac464e878f0637cf8d9d0505dc4a965cbee3d3d6047442262edb", - "memory": "82d7a1ea3e7eca7d0634e7d11f2979bdbd5e9bb3cdccab9728efa9a22ede85ac", + "memory": "1f3ab45354a5791290f0f2ab0300340e2a64b3f84b90212c65bba4a2baabcb45", "wram": "60a2bd0ffedc0ba67b66707c1b59d97722c2acfad565478b40933542ddf35695", "audio": { "firstSample": "163140", @@ -4425,7 +4425,7 @@ }, "mask": 8, "frame": "6cba02dbf825145cc07806d2dc3ade17e6b088647f99936b9a909560e9cf7647", - "memory": "1845abc6768dfde671a64bbe37fd85ceedf3a6b61fdf6a0b15e1b9ecbdd57c65", + "memory": "98bc367c3f7de356a95d9cefd0557e8ff244092c7320c7c89e85ff972faa4c2c", "wram": "c1fb67f1b975243ead0203e119035aa4e8af9f7011623cd79c87e6a477c3c239", "audio": { "firstSample": "163943", @@ -4446,7 +4446,7 @@ }, "mask": 8, "frame": "2924ff348e30d714820a2ebb9c22048a956a352ef60bbbbf4c7f274844494737", - "memory": "49198c5f47523e4db41aff0fe9233fd4f213f5cd065aa5855f50d3bc9aa8579e", + "memory": "1897def9cc5190fe7e3ba62402277b20eb3fa5694ddfdf4ab38048b61751add6", "wram": "4bd5fb590562145197c0e507bc9afceac842990ed7bbf165ff066f56a3d114f5", "audio": { "firstSample": "164747", @@ -4467,7 +4467,7 @@ }, "mask": 8, "frame": "dcafa4cd7c189c8f04b910f4ee20134c8af34f1bc31981e1eb0d3b398791861a", - "memory": "98dadb7805c696bd98a76c955bf69cd4de840baf84ac2b1d8495b8dd6de0438e", + "memory": "310a7a0ebed04427fe109280abb5bb3dcece6bb89a7b42ba50442cf651357600", "wram": "37120708b99fe73d33afa7c7c502ba395486b8c2ef596a3f8b9548c31596b889", "audio": { "firstSample": "165551", @@ -4488,7 +4488,7 @@ }, "mask": 8, "frame": "5b8dc52d943d4f8aa8923102ae1c13065d605e07d4802b8fa54eb94ecffb5652", - "memory": "ca14135628fd8d8798ebff254855d7a88ea23372b530c8f9f0cf6170894ee0e8", + "memory": "48a08f4f9910877e81efe8f3986b51194295b421dceac83defbfad99f1777d44", "wram": "2e0ed8f605a733ae2e72d938141caf56e81054f2c1a3e823cd93ecb0c4109748", "audio": { "firstSample": "166354", @@ -4509,7 +4509,7 @@ }, "mask": 8, "frame": "9d703c7edd72a2229a2b743b56ec9bbec2cfdd6b12749aabf39ebb8c8f426b65", - "memory": "362ee108ced284d77ce8005403cd93c3036b0c40409e145d32f807242547fc04", + "memory": "95ab525dfae1953924648f5447c485ceafc4b37fe22be549e9e9ca12cca135cb", "wram": "51bbddaaa741b3549d15426326738991e5b3b70eda73c9bfd86270ac9e0c0421", "audio": { "firstSample": "167158", @@ -4530,7 +4530,7 @@ }, "mask": 8, "frame": "bae7a850b57436877d832fce14a91c157b45565494db416b177053a5fc7bb307", - "memory": "0f8a8f809066a011dedc85e1d13df740cee66e362499acf7425ebc5a029c9e5f", + "memory": "a2612f54c5717b9ba309fab61b6cc990d3bc348e5f1ab63bf312c61edb226a0d", "wram": "b3425b7786cd55dfec7e0a1de7bbb9bd6731093adea7fe41471181a31339576a", "audio": { "firstSample": "167962", @@ -4551,7 +4551,7 @@ }, "mask": 8, "frame": "e68dc063f6e0a89b1b17d58c6e0db3d2feafb17128fb0c391a8def1968d367ad", - "memory": "126435b5cb3a43bf7837abdd73beb90e87d7da5181f9f75c251cffa774a993e4", + "memory": "60f94e284cfbcad6c91e063654b8330c33edcc8b412e7c052b8a2f9b7caf417d", "wram": "968cbb1c2395ba97cf0132b738ff64eb8a526d5eccdfa7321255268ffed69e07", "audio": { "firstSample": "168765", @@ -4572,7 +4572,7 @@ }, "mask": 8, "frame": "07d6b8fd7e97c484c25b8fa15e627b2c98efdab11a9a0749808d493d142e93f1", - "memory": "af4ce5509c7c16cf9f230582e876c56f12d140ddeff640335bb73ef4b26f5112", + "memory": "43b24046bef5decdc10b02217f5e1ebbe5ab75b102eb977e85cdf356f3a2a21c", "wram": "1f157737327429e63a3efd39bfb776b31e948791ed92ac73be297d7aa67e0d0b", "audio": { "firstSample": "169569", @@ -4593,7 +4593,7 @@ }, "mask": 8, "frame": "52f14f58fc744bdc0933caa91267ad63a33b70be09df5556a55bbf6488961f22", - "memory": "4ba2cd5499c4f37cf2dd2dd643cd3ee73983ab2187d5cd1e96e554936046fefa", + "memory": "c3b46e07b3f591abae1c84f011daec47a600dfeff5b422daef42a335170da8f5", "wram": "c13b0cd5619e195dc391b475c1e160122b668bb33777664131afc650af2844cd", "audio": { "firstSample": "170373", @@ -4614,7 +4614,7 @@ }, "mask": 8, "frame": "7c3593bf3fbe546145a4a91d40857b0e89bcda6051ebfe6efd17b48c2af685b8", - "memory": "b34f82939bbca32caa73c3c53d140d5751ff278826baa5a51754f74bdae4f375", + "memory": "3719174749289aaea1b6524eca37deb9a2a475d4660b5c361453b8094a6dae9c", "wram": "b8a252b8900d7c2447f8e9d4d3ba6a577237dcd2b013981746a7dd263033957f", "audio": { "firstSample": "171176", @@ -4635,7 +4635,7 @@ }, "mask": 8, "frame": "3417b86f160ff0097576a0ce6979bc618d4e41b7e58f386cd6b491bd946ac48c", - "memory": "40872ece17ecfaefa1d14c8cef3fbf2940e388f03d76f40d840544eb30fb26ed", + "memory": "e582974d8ea5cbad75436716e44f5c440c8a11080c5614315e5a9abd2e4a2223", "wram": "9ce4abdbdb579cd2801e75e03705691e3225f94a19b956afdfa742f0394c3154", "audio": { "firstSample": "171980", @@ -4656,7 +4656,7 @@ }, "mask": 8, "frame": "96bab8734c98ff2fe825c654f99156cd95f852fc1caf342c4aef051a3ec14257", - "memory": "5aa562c2c0045d7ad3e2461563b5a5d39e58857ad9a321188c8efeb78d25612b", + "memory": "31e35b20005979cd127e6b816813538ff9cdd2e15490f2a1eaf724c6d94ee3a7", "wram": "b9c4811fa190e9e3e2ac3ad6d1dd995d6cc63b4a0e6ec39c93d4156620adaf2b", "audio": { "firstSample": "172783", @@ -4677,7 +4677,7 @@ }, "mask": 8, "frame": "2e5be93785f5459d3a67da26b4c97b2a7485c6b3f6e238d15d29c0c97102b68f", - "memory": "dce2f4c6e996282de9e6aa307c3b997a0c80fe9a53fcf2ac001ac2610c1d8816", + "memory": "3b7c6403e7b4d47e6968222a6d6f6af55666fb10a0d9907d8368375b7253b74a", "wram": "364907dee8ac984fe8278064ad7d0fc0a0e3d97705bffbc18bedf24f8c41b91a", "audio": { "firstSample": "173587", @@ -4698,7 +4698,7 @@ }, "mask": 8, "frame": "e8c911372daba1b8377be98ed4c238414627ad8e3387a61f207db85ec38085df", - "memory": "1109cf126c416c51489177ab590d52466a1da9d9b7c9c7d38934378f0ecfc6bc", + "memory": "8ed66752b7947f30ded32b98883608f5ced5a384422c965b54d1df07c2faefaa", "wram": "d13fd05b034e300516600b1afc3dbb97430ea0ed85a953818f2999ebf5f06159", "audio": { "firstSample": "174391", @@ -4719,7 +4719,7 @@ }, "mask": 8, "frame": "4ff2d73ab463610decf56c5ab38cf31f9e190fe5bc0da1fe678f82dde5a2d785", - "memory": "6ae3ce75983b2fec28f7231a3e2b69a5cc364fbd07a8abbfd860ba3d23e9b6a1", + "memory": "74e5accaced6d49a56dc8371e922c6d12e3793ce830d8f24285e18b363760f77", "wram": "b672393631b1a59ec2d3aaedbb563768b70740da8564e47d34ec758ef06a917c", "audio": { "firstSample": "175194", @@ -4740,7 +4740,7 @@ }, "mask": 8, "frame": "abc90ba2d5a5471e6f6f80ce4f93cde6ca3d96dab73c80849bdc75e7651b5a55", - "memory": "8141e28c550aedc5eb3801dde7ff34d3e29661d1fac7c201514bb0a4ca1b4452", + "memory": "c807a5d4e91b45d4302a108d39b2be697190fd0704b753134088d06e05ecde6a", "wram": "108b03e3174aa54b23abaca97509ae0f8db49cf3c2831fd883f900be29d0cf64", "audio": { "firstSample": "175998", @@ -4761,7 +4761,7 @@ }, "mask": 8, "frame": "6cbc4ced50947d45172bf9f2e6e8e312b8a1b13459d3e96e2aff699bc8695d79", - "memory": "cad432c960c77bda92f99896042304d0c5008f832b5fb32794dc930fe58cf722", + "memory": "c1b97c3158010f6170d7d6e087fba6ba03834caa4da3aea6d79ad560fdc82c0f", "wram": "0d2b3b8dbaa5230131cca87ed55c3995f403544d0f4eac6f866ad2891dd75110", "audio": { "firstSample": "176802", @@ -4782,7 +4782,7 @@ }, "mask": 8, "frame": "68eb1f49572f2225bac13f5c2509c6bbf9bbff622322a7d518f4655cde4415d8", - "memory": "ebd4f46249168fdf0327d749b8d3b515b8b97156eebd97a03c60b27fb0cb3b96", + "memory": "61c6a18cb2da5d3ad373bf32afbe8e8eb2ea7b7ac7d18c8f1e5d185b4cb5a036", "wram": "0767b53465401e5f91e86a7c14210a4bbbb821c40a234e767cf4f170f8420456", "audio": { "firstSample": "177605", @@ -4803,7 +4803,7 @@ }, "mask": 8, "frame": "2b825f6a37dbaa90752a2590fe23dec97b779e2b264996c3a096cb3738bf2a00", - "memory": "a63d0082486d0d81145b62baf92096e072c20684bbeb1dde288ba0d599ccb7cc", + "memory": "45e385eb2d13662ad8fa41e6b55548150ac5fb1316795a65395352203a7a57c0", "wram": "b9103097929e71c6211077ba7efde39776c3824ae3ac4e95c135a29b45cb240b", "audio": { "firstSample": "178409", @@ -4824,7 +4824,7 @@ }, "mask": 1, "frame": "44868a9fab3aa5f1d64ea98bdc59bb3a97e4e74d35bd9ecedf2d10c3e9cc24dc", - "memory": "8d782f479f6fbd2e214d666ea24373d15e66714dd9f8e9ef785f4ecf81f03070", + "memory": "eea0fdc4b6a058944977c1c11c57ab809ca97d743690837929aaf44377418303", "wram": "257ae63d75a13ea9c7568ba61d88747d790e122ee4d5656c10adb81ba18979b9", "audio": { "firstSample": "179213", @@ -4845,7 +4845,7 @@ }, "mask": 1, "frame": "4a6b0b8f1651f2b995fb3341775b7c19413d619067a1106e27cd836fe63215a7", - "memory": "84a0b79747c4ea05c11bb3d2ee741541618686851c72068d4b8d410a745a5cbd", + "memory": "7838e9e6994596f21d222d0b6fd932678a0d653f25267ba20b36aab2f06adba7", "wram": "c69a64737dbc7e5f120a21b1ff2753894cfed0caf289212ab05a4bd1b7f31e90", "audio": { "firstSample": "180016", @@ -4866,7 +4866,7 @@ }, "mask": 1, "frame": "1c66ad5994268f84439344a38fb56ce6b0c607c50dccac42b75af23fb6746982", - "memory": "6aab844e5401355cf4c21c6f08a70ef1142063c55d6bdc85bf0f18dcf98402db", + "memory": "c11eef9cfca12cf1758e478484ce8575e71c4f4fd28cedc8315847c44b97ed51", "wram": "2fc8aa8a856e17120c7edd70ad2197baef472b61bd474eb1cbe6b6e3ff921e2a", "audio": { "firstSample": "180820", @@ -4887,7 +4887,7 @@ }, "mask": 1, "frame": "117c3284f558d98cc13268a44246e8056776f273777fc7585b3d3be68148bc08", - "memory": "530eb559a7979893d15fcf43fd6c58ebafa7e2afcc41a07090010d16486a0820", + "memory": "3ce2abd2154d3961bfa762819a94caefdcb30730d23dc565a60ed9651fe3bd81", "wram": "96613217eec68543765ee18bcd3900ac89b2a31ff681efcf1fba24471195c157", "audio": { "firstSample": "181623", @@ -4908,7 +4908,7 @@ }, "mask": 1, "frame": "55d3f0e40df508cb2b276d69e14819f2ee715dfc215dd452caac2f3fd1bab7f3", - "memory": "f2633184f9c2fdddff8f312e58e0c42d0a184873962583a4c2f864b283aabf15", + "memory": "fab7e93ca09fbcc71beb2b9dcc02da0558e4921dd4a8cf045fad8c0078bd5426", "wram": "03b63a57c24174c5f57fe73bc3fadb8319864cdcf775f784347256647a27b225", "audio": { "firstSample": "182427", @@ -4929,7 +4929,7 @@ }, "mask": 1, "frame": "156a5367bd9d102d2e5a7a4d5a0ba713bb306b24db99d281d8285334f9dfb8f9", - "memory": "cfa6b8dd8b2f10a25ee36e6ce59ff98885f3c505a0a821f5cef81533f7740681", + "memory": "56a8b1f90777f739b992039d77ee29afdf34d4c97f30c40a6913e0568ecba039", "wram": "6aa9c4f2fe72c2addb985c04c63530884b689d5e34865a65e4cfbf905e8010ff", "audio": { "firstSample": "183231", @@ -4950,7 +4950,7 @@ }, "mask": 1, "frame": "07cdcf90c8d7df6db86c75969bfc8ac0c4ce677d76d9aad6bf53a601b284dca0", - "memory": "1abfacecc764edfb9b822311f1da469b4c22ab9763f3dd3e7f415082c0c632df", + "memory": "bdff6dc52856af939b14ee246a67cdf8c9170d2e5915220fbdf5a4cc9b815d8e", "wram": "dfbed1886a0382f5b6c7f2ef06662a9666793095bca815c350c7a90213b6f0f9", "audio": { "firstSample": "184034", @@ -4971,7 +4971,7 @@ }, "mask": 1, "frame": "3b72039392ba6f02876cbf434c22db0dcbb2a858695c0e05540a97302132c739", - "memory": "88bfd0bf79911212fa5503adffb965176abda30d5675afade30d3188d74a85a3", + "memory": "c70db510bc307cf4bf018f3bc69e72183428c5a97cb107cdb7d69225f9da0ee4", "wram": "955b0c56c5a562493e37eaf581db116ca4e2b57f88ded65e619b7916a2b7f082", "audio": { "firstSample": "184838", @@ -4992,7 +4992,7 @@ }, "mask": 1, "frame": "ac9d0d530d12fb871d5c5718e035cfc46c528d134a2026235a578bc67b590390", - "memory": "256f5492f278b84d3d698aa797f964f603656111d7866ea40d249658efadba69", + "memory": "4c424ffa8ac949c4b9215499934dd52fdb415637ccc0583cdde378abd2e1ea83", "wram": "0f6cdbdc254134c98da7de674d37f8a7cc361d195a2fc1e661fd6133e41b54bd", "audio": { "firstSample": "185642", @@ -5013,7 +5013,7 @@ }, "mask": 1, "frame": "2ffff14f93c6629ae9e9319e54b65a08c1a3d8ba04d69f2b5153fc2746e6fcc9", - "memory": "8865f65ccd0cc1a89f28b0d50e9f3f3b88b143efa0aa1b46d5a18a87a718c8cf", + "memory": "2996e482cf5f9b3c984b904be55b685d4fc129e5b571c04075cea82701239bdf", "wram": "91078469ab75ffcbcec9cf8dc3e64776d92680355226b123391a222de8009d2f", "audio": { "firstSample": "186445", @@ -5034,7 +5034,7 @@ }, "mask": 1, "frame": "8bc0766900ca93bf0fca0b42ca8b064e1bc4338fdb8bcd869161f75923013452", - "memory": "9a8482272ba07c3b401cb8c00aa967fdae4bdb4dafb1e97b4246e669e209f917", + "memory": "52738f1d5363a06dc91f3e4815d2b29d59ab2b8904290a077718a5ba3430c378", "wram": "985cef65ab9bdf1d5e1f15212a02e997a19dc1b962f792fd5a345f5948ed6b97", "audio": { "firstSample": "187249", @@ -5055,7 +5055,7 @@ }, "mask": 1, "frame": "21a440c21fd380cf0042b654859d49e6d1f5c4a07baad75dce602bde572fb3ec", - "memory": "79bc6fd3c85640255f9554b7a8d69e8495c44e2d9b8aaeaf167ab5afee0c200f", + "memory": "817e6ccc557162a46c2859a08da60eacbdaa44eee9c22867eb604a699ef76507", "wram": "8e6a6ccaf60f5d936365f85c93cddea592498c3a092970594f166e62ebe90b8e", "audio": { "firstSample": "188053", @@ -5076,7 +5076,7 @@ }, "mask": 1, "frame": "2c2f98b57a3e88cceaac5c4a68fd103edc98b51efcd39403e22b86ac8f2c2edf", - "memory": "98438dc2d47e4a744dcfed3c379ea98c0de162fa868c167109ab68af10b90c71", + "memory": "f509524ebe1ed45a938cf7c6ec94f89f9f499c769f5921edf7d6f7f8a6c0b1aa", "wram": "63e0af376d6a1a777bac6fb85340bf9cec1974e5d0efaa8f1ddc4c8353d01845", "audio": { "firstSample": "188856", @@ -5097,7 +5097,7 @@ }, "mask": 1, "frame": "5d9b77421e31cca94f089a76a25d1c2c24ec41eb40138b0ef3eb664976fea216", - "memory": "1e7b26e6a7106c859e3930bca3c3d496aec4e53ab44e527bd3933a11d2c597fa", + "memory": "144a8aeedc8eafb292af7417fd6261f2128c23835aec4796603da76d1b8c2002", "wram": "082f6e49f3a33ae0bcd2ca0d957b7c151b5f19833225f02ce7f72334b322636e", "audio": { "firstSample": "189660", @@ -5118,7 +5118,7 @@ }, "mask": 1, "frame": "3c0ad627bd3b9c21199b03341f4153eaf2309e0a672c703cdfe108afe9415b9e", - "memory": "79d6e06bc9fcd8f9ee2eec1c95de41df329a68c554e02791f13e69f1356589a2", + "memory": "ca6ebffb428e626b2e4f6c4233930b2db3d9a642b9dfc2a3c0e27be2fec2dc94", "wram": "4c504f444d0e4120279d7307f1f1b94235c99f1ba700bd0d67a3d920c64b8cdb", "audio": { "firstSample": "190464", @@ -5139,7 +5139,7 @@ }, "mask": 1, "frame": "f4d236c0185298ae2898aeb56b879a4fa452824fc3e9186ed9bfdc7b38f7d2f7", - "memory": "f82a0a3e90ed2326940fb7cec04e3d740e4c7df1d27f5b977f025b3e75fa848a", + "memory": "1697c388a4308e510ce19f6ec63d65088065496ec96190177b7950e237af9df3", "wram": "1f2d58cf5b760af0010d94520650c3319a2cd201fbb09443dc7dab71e50f50c0", "audio": { "firstSample": "191267", @@ -5160,7 +5160,7 @@ }, "mask": 1, "frame": "3c0ad627bd3b9c21199b03341f4153eaf2309e0a672c703cdfe108afe9415b9e", - "memory": "8517f61e302a0fd6d2a51cefde32fa7781eb547927ca1362c839a6394a2730ff", + "memory": "c6e9a785399e0e9386b01acb3ab3421b381282736f08dcdea313ada4c48b7842", "wram": "d34426d040a0162851e78b564935a8470b647bc1b270e580d0194bec028e1eb9", "audio": { "firstSample": "192071", diff --git a/services/flysim/crates/fly-session/src/legacy_env.rs b/services/flysim/crates/fly-session/src/legacy_env.rs index be49534..a423c70 100644 --- a/services/flysim/crates/fly-session/src/legacy_env.rs +++ b/services/flysim/crates/fly-session/src/legacy_env.rs @@ -82,34 +82,22 @@ pub fn capabilities() -> Vec { // ------------------------------------------------------------------------------------------- // The emulator seams -/// The boundary's memory image: byte `i` is `fly_gb_read_mem(i)` (`legacy-gameboy-v1` section 8), -/// read without leaving a trace in the emulator. +/// The boundary's memory image (`legacy-gameboy-v1` section 8 and its MEM-01 amendment of +/// 2026-09-29): MEM-01's one read-only bulk read, `Emulator::read_memory_image`. /// -/// **The MEM-01 seam.** MEM-01 adds one read-only bulk read to the binjgb shim; when it lands the -/// 65,536 reads below become that one call and nothing else in this worker changes. The interim -/// body is the same function called 65,536 times through the existing `read_uncached`, so the -/// bytes are already the specified ones; the per-frame read cache is neither consulted nor -/// filled. +/// Every memory byte (`flybrain_gb::captured`) is what `fly_gb_read_mem(i)` returns at this +/// boundary; the three register windows -- VRAM, OAM, I/O with the APU and wave RAM -- are not +/// captured and read `$FF` (`flybrain_gb::NOT_CAPTURED`). binjgb answers every captured address +/// straight out of an array, so the read is state-neutral by construction: nothing is saved or +/// imported around it, and `export_state` before and after is byte-identical +/// (`tests/legacy_env.rs`, `the_memory_image_leaves_the_emulator_as_it_found_it`). /// -/// **Why the save and the import.** `emulator_read_mem` is not state-neutral: reading OAM, VRAM, -/// the serial and timer registers, `IF`, `STAT` or `LY` runs binjgb's lazy synchronisation up to -/// the current tick, which changes the bytes `export_state` writes (never, in a 3,199-frame -/// replay, a frame or WRAM). The legacy loop reads none of them between a frame and the ratchet's -/// capture, so a slot saved after an unguarded image read would not be the slot the service -/// saves. The image is therefore read between an `export_state` and an `import_state` of the same -/// bytes, which leaves the emulator exactly as the frame left it (`tests/legacy_env.rs`, -/// `the_memory_image_leaves_the_emulator_as_it_found_it`). +/// (Until the ENV-01 review, 2026-09-29, R1, this body read all 65,536 addresses through +/// `read_uncached` between an `export_state` and an `import_state` of the same bytes, because a +/// read of a register window runs binjgb's lazy catch-up and moves the exported state. MEM-01's +/// rule removes the cause: a register window is never read.) pub fn memory_image(emulator: &mut Emulator) -> Result, String> { - let saved = emulator - .export_state() - .map_err(|e| format!("saving before the image: {e}"))?; - let image = (0..=u16::MAX) - .map(|address| emulator.read_uncached(address)) - .collect(); - emulator - .import_state(&saved) - .map_err(|e| format!("restoring after the image: {e}"))?; - Ok(image) + Ok(emulator.read_memory_image().as_bytes().to_vec()) } /// binjgb's unsigned 8-bit interleaved stereo as the declared `f32le-interleaved`, with binjgb's diff --git a/services/flysim/crates/fly-session/tests/legacy_env.rs b/services/flysim/crates/fly-session/tests/legacy_env.rs index 938c485..d1c9267 100644 --- a/services/flysim/crates/fly-session/tests/legacy_env.rs +++ b/services/flysim/crates/fly-session/tests/legacy_env.rs @@ -506,25 +506,21 @@ fn the_memory_image_leaves_the_emulator_as_it_found_it() { let before = read.export_state().unwrap(); let image = legacy_env::memory_image(&mut read).unwrap(); assert_eq!(image.len(), 65_536); - assert_eq!( - read.export_state().unwrap(), - before, - "the guarded read is neutral" - ); + // MEM-01's bulk read is neutral by construction: no guard around it. + assert_eq!(read.export_state().unwrap(), before, "the bulk read is neutral"); for (address, byte) in image.iter().enumerate() { - assert_eq!( - *byte, - unread.read_uncached(address as u16), - "byte {address:04x} is fly_gb_read_mem's" - ); + let address = address as u16; + if flybrain_gb::captured(address) { + assert_eq!(*byte, unread.read_uncached(address), "byte {address:04x} is fly_gb_read_mem's"); + } else { + assert_eq!(*byte, flybrain_gb::NOT_CAPTURED, "register byte {address:04x} is not captured"); + } } + // Why the register windows are not captured: reading them through `emulator_read_mem` runs + // binjgb's lazy catch-up, which moves the exported state. let mut fresh = boot(); let _: Vec = (0..=u16::MAX).map(|a| fresh.read_uncached(a)).collect(); - assert_ne!( - fresh.export_state().unwrap(), - before, - "an unguarded read is not neutral" - ); + assert_ne!(fresh.export_state().unwrap(), before, "a register read is not neutral"); let mut unread = boot(); for e in [&mut read, &mut unread] { e.set_buttons(32); From f0981825a0a2df14535f87562c48ba1c2616a2ca Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 17:17:56 +0000 Subject: [PATCH 25/26] FLYSIM01 carries the reinforcement count; the import takes its ids from the file; StageRestore refuses conflicts before building a network AGENT-01 review: learning.updates fell back to plasticity.updates on every FLYSIM01 round trip. Both runtimes now count reinforcement calls the same way (one per commit while the rule is enabled) and write the count as the optional manifest member reinforcements, which old readers ignore and old files lack (a reader then starts from plasticity.updates, once). The import's checkpoint id is the file's generation (flysim01-g), and the agent worker checks for a staged or activated restore before it builds the replacement network. --- .../crates/fly-session/src/legacy_agent.rs | 57 ++++++++----- .../fly-session/src/legacy_checkpoint.rs | 81 +++++++++++++++++-- .../crates/fly-session/src/legacy_parity.rs | 24 +++++- .../flysim/crates/flysim-store/src/store.rs | 20 +++++ services/flysim/crates/flysim/src/frame.rs | 13 +++ services/flysim/crates/flysim/src/reset.rs | 1 + services/flysim/crates/flysim/src/simloop.rs | 1 + .../crates/flysim/tests/compat_migration.rs | 1 + .../flysim/crates/flysim/tests/state_02.rs | 8 +- .../crates/flysim/tests/state_02_store.rs | 25 +++++- services/flysim/crates/flysim/tests/store.rs | 1 + 11 files changed, 193 insertions(+), 39 deletions(-) diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index 876fc8c..3367247 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -312,6 +312,19 @@ pub fn encode_payload( encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string()) } +/// The reinforcement calls a `FLYAGT01` capture payload records (`learning.updates`). +pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result { + let parts = decode_envelope(bytes, PAYLOAD_MAGIC) + .map_err(|e| format!("not a {PAYLOAD_MAGIC} envelope: {e}"))?; + let session = parts.manifest.get("session").ok_or("the agent payload has no session member")?; + let session: Value = serde_json::from_str(&session.stringify()).map_err(|e| e.to_string())?; + session + .get("reinforcements") + .and_then(Value::as_str) + .and_then(|text| text.parse().ok()) + .ok_or_else(|| "the agent payload has no reinforcement count".to_owned()) +} + /// The agent state a `FLYAGT01` capture payload carries, with the accumulator's remainder in it. /// The `session` member is not validated here; `State.StageRestore` does that. pub fn decode_payload_state(bytes: &[u8]) -> Result { @@ -1536,6 +1549,29 @@ impl LegacyAgentWorker { if !state.warmed_up { return Err(incompatible("the staged agent state was never warmed up")); } + // The conflicts first: a worker already holding a staged restore, or a token already + // activated, is refused before a replacement network is built for nothing. + if let Some(staged) = &self.staged { + return Err(DomainError::before( + ErrorCode::Conflict, + format!( + "this worker already holds the staged restore {} for checkpoint {}", + staged.token, staged.checkpoint_id + ), + )); + } + let token = crate::agent::restore_token( + ¶ms.checkpoint_id, + &scope, + &actual, + &self.config.incarnation_id, + ); + if self.activated.contains(&token) { + return Err(DomainError::before( + ErrorCode::Conflict, + "this exact restore was already activated on this worker", + )); + } // A replacement fly: the dataset is loaded and checked here, not trusted. let dataset = self.dataset()?; let (mut agent, graph) = self.build_agent(dataset.clone(), seed)?; @@ -1560,27 +1596,6 @@ impl LegacyAgentWorker { } agent.network.set_visual_frame(frame, width, height); } - if let Some(staged) = &self.staged { - return Err(DomainError::before( - ErrorCode::Conflict, - format!( - "this worker already holds the staged restore {} for checkpoint {}", - staged.token, staged.checkpoint_id - ), - )); - } - let token = crate::agent::restore_token( - ¶ms.checkpoint_id, - &scope, - &actual, - &self.config.incarnation_id, - ); - if self.activated.contains(&token) { - return Err(DomainError::before( - ErrorCode::Conflict, - "this exact restore was already activated on this worker", - )); - } self.staged = Some(StagedAgent { token: token.clone(), checkpoint_id: params.checkpoint_id.clone(), diff --git a/services/flysim/crates/fly-session/src/legacy_checkpoint.rs b/services/flysim/crates/fly-session/src/legacy_checkpoint.rs index 8ff27ad..7e0210a 100644 --- a/services/flysim/crates/fly-session/src/legacy_checkpoint.rs +++ b/services/flysim/crates/fly-session/src/legacy_checkpoint.rs @@ -112,6 +112,9 @@ pub struct HostHalf { #[derive(Clone, Debug)] pub struct Halves { pub agent: AgentState, + /// The agent's reinforcement calls (`learning.updates`): the file's `reinforcements`, or + /// [`legacy_reinforcements`] for a file from before the counter. + pub reinforcements: u64, pub world: WorldState, pub task: TaskHalf, pub host: HostHalf, @@ -132,6 +135,7 @@ pub fn world_state(world_payload: &[u8]) -> Result { /// The `FLYSIM01` runtime fields of one boundary, exactly as `Sim::snapshot_state` fills them. pub fn runtime_state( + reinforcements: u64, world: &WorldState, slot_id: &Id, task: &TaskHalf, @@ -158,6 +162,7 @@ pub fn runtime_state( last_event_id: host.last_event_id, reward: task.reward.clone(), ratchet: task.ratchet, + reinforcements: Some(reinforcements), emulator, framebuffer, ratchet_game, @@ -169,12 +174,14 @@ pub fn runtime_state( /// and the host's. pub fn export_states( agent: &AgentState, + reinforcements: u64, world: &WorldState, slot_id: &Id, task: &TaskHalf, host: &HostHalf, ) -> Result, String> { - store::encode(agent, &runtime_state(world, slot_id, task, host)).map_err(|e| format!("{e:#}")) + store::encode(agent, &runtime_state(reinforcements, world, slot_id, task, host)) + .map_err(|e| format!("{e:#}")) } /// The `FLYSIM01` envelope of one boundary, from the two participants' capture payloads. @@ -186,8 +193,9 @@ pub fn export( host: &HostHalf, ) -> Result, String> { let agent = agent_state(agent_payload)?; + let reinforcements = legacy_agent::decode_payload_reinforcements(agent_payload)?; let world = world_state(world_payload)?; - export_states(&agent, &world, slot_id, task, host) + export_states(&agent, reinforcements, &world, slot_id, task, host) } // ------------------------------------------------------------------------------------------- @@ -213,6 +221,9 @@ pub fn halves( } .into_state(episode_id, slot_id, audio_sample_rate)?; Ok(Halves { + reinforcements: runtime + .reinforcements + .unwrap_or_else(|| legacy_reinforcements(&checkpoint.agent)), agent: checkpoint.agent.clone(), world, task: TaskHalf { @@ -288,6 +299,7 @@ pub struct AgentImport { /// outcome and not to its own bytes (`legacy-gameboy-v1` section 16 amendment of 2026-09-29). pub fn agent_payload( state: &AgentState, + reinforcements: u64, frame_on_screen: &[u8], import: &AgentImport, checkpoint_id: &Id, @@ -304,7 +316,7 @@ pub fn agent_payload( committed_step: source_scope.step, profile: &import.profile, seed: import.seed, - reinforcements: legacy_reinforcements(state), + reinforcements, macro_channels: &import.macro_channels, }, &accumulator, @@ -329,6 +341,12 @@ pub fn world_payload( }) } +/// The checkpoint id of the payloads imported from a `FLYSIM01` file: its generation, so two +/// imports of one file name the same checkpoint and imports of two files never do. +pub fn import_checkpoint_id(generation: u64) -> Id { + id(&format!("flysim01-g{generation}")) +} + /// The scope a payload made from a `FLYSIM01` file records as its source: the session, the /// [`LEGACY_SOURCE_EPOCH`] and the world's boundary. pub fn legacy_source_scope(session_id: &Id, boundary: u64) -> Scope { @@ -852,7 +870,7 @@ mod tests { fn the_export_is_the_legacy_encoder_on_the_same_values_and_splits_back_into_its_halves() { let agent = agent(9_000.0, 0.75, 3.0); let world = world_at(12_344, true); - let bytes = export_states(&agent, &world, &id("best"), &task(), &host(4)).unwrap(); + let bytes = export_states(&agent, 55, &world, &id("best"), &task(), &host(4)).unwrap(); // Field for field what `Sim::snapshot_state` builds, through the one encoder. let legacy = store::encode( &agent, @@ -868,6 +886,7 @@ mod tests { last_event_id: 77, reward: task().reward, ratchet: task().ratchet, + reinforcements: Some(55), emulator: vec![7; 64], framebuffer: vec![9; FRAMEBUFFER_LEN], ratchet_game: vec![1, 2, 3], @@ -878,11 +897,12 @@ mod tests { assert_eq!(bytes, legacy); let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); assert_eq!(back.agent, agent); + assert_eq!(back.reinforcements, 55); assert_eq!(back.world, world); assert_eq!(back.task, task()); assert_eq!(back.host, host(4)); // And no slot is an empty ratchet snapshot, both ways. - let bytes = export_states(&agent, &world_at(5, false), &id("best"), &task(), &host(1)).unwrap(); + let bytes = export_states(&agent, 3, &world_at(5, false), &id("best"), &task(), &host(1)).unwrap(); let back = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); assert!(back.world.slots.is_empty()); } @@ -899,13 +919,13 @@ mod tests { }; let scope = legacy_source_scope(&id("s1"), world.boundary); let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); - let agent_bytes = agent_payload(&agent, &world.framebuffer, &import, &id("c1"), &scope, &context).unwrap(); + let agent_bytes = agent_payload(&agent, 70, &world.framebuffer, &import, &id("c1"), &scope, &context).unwrap(); let world_bytes = world_payload(&world, &id("world"), &id("c1"), &scope, &"cd".repeat(32)); assert_eq!(agent_state(&agent_bytes).unwrap(), agent); assert_eq!(world_state(&world_bytes).unwrap(), world); assert_eq!( export(&agent_bytes, &world_bytes, &id("best"), &task(), &host(9)).unwrap(), - export_states(&agent, &world, &id("best"), &task(), &host(9)).unwrap() + export_states(&agent, 70, &world, &id("best"), &task(), &host(9)).unwrap() ); assert!(export(&world_bytes, &agent_bytes, &id("best"), &task(), &host(9)).is_err()); } @@ -935,6 +955,7 @@ mod tests { gameboy::ReadoutContext { boot: true, bound: vec![], location: None }.to_typed(); let bytes = agent_payload( &state, + legacy_reinforcements(&state), &[0; FRAMEBUFFER_LEN], &import, &id("c1"), @@ -958,6 +979,50 @@ mod tests { assert_eq!(session["accumulator"]["warmupOffset"], "2500"); } + #[test] + fn the_reinforcement_count_survives_every_round_trip_and_starts_at_the_lower_bound_once() { + // A file from before the counter: the import starts at plasticity.updates. + let agent = agent(9_000.0, 0.75, 40.0); + let world = world_at(10, true); + let mut runtime = runtime_state(0, &world, &id("best"), &task(), &host(1)); + runtime.reinforcements = None; + let old = store::encode(&agent, &runtime).unwrap(); + let halves = split(&old, &id("ep1"), &id("best"), 48_000).unwrap(); + assert_eq!(halves.reinforcements, 40); + // The session runs on and counts 900 more calls than the gains moved; the export carries + // them, and every later import, legacy or session, starts where the last one stopped. + let bytes = export_states(&agent, 940, &world, &id("best"), &task(), &host(2)).unwrap(); + let again = split(&bytes, &id("ep1"), &id("best"), 48_000).unwrap(); + assert_eq!(again.reinforcements, 940); + let import = AgentImport { + agent_id: id("fly"), + profile: gameboy::profile_asset_ref(), + seed: 22_222, + macro_channels: Vec::new(), + }; + let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); + let payload = agent_payload( + &again.agent, + again.reinforcements, + &again.world.framebuffer, + &import, + &import_checkpoint_id(again.host.generation), + &legacy_source_scope(&id("s1"), again.world.boundary), + &context, + ) + .unwrap(); + assert_eq!(crate::legacy_agent::decode_payload_reinforcements(&payload).unwrap(), 940); + let world_bytes = world_payload( + &again.world, + &id("world"), + &import_checkpoint_id(again.host.generation), + &legacy_source_scope(&id("s1"), again.world.boundary), + &"cd".repeat(32), + ); + assert_eq!(export(&payload, &world_bytes, &id("best"), &again.task, &again.host).unwrap(), bytes); + assert_eq!(import_checkpoint_id(2), id("flysim01-g2")); + } + #[test] fn the_task_ledger_carries_exactly_the_reward_and_the_ratchet() { let ledger = task().to_ledger(true); @@ -984,7 +1049,7 @@ mod tests { let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); LegacyCapture { boundary, - agent_payload: agent_payload(&agent, &world.framebuffer, &import, &id("c"), &scope, &context) + agent_payload: agent_payload(&agent, 3, &world.framebuffer, &import, &id("c"), &scope, &context) .unwrap(), world_payload: world_payload(&world, &id("world"), &id("c"), &scope, &"cd".repeat(32)), task: task(), diff --git a/services/flysim/crates/fly-session/src/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs index 07af25f..24d5f41 100644 --- a/services/flysim/crates/fly-session/src/legacy_parity.rs +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -1462,6 +1462,20 @@ impl AgentDriver { agent_id: &Id, initial_frame: usize, state: &flybrain_core::agent::AgentState, + ) -> Result { + self.seed_with_reinforcements(rig, agent_id, initial_frame, state, legacy_reinforcements(state)) + .await + } + + /// [`AgentDriver::seed_from_legacy_state`] with the reinforcement count a `FLYSIM01` file + /// records (`legacy_checkpoint::Halves::reinforcements`). + pub async fn seed_with_reinforcements( + &mut self, + rig: &mut LegacyRig, + agent_id: &Id, + initial_frame: usize, + state: &flybrain_core::agent::AgentState, + reinforcements: u64, ) -> Result { self.initialize(initial_frame).await?; let template = self.capture().await?; @@ -1478,6 +1492,7 @@ impl AgentDriver { }; let bytes = crate::legacy_checkpoint::agent_payload( state, + reinforcements, &self.frames[initial_frame], &import, &template.result.checkpoint_id, @@ -1544,6 +1559,7 @@ pub async fn run_on_worker_from( script: &LegacyScript, start: Option<&flybrain_core::agent::AgentState>, ) -> Result, String> { + let start = start.map(|state| (state, legacy_reinforcements(state))); run_script(rig, agent_id, script, start, false) .await .map(|(records, _)| records) @@ -1555,7 +1571,7 @@ pub async fn run_on_worker_from_then_capture( rig: &mut LegacyRig, agent_id: &Id, script: &LegacyScript, - start: Option<&flybrain_core::agent::AgentState>, + start: Option<(&flybrain_core::agent::AgentState, u64)>, ) -> Result<(Vec, Vec), String> { let (records, captured) = run_script(rig, agent_id, script, start, true).await?; Ok((records, captured.expect("a capture was asked for"))) @@ -1565,15 +1581,15 @@ async fn run_script( rig: &mut LegacyRig, agent_id: &Id, script: &LegacyScript, - start: Option<&flybrain_core::agent::AgentState>, + start: Option<(&flybrain_core::agent::AgentState, u64)>, capture_at_end: bool, ) -> Result<(Vec, Option>), String> { let mut driver = rig.driver(agent_id, script); let first = match start { None => driver.initialize(script.initial_frame).await?, - Some(state) => { + Some((state, reinforcements)) => { driver - .seed_from_legacy_state(rig, agent_id, script.initial_frame, state) + .seed_with_reinforcements(rig, agent_id, script.initial_frame, state, reinforcements) .await? } }; diff --git a/services/flysim/crates/flysim-store/src/store.rs b/services/flysim/crates/flysim-store/src/store.rs index 586e6c0..2e4e562 100644 --- a/services/flysim/crates/flysim-store/src/store.rs +++ b/services/flysim/crates/flysim-store/src/store.rs @@ -290,6 +290,11 @@ pub struct RuntimeState { /// The adapter's own lifetime reward state. pub reward: serde_json::Value, pub ratchet: flybrain_gb::RatchetState, + /// Reinforcement calls the fly has had: one per committed frame while the rule is enabled, + /// zero sums included (the session runtime's `learning.updates`). An optional manifest member + /// since STATE-02 (2026-09-29): a file without it predates the counter, and a reader starts + /// from its `plasticity.updates`, a lower bound. Readers that do not know it ignore it. + pub reinforcements: Option, pub emulator: Vec, pub framebuffer: Vec, /// The ratchet's best safe snapshot, if it has one. @@ -322,6 +327,9 @@ pub fn encode( manifest.set("lastEventId", (runtime.last_event_id as f64).into()); manifest.set("reward", to_json_value(&runtime.reward)?); manifest.set("ratchet", to_json_value(&serde_json::to_value(runtime.ratchet)?)?); + if let Some(reinforcements) = runtime.reinforcements { + manifest.set("reinforcements", (reinforcements as f64).into()); + } let mut chunks = parts.chunks; chunks.push((EMULATOR_CHUNK.to_string(), runtime.emulator.clone())); @@ -389,6 +397,7 @@ pub fn decode(bytes: &[u8]) -> Result { last_event_id: number("lastEventId").unwrap_or(0.0) as u64, reward, ratchet, + reinforcements: number("reinforcements").ok().map(|n| n as u64), emulator: chunk(EMULATOR_CHUNK)?, framebuffer: chunk(FRAMEBUFFER_CHUNK)?, ratchet_game: chunk(RATCHET_GAME_CHUNK)?, @@ -456,6 +465,7 @@ mod tests { last_event_id: 77, reward: serde_json::json!({ "version": 3, "total": 1.25 }), ratchet: flybrain_gb::RatchetState { best: 3, ..Default::default() }, + reinforcements: Some(1_234), emulator: vec![7; 64], framebuffer: vec![9; 32], ratchet_game: vec![1, 2, 3], @@ -524,6 +534,16 @@ mod tests { assert_eq!(encode(&back.agent, &back.runtime).unwrap(), bytes); } + #[test] + fn a_file_without_the_reinforcement_count_still_reads_and_writes_as_before() { + let runtime = RuntimeState { reinforcements: None, ..runtime(4) }; + let bytes = encode(&agent_state(), &runtime).unwrap(); + assert!(!String::from_utf8_lossy(&bytes[..4096.min(bytes.len())]).contains("reinforcements")); + let back = decode(&bytes).unwrap(); + assert_eq!(back.runtime.reinforcements, None); + assert_eq!(encode(&back.agent, &back.runtime).unwrap(), bytes); + } + #[test] fn a_corrupted_or_truncated_envelope_is_rejected() { let bytes = encode(&agent_state(), &runtime(1)).unwrap(); diff --git a/services/flysim/crates/flysim/src/frame.rs b/services/flysim/crates/flysim/src/frame.rs index 8b023c8..d916a56 100644 --- a/services/flysim/crates/flysim/src/frame.rs +++ b/services/flysim/crates/flysim/src/frame.rs @@ -198,6 +198,11 @@ pub struct LegacyFrame { pub location: Option<(u32, u32, u32)>, pub held_channel: Option, pub blocked_since_ms: f64, + /// Reinforcement calls since the fly's fresh start: one per commit while the rule is + /// enabled, zero sums included; checkpointed (`reinforcements`, STATE-02). It is the session + /// agent's `learning.updates`, counted the same way, so a checkpoint carries it across both + /// runtimes. Counting changes nothing the fly does. + pub reinforcements: u64, trace: Option, } @@ -219,6 +224,7 @@ impl LegacyFrame { location: None, held_channel: None, blocked_since_ms: 0.0, + reinforcements: 0, trace: None, } } @@ -248,6 +254,7 @@ impl LegacyFrame { .map_err(|error| anyhow!("running the first frame: {error}"))?; self.frame_buffer.copy_from_slice(emulator.framebuffer()); self.frame_counter = 1; + self.reinforcements = 0; let audio = emulator.take_audio_u8(); agent .warmup(Some(&self.frame_buffer)) @@ -305,6 +312,11 @@ impl LegacyFrame { .map_err(|error| anyhow!("{error}"))?; self.remainder = checkpoint.agent.remainder; + // A file from before the counter starts it at the recorded `plasticity.updates`, a lower + // bound (legacy-gameboy-v1 section 13 amendment of 2026-09-29). + self.reinforcements = runtime + .reinforcements + .unwrap_or(checkpoint.agent.network.plasticity.updates as u64); self.frame_counter = runtime.emulator_frame; self.buttons = runtime.buttons; self.frame_buffer.copy_from_slice(&runtime.framebuffer); @@ -576,6 +588,7 @@ impl LegacyFrame { } if agent.network.plasticity.enabled { agent.network.plasticity.reinforce(total, ms); + self.reinforcements += 1; } } diff --git a/services/flysim/crates/flysim/src/reset.rs b/services/flysim/crates/flysim/src/reset.rs index 3256270..c142541 100644 --- a/services/flysim/crates/flysim/src/reset.rs +++ b/services/flysim/crates/flysim/src/reset.rs @@ -326,6 +326,7 @@ mod tests { }, }; let runtime = store::RuntimeState { + reinforcements: None, generation, wall_ms: 1_700_000_000_000, rom_sha256: "ab".repeat(32), diff --git a/services/flysim/crates/flysim/src/simloop.rs b/services/flysim/crates/flysim/src/simloop.rs index 7604081..f83d831 100644 --- a/services/flysim/crates/flysim/src/simloop.rs +++ b/services/flysim/crates/flysim/src/simloop.rs @@ -1396,6 +1396,7 @@ impl Sim { last_event_id: self.log.next_id().saturating_sub(1), reward: self.adapter.export_state(), ratchet: self.ratchet.state, + reinforcements: Some(self.frame.reinforcements), emulator: self .emulator .export_state() diff --git a/services/flysim/crates/flysim/tests/compat_migration.rs b/services/flysim/crates/flysim/tests/compat_migration.rs index 2234d56..cf70694 100644 --- a/services/flysim/crates/flysim/tests/compat_migration.rs +++ b/services/flysim/crates/flysim/tests/compat_migration.rs @@ -113,6 +113,7 @@ fn v6_checkpoint() -> Vec { }, }; let runtime = RuntimeState { + reinforcements: None, generation: 41, wall_ms: 1_790_000_000_000, rom_sha256: flybrain_gb::pokemon_red::SUPPORTED_ROM.to_string(), diff --git a/services/flysim/crates/flysim/tests/state_02.rs b/services/flysim/crates/flysim/tests/state_02.rs index a23b39a..984009f 100644 --- a/services/flysim/crates/flysim/tests/state_02.rs +++ b/services/flysim/crates/flysim/tests/state_02.rs @@ -127,6 +127,7 @@ fn first_difference(left: &[u8], right: &[u8]) -> String { ("lastEventId", a.runtime.last_event_id == b.runtime.last_event_id), ("reward", a.runtime.reward == b.runtime.reward), ("ratchet", a.runtime.ratchet == b.runtime.ratchet), + ("reinforcements", a.runtime.reinforcements == b.runtime.reinforcements), ("emulator", a.runtime.emulator == b.runtime.emulator), ("framebuffer", a.runtime.framebuffer == b.runtime.framebuffer), ("ratchetGame", a.runtime.ratchet_game == b.runtime.ratchet_game), @@ -290,6 +291,7 @@ async fn every_real_checkpoint_round_trips_legacy_session_legacy() { let restored_context = ReadoutContext { boot: false, bound: vec![], location: None }; let agent_bytes = lc::agent_payload( &halves.agent, + halves.reinforcements, &halves.world.framebuffer, &import, &id("c1"), @@ -328,6 +330,7 @@ async fn every_real_checkpoint_round_trips_legacy_session_legacy() { let legacy = store::encode( &checkpoint.agent, &RuntimeState { + reinforcements: Some(halves.reinforcements), emulator: emulator.export_state().expect("the emulator exports"), reward: legacy_task.reward, ratchet: legacy_task.ratchet, @@ -453,6 +456,7 @@ impl LegacyWorld { last_event_id: host.last_event_id, reward: self.adapter.export_state(), ratchet: self.ratchet.state, + reinforcements: Some(self.frame.reinforcements), emulator: self.emulator.export_state().expect("the emulator exports"), framebuffer: self.frame.frame_buffer.clone(), ratchet_game: self.ratchet.game().map(<[u8]>::to_vec).unwrap_or_default(), @@ -650,7 +654,7 @@ async fn restore_then_continue( &mut agents, &id("fly"), &script, - Some(&halves.agent), + Some((&halves.agent, halves.reinforcements)), ) .await .expect("the agent runs"); @@ -693,7 +697,7 @@ async fn restore_then_continue( &mut agents, &id("fly"), &one_step, - Some(&again.agent), + Some((&again.agent, again.reinforcements)), ) .await .expect("the agent imports the export"); diff --git a/services/flysim/crates/flysim/tests/state_02_store.rs b/services/flysim/crates/flysim/tests/state_02_store.rs index 89b10e5..df8541f 100644 --- a/services/flysim/crates/flysim/tests/state_02_store.rs +++ b/services/flysim/crates/flysim/tests/state_02_store.rs @@ -105,7 +105,7 @@ fn capture(k: u64, ratchet: RatchetState) -> LegacyCapture { let context = gameboy::ReadoutContext { boot: false, bound: vec![], location: None }.to_typed(); LegacyCapture { boundary: k, - agent_payload: lc::agent_payload(&agent(9_000.0 + k as f64), &world(k).framebuffer, &import, &id("c"), &scope, &context) + agent_payload: lc::agent_payload(&agent(9_000.0 + k as f64), 17 + k, &world(k).framebuffer, &import, &id("c"), &scope, &context) .unwrap(), world_payload: lc::world_payload(&world(k), &id("world"), &id("c"), &scope, &"cd".repeat(32)), task: TaskHalf { reward: serde_json::Value::Null, ratchet }, @@ -306,6 +306,7 @@ fn a_store_the_legacy_loop_wrote_and_the_tools_reset_is_restored_by_the_session_ last_event_id: k, reward: serde_json::Value::Null, ratchet, + reinforcements: None, emulator: vec![(k % 251) as u8; 256], framebuffer: vec![9; FRAMEBUFFER_LEN], ratchet_game: vec![1; 32], @@ -328,7 +329,23 @@ fn a_store_the_legacy_loop_wrote_and_the_tools_reset_is_restored_by_the_session_ assert_eq!(restored.installed.task.ratchet.attempts, 0); // And what the session runtime would save from it is the legacy bytes again. let halves = &restored.installed; - let again = lc::export_states(&halves.agent, &halves.world, &id("best"), &halves.task, &halves.host) - .unwrap(); - assert_eq!(again, std::fs::read(&restored.candidate.path).unwrap()); + // And the session runtime would save it as the legacy loop's own restore would: the same + // bytes plus the reinforcement count the legacy loop now also writes (from the lower bound). + assert_eq!(halves.reinforcements, 17); + let again = lc::export_states( + &halves.agent, + halves.reinforcements, + &halves.world, + &id("best"), + &halves.task, + &halves.host, + ) + .unwrap(); + let file = store::load(&restored.candidate.path).unwrap(); + let expected = store::encode( + &file.agent, + &RuntimeState { reinforcements: Some(17), ..file.runtime }, + ) + .unwrap(); + assert_eq!(again, expected); } diff --git a/services/flysim/crates/flysim/tests/store.rs b/services/flysim/crates/flysim/tests/store.rs index 983a1e9..536c336 100644 --- a/services/flysim/crates/flysim/tests/store.rs +++ b/services/flysim/crates/flysim/tests/store.rs @@ -67,6 +67,7 @@ fn agent_state() -> flybrain_core::agent::AgentState { fn checkpoint(generation: u64, frame: u64, rom: &str, compatibility: &str) -> Vec { let runtime = RuntimeState { + reinforcements: None, generation, wall_ms: 1_757_000_000_000 + generation, rom_sha256: rom.to_string(), From 0d41cc2003030171b5fd3fe026b523447c735189 Mon Sep 17 00:00:00 2001 From: acamilo Date: Tue, 29 Sep 2026 17:18:10 +0000 Subject: [PATCH 26/26] docs: STATE-02, the reinforcement count in FLYSIM01 and the import's ids --- .../session-framework/implementation.md | 27 ++++++++++++++----- .../session-framework/legacy-gameboy-v1.md | 10 +++++-- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index ce8904c..146e5e7 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -378,14 +378,25 @@ string changes. the shipped form of AGENT-01's `seed_from_legacy_state` prototype. It builds the `FLYAGT01` payload a replacement agent stages, using the same encoder the worker's own capture uses (`legacy_agent::encode_payload`). The accumulator is `{remainder, executedTicks = network.ms, - warmupOffset = 2500}`, and `learning.updates` starts at `plasticity.updates` - (`legacy_reinforcements`, section 13 amendment). The payload also carries the file's + warmupOffset = 2500}`. `learning.updates` is the file's `reinforcements`. A file from before + that member starts at `plasticity.updates` once (`legacy_reinforcements`, section 13 + amendment). The checkpoint id is the file's generation (`flysim01-g`). No template worker + is involved. This fixes the four points the AGENT-01 review raised against the prototype: + template dependence, borrowed ids, no compatibility gate (the gate is `restore_from_store`'s, + below), and the count falling back on every round trip. The payload also carries the file's `framebuffer` as an `inputFrame` chunk, which `State.StageRestore` installs as the next input. `LegacyFrame::restore` re-projects the framebuffer and does not keep the saved visual drive, and the two differ on the row 65 yard survey checkpoint (found here; see the section 13 amendment). `world_payload` is ENV-01's `FLYENV01` from the same world. The source scope of both is `(session, "legacy", emulatorFrame - 1)`. `legacy_parity` now seeds its workers through this import. +- **`reinforcements`, an optional `FLYSIM01` manifest member.** `LegacyFrame` now counts + reinforcement calls the way the agent worker does: one per commit while the rule is enabled, + zero sums included. `Sim` writes the count, and `LegacyFrame::restore` reads it (falling back + to `plasticity.updates`), so the count survives every round trip in either runtime. Readers + that predate it ignore it. The member changes no behaviour and not the compatibility string, + but it does change legacy checkpoint bytes: a file written from now on is the old layout plus + this member. - **Store policy.** `LegacyCheckpointer` follows `Sim` at each call site: - one generation counter over both stores, starting above the highest either has allocated; - a hot copy every `hot_seconds`, and a durable one every `checkpoint_seconds`, which also @@ -401,6 +412,8 @@ string changes. on *any* refusal, including a participant's `State.StageRestore`. It reports `Fresh` when no candidate exists, and `Refused` when every candidate failed. In that case the runtime must exit as `Sim::restore_or_warm_up` does. +- **The agent worker** now refuses a conflicting stage (a restore already staged, or a token + already activated) before it builds a replacement network (AGENT-01 review). - **Sugar journal** (the FND-01 review note, before SHADOW-01). A per-process boot header records the runtime, start frame, brain ms, restore origin, generation and compatibility. The journal rotates at 4 MiB and keeps three files; every rotated-in file starts with a @@ -430,10 +443,12 @@ coordinator (TASK-01); this slice ships the pieces and proves them on the worker into the real environment worker and captured again. The agent goes through the imported `FLYAGT01` payload and the task through the Pokémon adapter and the ratchet. Every export is byte-identical to the legacy loop's own restore outcome of the same file, checkpointed at once. - Six exports are byte-identical to the file itself. The other twelve differ in named fields - only. Eleven were written by adapters v5 or v6, and the adapter's import migrates their - `reward` state. One, a survey checkpoint, also has a joypad byte in the emulator state that - its own `buttons` field does not match; both runtimes apply `buttons` on restore. + Against the files themselves, every export differs only in named fields. All 18 gain + `reinforcements`, because the files predate it. Twelve written by adapters v5 or v6 also + differ in `reward`, which the adapter's import migrates. One survey checkpoint also differs in + a joypad byte of its emulator state that its own `buttons` field does not match; both runtimes + apply `buttons` on restore. Before the counter was added, six of the 18 were byte-identical to + the file. - *Restore then continue, toy connectome, raw mode* (every ROM run). The legacy frame writes a checkpoint. The session runtime selects it from a store whose hot copy is torn. The legacy loop and the session runtime then each run 600 frames from it. World: 1,800 values identical diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 6cd6313..dac77af 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -544,7 +544,7 @@ current `flysim` reads, under the unchanged compatibility string. The deploy gat checkpoint may be written beside it, but it is not what a restore selects until RETIRE-01 says so. -**Amendment, 2026-09-29 (STATE-02).** Five readings of this section, fixed by building it +**Amendment, 2026-09-29 (STATE-02).** Six readings of this section, fixed by building it ([implementation guide](implementation.md) STATE-02): - *"A FLYSIM01 envelope that the current `flysim` reads" means the same bytes.* The session @@ -554,7 +554,8 @@ says so. owners of the fields are: the agent (the seven agent chunks, the remainder), the environment (`emulator`, `framebuffer`, `emulatorFrame`, `buttons`, `romHash`, and slot `best` as `ratchetGame` and `ratchetFrame`), the task (`reward`, `ratchet`) and the host (`generation`, - `wallMs`, `compatibility`, `speed`, `rankSinceMs`, `lastEventId`). + `wallMs`, `compatibility`, `speed`, `rankSinceMs`, `lastEventId`); the agent's reinforcement + count, `reinforcements`, is new (below). - *The milestone archive is per process, as in the legacy loop.* A rank climb is archived when the rank is above every rank *this process* has archived. After a restart, the first climb rewrites `milestone-` even if an older process had archived that rank. That is the @@ -573,6 +574,11 @@ says so. the agent payload (chunk `inputFrame`), and `State.StageRestore` installs it after the import, as `LegacyFrame::restore` does. A worker's own capture carries no such chunk and restores exactly. +- *`learning.updates` is carried in `FLYSIM01`.* This corrects section 13's *Learning telemetry* + amendment, which started every import at `plasticity.updates` and so dropped the count on + every round trip. Both runtimes count reinforcement calls the same way and write the count + as the optional manifest member `reinforcements`. A file without it (every file from before + 2026-09-29) starts at `plasticity.updates` once. - *The sugar journal is the shadow run's input record.* It gets a per-process boot header, is rotated at 4 MiB with three kept files, and `fly-reset-to-milestone` clears it (`flysim-store::journal`). It is not a checkpoint and nothing restores from it.