diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index a11fa4c..ffbd75a 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -176,6 +176,35 @@ 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`. + +**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. @@ -213,6 +242,64 @@ 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).~~ + *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 + `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. @@ -220,6 +307,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. @@ -233,6 +357,136 @@ 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}`. `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 + 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. +- **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 + `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. + 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 + 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 163934e..d08f539 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`. @@ -168,7 +169,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 +188,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 @@ -214,6 +248,22 @@ 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`. + +*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 @@ -351,6 +401,79 @@ 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. + *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 + 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 @@ -428,6 +551,45 @@ 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).** 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 + 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 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 + 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. +- *`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. + ## 17. PROF-02b: MaleCNS bundles (later) Dataset manifests, original-ID mapping, anatomical roles, sensory and readout bindings, strict 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/Cargo.lock b/services/flysim/Cargo.lock index 25f88d6..3c6e925 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -439,8 +439,12 @@ dependencies = [ name = "fly-session" version = "0.1.1" dependencies = [ + "flate2", "fly-session-types", + "flybrain-core", + "flybrain-gb", "flybus", + "flysim-store", "serde_json", "tempfile", "tokio", @@ -500,10 +504,12 @@ dependencies = [ "anyhow", "axum", "clap", + "fly-session", "fly-session-types", "flybrain-core", "flybrain-gb", "flybus", + "flysim-store", "futures-util", "jsonschema", "serde", @@ -519,6 +525,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/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()); +} diff --git a/services/flysim/crates/fly-session/Cargo.toml b/services/flysim/crates/fly-session/Cargo.toml index 25d9a76..1af661b 100644 --- a/services/flysim/crates/fly-session/Cargo.toml +++ b/services/flysim/crates/fly-session/Cargo.toml @@ -23,6 +23,17 @@ 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. +# 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. +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 219af28..639ae58 100644 --- a/services/flysim/crates/fly-session/README.md +++ b/services/flysim/crates/fly-session/README.md @@ -47,6 +47,9 @@ 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` | +| `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 @@ -88,6 +91,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/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..6e20ddf --- /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": "b0a9731b864ef62903d94fd5ff2b39d476e1538cef1d462d1dde38f4f0289686", + "wram": "0ba149ce666205c7c800d970694d8c1bfd3c6d501f77e89044c547206a322067", + "audio": null, + "state": null + }, + { + "index": 1, + "op": "advance", + "boundary": "1", + "engineFrame": "2", + "worldTime": { + "numerator": "8572265625", + "denominator": "512" + }, + "mask": 8, + "frame": "ae8b59e34dfc614749c6a047ced955771319208885814b2d2e4d0dc7ea892984", + "memory": "9a9e12c0b052ca3817470bc339cb4627f73cba265f6db376da84f6655cac9bc1", + "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": "0bd47bbb81bab5b493789f392da880b1516aff2d96394dd683a2fc416d34d9e1", + "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": "b7a9889c1fed0b1050adf7a358d95fe65d97a60d846211db544059d7ede225e4", + "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": "07f40beccf02e0de3507d0d7a628295eb5cbe949e3b0dcca51c0c166da19a08d", + "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": "93a4db8ce38b7de5c4f0fcb812591c8a02b3fd9e56a89642a03f610de6c03ea5", + "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": "149854e34a32ffa79aca26a318ace928722f1643bba429620bdce0f98fb818a5", + "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": "30a5b5341a9cb53066b4a0f2a1aea655a6c7ad57180d91fa4a263b8d0a3dcacd", + "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": "b674764e8259bc02ed5163a4a2832c1b8749e6b4467d913f9d457dcfae55dc92", + "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": "f053c4f7fd59303a498b767564eca9b383a0666c08a2605ee25ef5e4bb620e6c", + "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": "b5ac45fdcb167cabe0219e0f27f09ac54032a8b97294eea6f8331b204f154e8c", + "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": "eb776ee7e74b4b304b93b1a55a225a88f739eb7a9277a3224737846c65e3105c", + "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": "eaafed21fdd048ecd61aeac9add7fa52804e24c71a85d174e25dd094e388faaa", + "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": "af9b78dd579925bf3b3eb750323b6686b2ed385a0fc7d81d6d52ff375007bbc4", + "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": "b711dc80b235d4f249ef106f5cd7802cbca28b66df378d16194eb7427143da55", + "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": "93adba83b3d8bd820aa03d48122b31f5e7972a46c85e591b12c953949688bbf9", + "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": "fafcd989f272cbd7267ab195854abede9849159b84e69dfbb34ec29fc416f680", + "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": "1e549dda59037fb72430a0919c0fa7d03af958290b442c0c6b56e15b6730a710", + "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": "10219f267f71fda09f2f22e3bebf885e5e78b816d5bd17e9d22689134462a770", + "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": "fa46c2157b28ea940b5e4760673ba6371386d3179240c5ce83646c02a906298d", + "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": "ce983beba7f13b489a59e398e1e401c161840a1804fac2d469d67b7400f05295", + "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": "0306270efb9e580c507b783f39327a67895b292dac60e481142551df8e32c88e", + "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": "158a086ec48250b07baf5331b2cbfe527c1e9079e1a7b1d17eef18dfee656965", + "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": "6c2d2790c0117d72572ef41ee691a085e57a196f038ba4b2ca07c59137ffe12c", + "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": "f72182171e32fe4fa4c994ca9fe08af46db77e117f67d7314b36f63c9e938b2b", + "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": "353ee19a2eb64204e7cb9d109fc692ad88da1fb2972a0773d2281589290b5029", + "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": "033043ab5455398cb5f0ea3bced4a3ba409ef97bd2280c8a55966736627fc696", + "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": "a375ce4b4f7a4f3a0855bb99d032d18ed7d3de8aa0ffafd0cfa7438cf5feac48", + "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": "15f3c7654d99740badd1fa53a187a868db1b29e6de3eb0522f2ed542348c5f9d", + "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": "a5c1356fea320ff56637108f5d8a481489d03078e1a8d9be0989ea01c56a7dcc", + "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": "ec870ea08344fc9adb4b0522e0906701b55b00305f8261a0bf387120b41e7202", + "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": "5df84a2cb48ac24e72a5ea063f24caeca2e929bbdc368306a6adf856dc07f381", + "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": "5df84a2cb48ac24e72a5ea063f24caeca2e929bbdc368306a6adf856dc07f381", + "wram": "fd666c21dabe652d5a961e8b85ff4c93367d5519f588d860fbb4ba1ccf549ea4", + "audio": null, + "state": "a92187ebda5a7ea77d82a40566678177b8e29208b61de01e2fb6e0fb569c690e" + }, + { + "index": 33, + "op": "advance", + "boundary": "32", + "engineFrame": "33", + "worldTime": { + "numerator": "8572265625", + "denominator": "16" + }, + "mask": 1, + "frame": "a050ca382016f826839cbe4c25040e24c8c225a254da33b943c7c92f6e4fc037", + "memory": "97028f96be04ea022ce16d48ba4dc64e4cac3a9a3cbd3ae19a90fad7f92ff4e3", + "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": "dd327e9082a24a5e89aff3d1dc2b9add47521e89602a093fa6f1d989138149df", + "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": "b0e753fe027d0bbf711b071bb954d6b46153b01772f9fc4005f048261edcff5a", + "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": "941492dc804fecb7934b1ff5428ea105a5bec4fb7e029483b55a3fcde83579e8", + "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": "645597cf42aeacd81199de7403daeecd0b485bc25497122df782d8cc16c2caea", + "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": "56f851d1f82f151451d838845aed1ceea92dc1cd533592bada0b5a9c08da7ff2", + "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": "a61fd1c8a22f629fbfbe2731cf300ef794077c021e9cdb02412a78ab578b4850", + "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": "20fbf7c81d6e45e4233a3f444053507ff4f3e5b131822a5bad74dd938aee57f1", + "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": "75af082f5b27235260369d8b8cb0bb447b4576042c350ed43fc3d57798c89547", + "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": "1bc85d39240d2535f8c9986e7365dfa77e469deb22e81accdce87c227e3cc498", + "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": "9ee9601706eeb26396c5181539a607ff80bbbac78c89e4ab63e86135b2635711", + "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": "723b77fe10b2fa3d660f5b11edf682d22d28e3926f7c9ee31962dc387dc1d90c", + "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": "8121cfb25deaaa2b5f52ce7c367b344a548ce0f409ccae533689f8f7256503ac", + "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": "34900c7b8e673057f80ad2129aacf6ac1096295f0d226489ba11bf443d6e7659", + "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": "bb9465f5f3afa6eb40612585efae4b247cb7ad24763a1f647be7ac428bcdcc30", + "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": "a46dd10f60ba550bd726185bc3480a590ef6502b14697f811844e3f2cf84d7f8", + "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": "477f008624dc3267441139f5dc137cd753cac8c6821066a15dcd31cb64d518b1", + "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": "470dfd8175c846fa6e3adf68c277bb0eea9f671241544b2dc60f24bc2550752f", + "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": "4f5712e8617498cad630e9872aa7d97aa3588d32d8256dd19d7f158cd1a77211", + "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": "914c02db5181aadffedc7adf34258ae49118c8ecb1479cfabbbafa7e7964a25f", + "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": "5063e6176a7ce3ce6e9dcd595e32d1dc36c984abfaa441c0e5b55c739ee89f97", + "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": "e0b89149c66487aec516d56098240444254b9cda80c15126de03b6df9cb30f62", + "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": "788334a803d9c7d2e0aa5ae653ced8c39694805721ad12f5cc1a61c0e61d984d", + "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": "9a8fd94eef73eab427cf2ca0eabb20dc60bb32747b708360d739f159ca3d0604", + "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": "74fe3bb37a458e9c7227b4276dda2d7eb5976677fc0452785d2c44a84e46f050", + "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": "d6d45b23d05cc429eca0963f07ec321352352644e5b0b34f495d113d76d2ea24", + "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": "1608ecf40fefd125f07afa2c80872b0e6c214165e7cb68fe70ecdaaf6676ac97", + "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": "f5bda201499ef79e7f882e987fe69633ff7718b33dc752de5b1ab2c4deb20fb7", + "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": "c4a35e9282c6117da57993d978e833205fe899ff9b6e73c2d902c5676a5478a4", + "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": "6e757543fb47c8794f51bc80d87f46fe4c471f5fc7e80687300c33b90e6a284d", + "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": "e62ba70f20c055c3f6372a11c9024d8ae49ef27a21b53a0a4e411a9e68610999", + "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": "6fbc45db1bdeb540bf19be9f2e8c31398b6480880183572b4aa90cde3646c163", + "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": "e3a2bcb7844adc70d67f3a03e52c514b050811e835a5cdd17b7cc09fc6016c26", + "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": "3d994f4a3408f4ce53a8e3d820d3a3f0f97ad354fda6c42887ea5e150d7618ea", + "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": "b477e731620c0b66e0eae19449aba284472a00613f51b4606e0a02b3a932956f", + "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": "03436fa95f904c860ca4b2ca0384966cd5d4d50dad9093c33e9b7b1f44378eb5", + "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": "ed77bfe41c4494c5e176ae50082eebcc2d642b3f8581947e18263f9def2ca181", + "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": "39ef6939ac716e21578e6082d885e3067c21da7d9de3e2f521d8add065ea7a9b", + "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": "16b928cc470b11376eed155f5fe37c75f3885e4ba8c2d72b734ef9121dac1d70", + "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": "2a9500f1ab72744852f1fb515f6d203a02d7a9fa04ada524ec5fcb8108cbc23b", + "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": "efb91d59754b84aebc5293e997b1b794ba3ee5cd1da52575192fc2603ea72288", + "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": "ba59f5843d11b38a17985023abd0896762e0af9872492f693db003d839ceee16", + "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": "9ab17a2d3a311a59e0af7747e7a6eca3c977da85f76a956f7d3d1a8d4feee50e", + "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": "fa945e44826ff38244df712ab7b8c3a4ce442d942f8fdc051c7febd9a851611f", + "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": "99e2afbf271916bcf877eca2d1f2f06750a61bcb3bbc3987fe35f419669e60d9", + "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": "365c9ae122d75f90e36a609ca7349ffe3216247c3218e7d1dd14cf1e076bc6a7", + "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": "de15152610404213f0a79dc8eb913d3b8d2a047ae86c9f5637fc9f56bc44a938", + "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": "24959dbfc1d242cce7b0d8e16232b80b873cb066dac645c3eb9a51190d50f27f", + "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": "415a008e623637889ecdd0911fecd8011c05d95043145c1ca31f0199b7b3ae19", + "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": "5429fbea77dfa1eebee1388685f477e6e8dafa9edb17cee565afa070c34dbacd", + "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": "d69a60d163b1e54d53540c00905a87146e71827a7b975f191acf9821ffc8c8a9", + "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": "7361aaea414d38b0ec806119d6866d0c012feb994d33fa851bdc56fc220feead", + "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": "3fdd1cfb572e1a0f267c2a49f76d7e96d3ba7b6ab4363ab3b2625cc2765f9e70", + "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": "1e8bef004656ccc9b1cd6ca10edfee5c15909562b4ad592ca773c1ca0f849039", + "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": "8571e36159896ed6e1250a73af0c5d03323ad28d6c1d8105491db323a9bc1260", + "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": "1a8fe4a588b2ab36dfa3724aa524f8cdcda18035cadee3b3f019aed11433752b", + "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": "e9c9df36958cd0dba6abb7553db372cb56686aeb6748c6ffabd7234506378d4e", + "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": "90c85465fd606d80c5e18101aacb851257be7ff3dbdf8a3b58e95535b27c1e93", + "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": "4d3f070c39780805dd58109c3bd59eeae71474b11bccbf435bb0b34274f2e8b5", + "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": "7a13b38cbbc0bfc434b3350ce02541bb3abe87679296842d220de25105c98fb1", + "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": "5df84a2cb48ac24e72a5ea063f24caeca2e929bbdc368306a6adf856dc07f381", + "wram": "fd666c21dabe652d5a961e8b85ff4c93367d5519f588d860fbb4ba1ccf549ea4", + "audio": null, + "state": null + }, + { + "index": 94, + "op": "advance", + "boundary": "92", + "engineFrame": "93", + "worldTime": { + "numerator": "197162109375", + "denominator": "128" + }, + "mask": 1, + "frame": "a050ca382016f826839cbe4c25040e24c8c225a254da33b943c7c92f6e4fc037", + "memory": "97028f96be04ea022ce16d48ba4dc64e4cac3a9a3cbd3ae19a90fad7f92ff4e3", + "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": "dd327e9082a24a5e89aff3d1dc2b9add47521e89602a093fa6f1d989138149df", + "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": "b0e753fe027d0bbf711b071bb954d6b46153b01772f9fc4005f048261edcff5a", + "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": "ae39993a273d2e153c15cd0357c4d8d2f02a8d183741c44bdd6ce5224ea4596c", + "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": "cc02c49782995cca6e105514b64619b2a1ba91470b0c0cb786fbda818a95b628", + "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": "44c0e3b78ecab86c566edddf303f47e807e3b373a42745f0f4dea7049ebe9033", + "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": "300c633c3e9e94b5b34419abdd3377ee11cda1c6baf2381fd784354b734df11d", + "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": "ea57cc63510ce7e81f4aa483fda950bc306f16d11d4d86974bc06c59f299e001", + "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": "d9dea79f1f96450d59ee3e53c6ee31337f4ace4aa9a7fd264ff2f0a410c12cd6", + "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": "bfa8cf645d5e56515e0c3660d397df9df72a6ba8577cb7ab0bd5151415c9f9c1", + "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": "0ac70893163dc9809ded8c1c783a5eaa7f41b5e29c72094802a00c21a7cbb6b6", + "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": "9233c8cab1653a22f76db7a96cf03aed9bfa8f6cf5df8040123ebc4c78360fd0", + "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": "c0a1cb5275ba4869fbfb9dd4a3a3d46d81c4c238555ee213d1b3cad491ea6876", + "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": "1fe06d861cee472c161c10b3f5da80457fbfbd64c920f29bf1e9f8b0203dd573", + "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": "8012778fe6bd3cdcbdeb788e91a78892dcbdf7bf87cca3a327adf3d37701d644", + "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": "5cc1624d609a68acdaeab83a937b9de07a490eb5497f39aae14fda562a27be2b", + "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": "4c95201ffb5685d837869e490e5ea3c2af031e6a033121993ebd0901f607fe36", + "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": "dc430c35c47cd73f195664459d8fe3b3e0bb7f789993e4beb96b96051a4acff7", + "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": "eef01a4277c135a7a511337f618f79a8d68005ab6569246ba7b843932dd40741", + "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": "8046124d52adb2c68683c47333de7ebfcc748d03ad4f3770844fea0d8aadc9e9", + "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": "6432bced3526f1f41ba767ae374ba1c7b41669ed98c13ae1088cfc941c31dfe0", + "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": "b51e6f7c6b1561db44bc6d49ab6866e131120cad909b8895a9b6876c62915492", + "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": "0b222b25cdfdd5fe4b77a53f3d68160da6a7b1506a99236eff91d9dec040a55d", + "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": "b9ad39c34ee06efdeb2c067663cff2b107ff48b0332b5b5ca9a8f573ec5305cf", + "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": "f657b7b8bb2e1e8536aa011ff3686092620bae43cab0a9aff74cde8f6e749dd8", + "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": "846260c7acfd710c9cd213b73ddd204445673917d27ed3db4525e68f965731ed", + "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": "6b1c5d501dabbbae93220bf709efcfc31585bff1516f8f0f44d3c4e65e3d4ebd", + "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": "98eace8be45a7482bd34d70f0b47cfc4a8e5574b64cd70fe2f05215815ee881e", + "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": "de4e8944fafcfdcbcf4062a5bdbea570fc3bac3a5849b09c1b5881388426087e", + "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": "b7b27a365b9c65a647d68013f7bc79ee490cc0bc5ac91cdf27c9ce5f5de0bb7e", + "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": "b7b27a365b9c65a647d68013f7bc79ee490cc0bc5ac91cdf27c9ce5f5de0bb7e", + "wram": "66378d77566d831f0f71472062bee6362359d67221e981586cfb5b2f5958dba6", + "audio": null, + "state": "25d098571f764336fe0f3a8e63438e749596f53a4065ccc6071868802172bd9d" + }, + { + "index": 125, + "op": "restore", + "boundary": "121", + "engineFrame": "122", + "worldTime": { + "numerator": "1037244140625", + "denominator": "512" + }, + "mask": null, + "frame": "4753fc53f7c1eea686729673e2f56105bfe210e3fa47cd6f269c530a4f2e5265", + "memory": "b7b27a365b9c65a647d68013f7bc79ee490cc0bc5ac91cdf27c9ce5f5de0bb7e", + "wram": "66378d77566d831f0f71472062bee6362359d67221e981586cfb5b2f5958dba6", + "audio": null, + "state": null + }, + { + "index": 126, + "op": "advance", + "boundary": "122", + "engineFrame": "123", + "worldTime": { + "numerator": "522908203125", + "denominator": "256" + }, + "mask": 4, + "frame": "cb83fd5fd54c4c80cc18d5c2ccb4256a6a0ceda285a98d3871044dc34a735d02", + "memory": "bef8a8a62edaf64f1953a862d250726486f768f9f97881a23479b17749399515", + "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": "c73aa5dd06a7423858bcdcca34dab68843be8c0655fd86e8398487d00abbf7d2", + "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": "8a5f54b1194f669514f618b3263768066e2dfb39cbc9389a2088231af8efad6d", + "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": "72482b14272df75e409d8a1f856558dc2fd456815922d7392873a7f54932ca9e", + "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": "4d72b66a02730d044657296959e03153d79d2208ab6fbb06cfb78863edd08120", + "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": "ba7cf3073d974e767ee9548c0dafb419cf674b5ad9856d0f32fb978907044377", + "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": "ff768a1ec139900aad4d0f25446334e1847ed9e010b1f0d91a1ad1ccf36398a0", + "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": "cd560595e81211c69246e0e5d3d4112f333eb366f10f161766248dcc3b1dd6ad", + "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": "819072b04101ca8eaeb7b06043401dcd4f3d0a290beca04a26d5a8d1be991fa9", + "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": "f8016aa21b88be29066516a10ad811cc1f330c7872a9088c80f1647db80af65d", + "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": "b7ddafb6160111a31f48580ecdfa888c91a823fbfb2940bad1c637f42a6c8fe6", + "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": "df5d5f2f0e94da51dcd67a351e8307c4e49299111bc882d991a19ade0fafcf0e", + "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": "351c61184b4a0b2030eff53b714bbc3a6dfe0fe5f51f35cddb1b2383ff884f15", + "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": "fcbf381fd1f7fb5083e8dd6a0c79242ebde8b7f0b1fdb9544abaf1a8ab96b5bd", + "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": "1d70f0aa1b6e6c6c9ee8616a9635d40145fcdef2ebfb09b523e4bcfb839c13e6", + "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": "9cdaa55c8023a273823545a665c2aae1bd6b60588593d98428572260cac90c73", + "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": "47b8550f20bb31f734992e85f5834828e5dafed6ffcfd9dd3141f910529f0e70", + "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": "88b91cd80c78087435f3fba149efb8ce519539dfa7fd501ef57eda6f6d28f2f6", + "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": "983f389df63ee2f13ee3e8e8b23e5611ecab007d954f4e774de3624d13acb81b", + "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": "056d7c6aa418d7df4e7ff7615fc03bcff78d49f2a88dc83b173fcec14c6a559f", + "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": "1a56a5b04c1539139f78e132add526c9b49b8c2d795d7ab8e16a2a3cd369072f", + "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": "8f82ea028216240adf490768416d7099b838d469a931854c278e02a9f2b72eff", + "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": "98622128d785112f10af09a630682cf3afc7bd6374ef9462824d9cc9d8309c07", + "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": "231e4be21b3c68dbadc227ac7a23a6fcff77597d43d891b9696d7a62d7d8028d", + "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": "cf050c959710c3feebfc09944430dc88ae6c869234ef2ae83029104f3991bfa8", + "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": "b4fd63b3f171d261814e57630e2a95d9ec4a9a3a4217d095dde779cb29181780", + "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": "50c44b727914319d7cf305432886d0455f3bd448a590a3e2f3a9316404c96b7b", + "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": "228832b613569eeaf2fceaf4fd66d1a2f3324c1d66d91cc476e940082d7f88cb", + "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": "dc51dc83c3bb1cffd4019a443de63fd94255e724d488c086ca73caebf320ae69", + "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": "6560b06eda267804944cbc8c79f66bafde47ca4ef9bc890d5721876f98c33b37", + "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": "5df84a2cb48ac24e72a5ea063f24caeca2e929bbdc368306a6adf856dc07f381", + "wram": "fd666c21dabe652d5a961e8b85ff4c93367d5519f588d860fbb4ba1ccf549ea4", + "audio": null, + "state": null + }, + { + "index": 157, + "op": "advance", + "boundary": "152", + "engineFrame": "153", + "worldTime": { + "numerator": "162873046875", + "denominator": "64" + }, + "mask": 32, + "frame": "753c140971ee4e9a32a1520a665ef9b0f9f7e1fa169df19d2f1b056d306aa456", + "memory": "99913ac75f748592be33444558d3c6de09be550d33a6cc18f7873a96022982bf", + "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": "dde0f4e61c121e197d4ab73c5e88b97d88a5ce70e65121b6685d6ea1b7c0f10a", + "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": "fe821bd102e3c68719afaa3e692dd4bcd25137e38f1f37d43235002436673090", + "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": "c9d50ef1267888680c843391f2a65f70920a66aeb7973fd50050fb2e5519e27f", + "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": "d067395e9f5e81ff806d7fd6b7e70b7cbdd90d752df4e5eb741e35d067260913", + "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": "0bcac811b589f14287de16b489c90654cd10e3668acf35b277ec819f2cc68ca5", + "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": "eb126d76c6ce673c28e5675ebd0fb932cb248124b06eaaa21754689c2ecd0e6e", + "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": "18d4413cf635d3f357cc0b35ecfb93e62b5c83089452fa038a691c6680cbd45e", + "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": "e3a243eeded545df442e2eb3adc038a01138a123cec3fe4be146725baa0e914a", + "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": "437e46cea00c641a95627fb236005b7dd3bc13b54f566be50f37af33f1ae2027", + "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": "16757275422c7ea7563f576d0d2bd3e13185c5befaeff60ee191fb6bbcd6c2c3", + "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": "83f2a128e5760a5558443f167019f67110c60cdb95388a181a665a4eabc8b80b", + "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": "fc56574365456b7529bf63cd9d2460727e168e3db875664618b34b30504b3c0a", + "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": "956a35f0f626308cdf40d3d3ba410f36b71e725a7d7fb056b7eea0c57c32b9a8", + "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": "1e4b8cfa3be8d375e13d74b052b8d85cf25577db7ecb188a7ac759eb377905d6", + "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": "e5ad32d46a6fc46b1e01903a42a4306b750f5a40ee3036c4a37df3e6cef1ff3a", + "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": "6fadb3c5f5bad99f3113578f62aebbafbd0aca1c1162b9a38a381ced0cb65425", + "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": "9a17563de2d5088374144578480c3cd462b0a17f56823d793911d221ab3a8ab0", + "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": "0e7a272b6f9c4827b9d2c2332eb561ef0f0a2e6f25731184302a1deacb4e29b9", + "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": "fd57cfa692d5b081a12cb7a1cf3d059921f563a56d83fac7b32d1e2230a5144e", + "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": "b2b01af52e6d875cdaa43f9438a5beae6a6b733b9616886bbf7ba67fafe600c1", + "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": "01899aafc113ecab1d11e8990ba7f8d530d426493953d66bc1ff6fe2b09a5067", + "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": "c8e9d4ff67374016ec913b88ee82b51f104fe5849f9acb0510d03d1c54dd5840", + "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": "4aab8018861ceeffa1ec9601c4886118cf6dce8e39a7eb44536cd20f0014c31d", + "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": "2c0618c688772debb4a5eef3de6b5214192ea0279373344df341e7d048665866", + "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": "cd0df3df4eeb879cbe217b769bd0f5e625ddcab38e5b345e09d9ab7eb90cba6f", + "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": "1a8fabf7867d4b3f2143630bdd2c76b1cc0813aa9b967c4fe1bc62b12095b810", + "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": "4ccd8a816fcaa9abc07bc542d94b10aaba72ae56c0035867984980547821e7fb", + "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": "3e899894aa240293d4f3a46f29291522753ebf24d6ba69ef0145c697cb60953d", + "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": "df34dd78a84e87f6e34e032c3de0480872c786b0b6ae174eda4389073ef2ad6d", + "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": "df34dd78a84e87f6e34e032c3de0480872c786b0b6ae174eda4389073ef2ad6d", + "wram": "eb8eb48fd3f1c0a93ca5f06d190cd2eae33a46d5df33d927245d55509cedf217", + "audio": null, + "state": "eceb68ba5c8c6ba1ba4833766a468bdef834dec57d8795aa4d329a53b97cedbc" + }, + { + "index": 188, + "op": "rollback", + "boundary": "181", + "engineFrame": "182", + "worldTime": { + "numerator": "1551580078125", + "denominator": "512" + }, + "mask": null, + "frame": "53a50210db831d20c781fc40e822559e99ac1839423c7214739fe646edaa833e", + "memory": "df34dd78a84e87f6e34e032c3de0480872c786b0b6ae174eda4389073ef2ad6d", + "wram": "eb8eb48fd3f1c0a93ca5f06d190cd2eae33a46d5df33d927245d55509cedf217", + "audio": null, + "state": null + }, + { + "index": 189, + "op": "advance", + "boundary": "182", + "engineFrame": "183", + "worldTime": { + "numerator": "780076171875", + "denominator": "256" + }, + "mask": 8, + "frame": "548df337e7d6185a9c2537b48bd42ef9ede7cb25b3ae8d1c9ad6cbe082ee717f", + "memory": "a18803e7f49347897f0a1cba651983d53ba40502fa4b364c8d592e422bdc9ba3", + "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": "e98db1a1b7f342ae26415a26d738c7cbe37e1a084c1c2c12afc61e1899c79c92", + "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": "e41355a82cf4b39d0bc33616e4f010f37893b1f97ec817c40c52852bc6207e8d", + "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": "1888ace3c14cb099e550b13a361eec9ccd665f3053e76ce516a2618e31b41e73", + "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": "44c8552edcd1b433686738c9256073dabc5768a30371c06cd3b7b954101244ad", + "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": "32b6d3282b21800bf026064885647a9567e57ceb174432b0dbb71f9d8cb7e75b", + "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": "ebd7db66a5c807f4b5a61a29bc949f34c0bc45a39a756869628ef73b3253b571", + "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": "c700dd0a9e2ee351a4c42534b74fdd9c172a965cbd88b017a38c8b6de1921db5", + "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": "79d3798cd77e79a363e3364ab1c05929065530569b524acedb5b58e239049721", + "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": "2d06eaf1de62ff744a4aa16dc657d6af5c071727c749cd821da32c3ec28bc91d", + "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": "49d44390cb6381ef9c5d1520b522ef378ff9087669047f3a7d221edc503dd4c7", + "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": "db1f0603a68a42e08262b79d78fc98657b2614d48a05de502815561b0b9d1058", + "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": "3a0ba40870d9fa1c4ca7f01f4ec13d9e608212d057040a425e4636b05942f1d4", + "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": "db8e4b16f60de6cd322d85251ae18879ae592ca0f9ab338d76094ff0216d9fe4", + "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": "43367e1d96780dddfde72eaa7f2533817885b44446714f8b871207ab4c59062a", + "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": "2bcfcb1240dc114a1ce06f3a93192ac9dc09454e239540a7ebdb14129b7fc442", + "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": "6b134910b534affdc25848e14f47815834797e26c0a78882cf36b34ffcc23ce4", + "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": "593c0e0ed2137fe1683726dc9783706e7edc3290176b900e0c12ec49aa1b3116", + "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": "4cdcc64176452001359cdb15312dc6376af8abbda99990252919f9b7b2d559f7", + "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": "2c9c26db7638d4b8c2bcc1f8f3b3178cbee22c57e97241e63ffea03409ecf4f0", + "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": "bc69ee60755d86476f35952b3b5f9b95a43a3b03098a20742871180717166850", + "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": "c8fa1595204597b959a235f984ec56f31a1751796269f12c4d9d396add7d9b0d", + "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": "1f3ab45354a5791290f0f2ab0300340e2a64b3f84b90212c65bba4a2baabcb45", + "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": "98bc367c3f7de356a95d9cefd0557e8ff244092c7320c7c89e85ff972faa4c2c", + "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": "1897def9cc5190fe7e3ba62402277b20eb3fa5694ddfdf4ab38048b61751add6", + "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": "310a7a0ebed04427fe109280abb5bb3dcece6bb89a7b42ba50442cf651357600", + "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": "48a08f4f9910877e81efe8f3986b51194295b421dceac83defbfad99f1777d44", + "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": "95ab525dfae1953924648f5447c485ceafc4b37fe22be549e9e9ca12cca135cb", + "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": "a2612f54c5717b9ba309fab61b6cc990d3bc348e5f1ab63bf312c61edb226a0d", + "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": "60f94e284cfbcad6c91e063654b8330c33edcc8b412e7c052b8a2f9b7caf417d", + "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": "43b24046bef5decdc10b02217f5e1ebbe5ab75b102eb977e85cdf356f3a2a21c", + "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": "c3b46e07b3f591abae1c84f011daec47a600dfeff5b422daef42a335170da8f5", + "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": "3719174749289aaea1b6524eca37deb9a2a475d4660b5c361453b8094a6dae9c", + "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": "e582974d8ea5cbad75436716e44f5c440c8a11080c5614315e5a9abd2e4a2223", + "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": "31e35b20005979cd127e6b816813538ff9cdd2e15490f2a1eaf724c6d94ee3a7", + "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": "3b7c6403e7b4d47e6968222a6d6f6af55666fb10a0d9907d8368375b7253b74a", + "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": "8ed66752b7947f30ded32b98883608f5ced5a384422c965b54d1df07c2faefaa", + "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": "74e5accaced6d49a56dc8371e922c6d12e3793ce830d8f24285e18b363760f77", + "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": "c807a5d4e91b45d4302a108d39b2be697190fd0704b753134088d06e05ecde6a", + "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": "c1b97c3158010f6170d7d6e087fba6ba03834caa4da3aea6d79ad560fdc82c0f", + "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": "61c6a18cb2da5d3ad373bf32afbe8e8eb2ea7b7ac7d18c8f1e5d185b4cb5a036", + "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": "45e385eb2d13662ad8fa41e6b55548150ac5fb1316795a65395352203a7a57c0", + "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": "eea0fdc4b6a058944977c1c11c57ab809ca97d743690837929aaf44377418303", + "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": "7838e9e6994596f21d222d0b6fd932678a0d653f25267ba20b36aab2f06adba7", + "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": "c11eef9cfca12cf1758e478484ce8575e71c4f4fd28cedc8315847c44b97ed51", + "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": "3ce2abd2154d3961bfa762819a94caefdcb30730d23dc565a60ed9651fe3bd81", + "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": "fab7e93ca09fbcc71beb2b9dcc02da0558e4921dd4a8cf045fad8c0078bd5426", + "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": "56a8b1f90777f739b992039d77ee29afdf34d4c97f30c40a6913e0568ecba039", + "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": "bdff6dc52856af939b14ee246a67cdf8c9170d2e5915220fbdf5a4cc9b815d8e", + "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": "c70db510bc307cf4bf018f3bc69e72183428c5a97cb107cdb7d69225f9da0ee4", + "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": "4c424ffa8ac949c4b9215499934dd52fdb415637ccc0583cdde378abd2e1ea83", + "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": "2996e482cf5f9b3c984b904be55b685d4fc129e5b571c04075cea82701239bdf", + "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": "52738f1d5363a06dc91f3e4815d2b29d59ab2b8904290a077718a5ba3430c378", + "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": "817e6ccc557162a46c2859a08da60eacbdaa44eee9c22867eb604a699ef76507", + "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": "f509524ebe1ed45a938cf7c6ec94f89f9f499c769f5921edf7d6f7f8a6c0b1aa", + "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": "144a8aeedc8eafb292af7417fd6261f2128c23835aec4796603da76d1b8c2002", + "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": "ca6ebffb428e626b2e4f6c4233930b2db3d9a642b9dfc2a3c0e27be2fec2dc94", + "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": "1697c388a4308e510ce19f6ec63d65088065496ec96190177b7950e237af9df3", + "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": "c6e9a785399e0e9386b01acb3ab3421b381282736f08dcdea313ada4c48b7842", + "wram": "d34426d040a0162851e78b564935a8470b647bc1b270e580d0194bec028e1eb9", + "audio": { + "firstSample": "192071", + "frames": 804, + "digest": "7707656b2b52437a2e2ef4a3ddd8d7d0f66a32282802a57af5ef7fdb6bafb084", + "discontinuity": false + }, + "state": null + } + ] +} 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 0000000..41935a3 Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/indptr.binz differ diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/meta.json b/services/flysim/crates/fly-session/fixtures/legacy-toy/meta.json new file mode 100644 index 0000000..ce8f896 --- /dev/null +++ b/services/flysim/crates/fly-session/fixtures/legacy-toy/meta.json @@ -0,0 +1 @@ +{"schemaVersion":1,"dataset":"legacy-toy","neurons":4096,"edges":40960,"roles":{"command_0":[1344,1345,1346,1347,1348,1349,1350,1351,1352,1353,1354,1355,1356,1357,1358,1359,1360,1361,1362,1363,1364,1365,1366,1367,1368,1369,1370,1371,1372,1373,1374,1375],"command_1":[1376,1377,1378,1379,1380,1381,1382,1383,1384,1385,1386,1387,1388,1389,1390,1391,1392,1393,1394,1395,1396,1397,1398,1399,1400,1401,1402,1403,1404,1405,1406,1407],"command_2":[1408,1409,1410,1411,1412,1413,1414,1415,1416,1417,1418,1419,1420,1421,1422,1423,1424,1425,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439],"command_3":[1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1470,1471],"command_4":[1472,1473,1474,1475,1476,1477,1478,1479,1480,1481,1482,1483,1484,1485,1486,1487,1488,1489,1490,1491,1492,1493,1494,1495,1496,1497,1498,1499,1500,1501,1502,1503],"command_5":[1504,1505,1506,1507,1508,1509,1510,1511,1512,1513,1514,1515,1516,1517,1518,1519,1520,1521,1522,1523,1524,1525,1526,1527,1528,1529,1530,1531,1532,1533,1534,1535],"command_6":[1536,1537,1538,1539,1540,1541,1542,1543,1544,1545,1546,1547,1548,1549,1550,1551,1552,1553,1554,1555,1556,1557,1558,1559,1560,1561,1562,1563,1564,1565,1566,1567],"command_7":[1568,1569,1570,1571,1572,1573,1574,1575,1576,1577,1578,1579,1580,1581,1582,1583,1584,1585,1586,1587,1588,1589,1590,1591,1592,1593,1594,1595,1596,1597,1598,1599],"reward_pam":[1280,1281,1282,1283,1284,1285,1286,1287,1288,1289,1290,1291,1292,1293,1294,1295,1296,1297,1298,1299,1300,1301,1302,1303,1304,1305,1306,1307,1308,1309,1310,1311,1312,1313,1314,1315,1316,1317,1318,1319,1320,1321,1322,1323,1324,1325,1326,1327,1328,1329,1330,1331,1332,1333,1334,1335,1336,1337,1338,1339,1340,1341,1342,1343],"steer_left":[2400,2401,2402,2403,2404,2405,2406,2407,2408,2409,2410,2411,2412,2413,2414,2415,2416,2417,2418,2419,2420,2421,2422,2423,2424,2425,2426,2427,2428,2429,2430,2431],"steer_right":[2432,2433,2434,2435,2436,2437,2438,2439,2440,2441,2442,2443,2444,2445,2446,2447,2448,2449,2450,2451,2452,2453,2454,2455,2456,2457,2458,2459,2460,2461,2462,2463],"visual_l1":[1600,1601,1602,1603,1604,1605,1606,1607,1608,1609,1610,1611,1612,1613,1614,1615,1616,1617,1618,1619,1620,1621,1622,1623,1624,1625,1626,1627,1628,1629,1630,1631,1632,1633,1634,1635,1636,1637,1638,1639,1640,1641,1642,1643,1644,1645,1646,1647,1648,1649,1650,1651,1652,1653,1654,1655,1656,1657,1658,1659,1660,1661,1662,1663,1664,1665,1666,1667,1668,1669,1670,1671,1672,1673,1674,1675,1676,1677,1678,1679,1680,1681,1682,1683,1684,1685,1686,1687,1688,1689,1690,1691,1692,1693,1694,1695,1696,1697,1698,1699,1700,1701,1702,1703,1704,1705,1706,1707,1708,1709,1710,1711,1712,1713,1714,1715,1716,1717,1718,1719,1720,1721,1722,1723,1724,1725,1726,1727,1728,1729,1730,1731,1732,1733,1734,1735,1736,1737,1738,1739,1740,1741,1742,1743,1744,1745,1746,1747,1748,1749,1750,1751,1752,1753,1754,1755,1756,1757,1758,1759,1760,1761,1762,1763,1764,1765,1766,1767,1768,1769,1770,1771,1772,1773,1774,1775,1776,1777,1778,1779,1780,1781,1782,1783,1784,1785,1786,1787,1788,1789,1790,1791,1792,1793,1794,1795,1796,1797,1798,1799,1800,1801,1802,1803,1804,1805,1806,1807,1808,1809,1810,1811,1812,1813,1814,1815,1816,1817,1818,1819,1820,1821,1822,1823,1824,1825,1826,1827,1828,1829,1830,1831,1832,1833,1834,1835,1836,1837,1838,1839,1840,1841,1842,1843,1844,1845,1846,1847,1848,1849,1850,1851,1852,1853,1854,1855,1856,1857,1858,1859,1860,1861,1862,1863,1864,1865,1866,1867,1868,1869,1870,1871,1872,1873,1874,1875,1876,1877,1878,1879,1880,1881,1882,1883,1884,1885,1886,1887,1888,1889,1890,1891,1892,1893,1894,1895,1896,1897,1898,1899,1900,1901,1902,1903,1904,1905,1906,1907,1908,1909,1910,1911,1912,1913,1914,1915,1916,1917,1918,1919,1920,1921,1922,1923,1924,1925,1926,1927,1928,1929,1930,1931,1932,1933,1934,1935,1936,1937,1938,1939,1940,1941,1942,1943,1944,1945,1946,1947,1948,1949,1950,1951,1952,1953,1954,1955,1956,1957,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1968,1969,1970,1971,1972,1973,1974,1975,1976,1977,1978,1979,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022,2023,2024,2025,2026,2027,2028,2029,2030,2031,2032,2033,2034,2035,2036,2037,2038,2039,2040,2041,2042,2043,2044,2045,2046,2047,2048,2049,2050,2051,2052,2053,2054,2055,2056,2057,2058,2059,2060,2061,2062,2063,2064,2065,2066,2067,2068,2069,2070,2071,2072,2073,2074,2075,2076,2077,2078,2079,2080,2081,2082,2083,2084,2085,2086,2087,2088,2089,2090,2091,2092,2093,2094,2095,2096,2097,2098,2099,2100,2101,2102,2103,2104,2105,2106,2107,2108,2109,2110,2111,2112,2113,2114,2115,2116,2117,2118,2119,2120,2121,2122,2123,2124,2125,2126,2127,2128,2129,2130,2131,2132,2133,2134,2135,2136,2137,2138,2139,2140,2141,2142,2143,2144,2145,2146,2147,2148,2149,2150,2151,2152,2153,2154,2155,2156,2157,2158,2159,2160,2161,2162,2163,2164,2165,2166,2167,2168,2169,2170,2171,2172,2173,2174,2175,2176,2177,2178,2179,2180,2181,2182,2183,2184,2185,2186,2187,2188,2189,2190,2191,2192,2193,2194,2195,2196,2197,2198,2199,2200,2201,2202,2203,2204,2205,2206,2207,2208,2209,2210,2211,2212,2213,2214,2215,2216,2217,2218,2219,2220,2221,2222,2223,2224,2225,2226,2227,2228,2229,2230,2231,2232,2233,2234,2235,2236,2237,2238,2239,2240,2241,2242,2243,2244,2245,2246,2247,2248,2249,2250,2251,2252,2253,2254,2255,2256,2257,2258,2259,2260,2261,2262,2263,2264,2265,2266,2267,2268,2269,2270,2271,2272,2273,2274,2275,2276,2277,2278,2279,2280,2281,2282,2283,2284,2285,2286,2287,2288,2289,2290,2291,2292,2293,2294,2295,2296,2297,2298,2299,2300,2301,2302,2303,2304,2305,2306,2307,2308,2309,2310,2311,2312,2313,2314,2315,2316,2317,2318,2319,2320,2321,2322,2323,2324,2325,2326,2327,2328,2329,2330,2331,2332,2333,2334,2335,2336,2337,2338,2339,2340,2341,2342,2343,2344,2345,2346,2347,2348,2349,2350,2351,2352,2353,2354,2355,2356,2357,2358,2359,2360,2361,2362,2363,2364,2365,2366,2367,2368,2369,2370,2371,2372,2373,2374,2375,2376,2377,2378,2379,2380,2381,2382,2383,2384,2385,2386,2387,2388,2389,2390,2391,2392,2393,2394,2395,2396,2397,2398,2399]},"visual":{"population":"toy-retina","count":800}} diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/targets.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/targets.binz new file mode 100644 index 0000000..84d574d Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/targets.binz differ 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 0000000..4203e09 Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-hemisphere.binz differ 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 0000000..1c50f0e Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-indices.binz differ 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 0000000..feb31e6 Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-xy.binz differ 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 0000000..c148f83 Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/weights.binz differ 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..ddb6a66 --- /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": "5139fb8a99c6503ac2315f5a5ed754a6054e6eb8068acdd2b649931ccd40a02f", + "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- 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", + "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 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", + "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 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", + "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 14a5132bd706cea1 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/src/cli.rs b/services/flysim/crates/fly-session/src/cli.rs index dcb0df7..5f54c2d 100644 --- a/services/flysim/crates/fly-session/src/cli.rs +++ b/services/flysim/crates/fly-session/src/cli.rs @@ -22,15 +22,21 @@ 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, LegacyEnvironmentLaunch, + Started, flags, serve_one, }; +use crate::legacy_agent::LegacyProfileKind; +use crate::legacy_env::BackendConfig; 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 + 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) @@ -47,9 +53,14 @@ 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] + 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) @@ -75,8 +86,14 @@ 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)), + "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 +237,35 @@ 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(), + }), + "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)?, @@ -259,11 +305,29 @@ fn serve(role: &str, options: &Options) -> Result<(), String> { }) } -fn parse_ports(value: &str) -> Result, String> { +fn parse_channels(value: &str) -> Result, String> { value .split(',') .filter(|part| !part.is_empty()) - .map(|part| parse_id(part).map_err(|e| format!("--ports: {e}"))) + .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> { + 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!("--{flag}: {e}"))) .collect() } 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/launcher.rs b/services/flysim/crates/fly-session/src/launcher.rs index 65827b6..d867ede 100644 --- a/services/flysim/crates/fly-session/src/launcher.rs +++ b/services/flysim/crates/fly-session/src/launcher.rs @@ -30,6 +30,8 @@ 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::legacy_env::{BackendConfig, LegacyEnvironmentConfig, LegacyGameboyEnvironment}; use crate::rpc::WorkerRef; use crate::types::*; use crate::worker::{StatusCell, WorkerHandle, serve}; @@ -257,6 +259,44 @@ 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, +} + +/// 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 @@ -581,6 +621,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, @@ -613,6 +685,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, @@ -690,11 +795,25 @@ 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(); (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 +1369,17 @@ 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 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"; @@ -1281,6 +1411,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, @@ -1297,6 +1429,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]; } @@ -1313,14 +1456,18 @@ fn arg(name: &str, value: impl std::fmt::Display) -> (String, String) { #[derive(Clone, Debug)] pub(crate) enum Started { Agent(AgentLaunch), + LegacyAgent(LegacyAgentLaunch), Environment(EnvironmentLaunch), + LegacyEnvironment(LegacyEnvironmentLaunch), } impl Started { pub(crate) fn subcommand(&self) -> &'static str { match self { Started::Agent(_) => "agent", + Started::LegacyAgent(_) => "legacy-agent", Started::Environment(_) => "environment", + Started::LegacyEnvironment(_) => "legacy-environment", } } @@ -1350,6 +1497,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), @@ -1387,6 +1545,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), + ], } } } @@ -1405,6 +1575,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(), @@ -1419,6 +1601,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( @@ -1441,9 +1637,19 @@ 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))) } + Started::LegacyEnvironment(spec) => serve( + client, + service, + LegacyGameboyEnvironment::new(legacy_environment_config(spec, worker_threads)), + ), }) } @@ -1528,6 +1734,36 @@ 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(), + } + } + + 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 +1775,14 @@ 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], + ), + ( + Started::LegacyEnvironment(legacy_environment_launch()), + [flags::COMMON, flags::LEGACY_ENVIRONMENT_ONLY], + ), ] { let arguments = started.arguments(); assert!(!arguments.is_empty()); 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..3367247 --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -0,0 +1,1878 @@ +//! 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"; +/// 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. +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 capture payload + +/// Everything in a `FLYAGT01` capture payload's `session` member except the accumulator and the +/// context: whose state it is, where it was taken and under which identities. +#[derive(Clone, Copy, Debug)] +pub struct PayloadIdentity<'a> { + 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 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 { + 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 + +/// 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))?; + 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, + }, + accumulator, + &context.typed, + None, + ) + .map_err(|e| DomainError::new(ErrorCode::Internal, e, 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")); + } + // 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)?; + 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}")))?; + // 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); + } + 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/legacy_checkpoint.rs b/services/flysim/crates/fly-session/src/legacy_checkpoint.rs new file mode 100644 index 0000000..7e0210a --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_checkpoint.rs @@ -0,0 +1,1216 @@ +//! 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, + /// 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, +} + +// ------------------------------------------------------------------------------------------- +// 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( + reinforcements: u64, + 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, + reinforcements: Some(reinforcements), + 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, + reinforcements: u64, + world: &WorldState, + slot_id: &Id, + task: &TaskHalf, + host: &HostHalf, +) -> Result, String> { + 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. +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 reinforcements = legacy_agent::decode_payload_reinforcements(agent_payload)?; + let world = world_state(world_payload)?; + export_states(&agent, reinforcements, &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 { + reinforcements: runtime + .reinforcements + .unwrap_or_else(|| legacy_reinforcements(&checkpoint.agent)), + 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, + reinforcements: u64, + 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, + 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 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 { + 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, 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, + &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, + reinforcements: Some(55), + 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.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, 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()); + } + + #[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, 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, 70, &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, + legacy_reinforcements(&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_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); + 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, 3, &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_env.rs b/services/flysim/crates/fly-session/src/legacy_env.rs new file mode 100644 index 0000000..a423c70 --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_env.rs @@ -0,0 +1,1615 @@ +//! 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 (`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`. +/// +/// 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`). +/// +/// (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> { + Ok(emulator.read_memory_image().as_bytes().to_vec()) +} + +/// 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/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs new file mode 100644 index 0000000..24d5f41 --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -0,0 +1,2026 @@ +//! AGENT-01's parity harness: recorded inputs, a reference that drives [`NeuralAgent`] directly +//! in the legacy frame order, the same inputs driven through a launched [`LegacyAgentWorker`] +//! over the bus, and a record-by-record comparison. +//! +//! ```text +//! LegacyScript ──> 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. +//! +//! 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. + +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 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() + .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, + // 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)), + } + }; + 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. +/// +/// [`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>; +} + +// ------------------------------------------------------------------------------------------- +// 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` (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, + 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 (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() { + 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 + } + + /// 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`). + /// + /// 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( + &mut self, + rig: &mut LegacyRig, + 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?; + // 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, + reinforcements, + &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 + .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)?; + // 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)?; + 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 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( + 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 start = start.map(|state| (state, legacy_reinforcements(state))); + 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, 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"))) +} + +async fn run_script( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, + 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, reinforcements)) => { + driver + .seed_with_reinforcements(rig, agent_id, script.initial_frame, state, reinforcements) + .await? + } + }; + let mut records = vec![first]; + 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); + } + let captured = if capture_at_end { + Some(driver.capture().await?.bytes) + } else { + None + }; + Ok((records, captured)) +} + +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::>(), + }) +} + +// ------------------------------------------------------------------------------------------- +// 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::*; + + #[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 6849001..63edd03 100644 --- a/services/flysim/crates/fly-session/src/lib.rs +++ b/services/flysim/crates/fly-session/src/lib.rs @@ -29,6 +29,11 @@ pub mod dedup; 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; pub mod measure; pub mod media; pub mod metrics; 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/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 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..36c91a0 --- /dev/null +++ b/services/flysim/crates/fly-session/tests/legacy_agent.rs @@ -0,0 +1,885 @@ +//! 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; + } +} + +/// 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")); + } + } +} + +/// 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/fly-session/tests/legacy_env.rs b/services/flysim/crates/fly-session/tests/legacy_env.rs new file mode 100644 index 0000000..d1c9267 --- /dev/null +++ b/services/flysim/crates/fly-session/tests/legacy_env.rs @@ -0,0 +1,630 @@ +//! 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); + // 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() { + 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, "a register 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 +); 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; 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 | 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"); +} 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..2e4e562 --- /dev/null +++ b/services/flysim/crates/flysim-store/src/store.rs @@ -0,0 +1,665 @@ +//! 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, + /// 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. + 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)?)?); + 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())); + 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, + reinforcements: number("reinforcements").ok().map(|n| n as u64), + 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() }, + reinforcements: Some(1_234), + 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_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(); + 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 b3184ba..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"] } @@ -55,6 +57,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/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/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..c142541 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) } @@ -317,6 +326,7 @@ mod tests { }, }; let runtime = store::RuntimeState { + reinforcements: None, generation, wall_ms: 1_700_000_000_000, rom_sha256: "ab".repeat(32), @@ -379,6 +389,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 +422,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..f83d831 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), @@ -1380,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/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::*; 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; +} 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/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()); +} 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..984009f --- /dev/null +++ b/services/flysim/crates/flysim/tests/state_02.rs @@ -0,0 +1,829 @@ +//! 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), + ("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), + ("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.reinforcements, + &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 { + reinforcements: Some(halves.reinforcements), + 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, + 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(), + 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, halves.reinforcements)), + ) + .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, again.reinforcements)), + ) + .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..df8541f --- /dev/null +++ b/services/flysim/crates/flysim/tests/state_02_store.rs @@ -0,0 +1,351 @@ +//! 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), 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 }, + } +} + +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, + reinforcements: None, + 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; + // 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(),