Merge port/integration (reviewed: APPROVE-WITH-NOTES)

This commit is contained in:
acamilo 2026-09-29 18:43:19 +00:00
commit 70e5ad6134
59 changed files with 21022 additions and 854 deletions

View file

@ -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`, legacy rate-role names (`command_0`, `macro_*`, which are not `Id`s) to `AgentGraph.rateRoles`,
which that contract leaves open. 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; **Implement:** adapter over existing LIF, plasticity, retina and fixed readout primitives;
reference-first composition/goldens; independently seeded agent state and shared immutable data. 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. 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 (section 3), and the fingerprint and compatibility string are embedded unchanged (sections 2
and 12). The acceptance criteria below stand. 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 **Implement:** binjgb environment, task-local memory inspector and identity/existing action
adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash semantics. 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 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. 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 ### STATE-01 — Coherent all-participant checkpoint/recovery
**Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01. **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. 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. 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-<N>` 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<N>`). 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-<rank>` 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-<N>` 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 ### PUBLISH-01 — Committed snapshots and observer isolation
**Depends on:** SESSION-02, MEDIA-01; public v2 contract work is a separate prerequisite to **Depends on:** SESSION-02, MEDIA-01; public v2 contract work is a separate prerequisite to

View file

@ -125,7 +125,8 @@ interface GameboyReadoutContext {
``` ```
`ChannelName` is `^[a-z][a-z0-9_]{0,63}$`. Decoder channel and rate-role names carry `_`, so `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 `initialDecisionContext`, then every `nextDecisionContext`). `bound` is an ordered subset of the
composition's `macroChannels`. 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. 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, 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 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. - **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. 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 ## 9. Environment
- **Initialize.** The backend configuration declares a setup scaffold of **one frame with no - **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 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). 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` ## 10. Executor `pokered-macros-v1`
The Pokémon Red task (reward adapter, ladder, ratchet ledger) and its action executor (the 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 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. 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` ## 14. Restore `legacy-transient-reset`
The legacy composition declares that a restore (a FLYSIM01 load today, and any group restore 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 checkpoint may be written beside it, but it is not what a restore selects until RETIRE-01
says so. 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-<N>` 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-<rank>` 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) ## 17. PROF-02b: MaleCNS bundles (later)
Dataset manifests, original-ID mapping, anatomical roles, sensory and readout bindings, strict Dataset manifests, original-ID mapping, anatomical roles, sensory and readout bindings, strict

View file

@ -14,8 +14,8 @@ import { digestOf, fail } from './canonical';
import { readRational, readSchemaRef } from './common'; import { readRational, readSchemaRef } from './common';
import { Reader, readArtifactRef, requireUnique, u64 } from './reader'; import { Reader, readArtifactRef, requireUnique, u64 } from './reader';
import type { ArtifactRef, Digest, Id, RationalNs, SchemaRef, TypedValue } from './scalar'; import type { ArtifactRef, Digest, Id, RationalNs, SchemaRef, TypedValue } from './scalar';
import { isDigest } from './scalar'; import { isDigest, isId } from './scalar';
import { type AssetRef, readAssetRef } from './workers'; import { type AssetRef, MAX_RATE_ROLES, readAssetRef } from './workers';
import { MAX_SLOTS, ROLLBACK_POLICY, SLOTS_CAPABILITY } from './extensions'; import { MAX_SLOTS, ROLLBACK_POLICY, SLOTS_CAPABILITY } from './extensions';
export const PROFILE_ID = 'gameboy-legacy-fafb-v783-v1'; 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. */ /** The legacy profile document's AssetRef digest: SHA-256 of its canonical JSON. */
export const PROFILE_DIGEST = '41e5d1ac62ab23f1b2d7252d52faac08b269c85e6b4c9ed7a370c74032c60878'; 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 { export function isChannelName(value: unknown): value is string {
return typeof value === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(value); 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 { export function decoderConfigDigest(config: DecoderConfigLike): Digest {
return digestOf(decoderConfigForm(config)); 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;
}

View file

@ -174,3 +174,24 @@ test('the decoderConfigDigest vectors are what the TypeScript oracle preset comp
assert.equal(example.decoderConfigDigest, cases[1]!.digest); assert.equal(example.decoderConfigDigest, cases[1]!.digest);
assert.deepEqual(example.executor.macroChannels, cases[1]!.macroChannels); 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<string, any>;
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']));
});

View file

@ -439,8 +439,12 @@ dependencies = [
name = "fly-session" name = "fly-session"
version = "0.1.1" version = "0.1.1"
dependencies = [ dependencies = [
"flate2",
"fly-session-types", "fly-session-types",
"flybrain-core",
"flybrain-gb",
"flybus", "flybus",
"flysim-store",
"serde_json", "serde_json",
"tempfile", "tempfile",
"tokio", "tokio",
@ -500,10 +504,12 @@ dependencies = [
"anyhow", "anyhow",
"axum", "axum",
"clap", "clap",
"fly-session",
"fly-session-types", "fly-session-types",
"flybrain-core", "flybrain-core",
"flybrain-gb", "flybrain-gb",
"flybus", "flybus",
"flysim-store",
"futures-util", "futures-util",
"jsonschema", "jsonschema",
"serde", "serde",
@ -519,6 +525,19 @@ dependencies = [
"unicode-normalization", "unicode-normalization",
] ]
[[package]]
name = "flysim-store"
version = "0.1.1"
dependencies = [
"anyhow",
"flybrain-core",
"flybrain-gb",
"serde",
"serde_json",
"tempfile",
"tracing",
]
[[package]] [[package]]
name = "foldhash" name = "foldhash"
version = "0.2.0" version = "0.2.0"

View file

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

View file

@ -0,0 +1,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"
}
]
}

View file

@ -413,6 +413,60 @@ pub fn extension_set_digest() -> String {
canonical::digest_of(&extension_set()).expect("canonicalizable") 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<String> {
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<String> {
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<Item = &'a str>) -> Result<Vec<String>> {
let ids = names
.into_iter()
.map(rate_role_id)
.collect::<Result<Vec<String>>>()?;
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 // Scalars and helpers

View file

@ -348,3 +348,44 @@ fn the_extension_methods_check_their_scope() {
assert_eq!(SLOTS_CAPABILITY, "gameboy-slots-v1"); assert_eq!(SLOTS_CAPABILITY, "gameboy-slots-v1");
assert_eq!(ROLLBACK_CAPABILITY, ROLLBACK_POLICY); 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<String> = (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());
}

View file

@ -23,6 +23,17 @@ path = "src/bin/fly-session.rs"
# Everything else this crate needs is std or Tokio. # Everything else this crate needs is std or Tokio.
fly-session-types = { path = "../fly-session-types" } fly-session-types = { path = "../fly-session-types" }
flybus = { path = "../flybus" } 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 } serde_json = { workspace = true }
# `rt-multi-thread` is not only for the tests: a worker process and a dedicated-thread # `rt-multi-thread` is not only for the tests: a worker process and a dedicated-thread

View file

@ -47,6 +47,9 @@ Ready(k) ─ Prepare all agents concurrently ───────────
| `cli` | The binary's subcommands: `agent`, `environment`, `measure` | | `cli` | The binary's subcommands: `agent`, `environment`, `measure` |
| `state` | The durable checkpoint store over `FLYSESS1`: compatibility, generations, the bounded writer | | `state` | The durable checkpoint store over `FLYSESS1`: compatibility, generations, the bounded writer |
| `harness` | The runnable composition: router, the flies, one arena, one coordinator | | `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 ## Execution modes and the launcher
@ -88,6 +91,7 @@ A separate-process participant is a subcommand of this crate's one binary, which
```sh ```sh
fly-session agent --socket S --store-root D --client-id C --service N --threads T ... 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 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 fly-session measure --steps 300 --agents 1,2,4
``` ```

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

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

View file

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

View file

@ -22,15 +22,21 @@ use std::process::ExitCode;
use crate::agent::AgentFaults; use crate::agent::AgentFaults;
use crate::environment::EnvironmentFaults; use crate::environment::EnvironmentFaults;
use crate::launcher::{ 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::*; use crate::types::*;
const USAGE: &str = "\ const USAGE: &str = "\
fly-session <command> [options] fly-session <command> [options]
agent serve one agent worker on a launcher-created endpoint 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 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 compare the execution modes and print the measurement table
measure-row measure one row and print it as JSON (one child per row) 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] --warmup-ticks N [--prepare-delay-ms N] [--commit-delay-ms N]
[--fail-commit-at-step N] [--fail-commit-at-step N]
[--fail-stage-restore 0|1] [--fail-activate-restore 0|1] [--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 environment: --worker ID --ports p1,p2 --step-numerator N --step-denominator N
[--advance-delay-ms N] [--omit-view-at-boundary N] [--advance-delay-ms N] [--omit-view-at-boundary N]
[--fail-stage-restore 0|1] [--fail-activate-restore 0|1] [--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: Measure options:
--steps N transitions per run (default 200) --steps N transitions per run (default 200)
@ -75,8 +86,14 @@ pub fn main() -> ExitCode {
let result = match command.as_str() { let result = match command.as_str() {
"agent" => Options::parse(&rest, &[flags::COMMON, flags::AGENT_ONLY]) "agent" => Options::parse(&rest, &[flags::COMMON, flags::AGENT_ONLY])
.and_then(|o| serve(&command, &o)), .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]) "environment" => Options::parse(&rest, &[flags::COMMON, flags::ENVIRONMENT_ONLY])
.and_then(|o| serve(&command, &o)), .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" => Options::parse(&rest, &[flags::MEASURE]).and_then(|o| measure(&o)),
"measure-row" => Options::parse(&rest, &[flags::MEASURE]).and_then(|o| measure_row(&o)), "measure-row" => Options::parse(&rest, &[flags::MEASURE]).and_then(|o| measure_row(&o)),
"--help" | "-h" | "help" => { "--help" | "-h" | "help" => {
@ -220,6 +237,35 @@ fn serve(role: &str, options: &Options) -> Result<(), String> {
client_id: client_id.clone(), client_id: client_id.clone(),
service: service.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 { _ => Started::Environment(EnvironmentLaunch {
session_id, session_id,
worker_id: options.id(flags::WORKER)?, worker_id: options.id(flags::WORKER)?,
@ -259,11 +305,29 @@ fn serve(role: &str, options: &Options) -> Result<(), String> {
}) })
} }
fn parse_ports(value: &str) -> Result<Vec<Id>, String> { fn parse_channels(value: &str) -> Result<Vec<String>, String> {
value value
.split(',') .split(',')
.filter(|part| !part.is_empty()) .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<Vec<Id>, String> {
parse_ids(value, flags::PORTS)
}
fn parse_ids(value: &str, flag: &str) -> Result<Vec<Id>, String> {
value
.split(',')
.filter(|part| !part.is_empty())
.map(|part| parse_id(part).map_err(|e| format!("--{flag}: {e}")))
.collect() .collect()
} }

View file

@ -336,6 +336,9 @@ pub struct Coordinator {
/// Set by whoever asks for a normal pause, possibly while a transition is in flight. /// Set by whoever asks for a normal pause, possibly while a transition is in flight.
pause: std::sync::Arc<std::sync::atomic::AtomicBool>, pause: std::sync::Arc<std::sync::atomic::AtomicBool>,
episode: Option<EpisodeRequest>, episode: Option<EpisodeRequest>,
/// 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<Id>,
lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>, lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>,
stats: Stats, stats: Stats,
/// The ordered actions this session took, for the ordering assertions. /// The ordered actions this session took, for the ordering assertions.
@ -431,6 +434,7 @@ impl Coordinator {
pacing: None, pacing: None,
pause: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), pause: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
episode: None, episode: None,
rollback_policy: None,
lifecycle_acks: Vec::new(), lifecycle_acks: Vec::new(),
stats: Stats::default(), stats: Stats::default(),
audit: Vec::new(), audit: Vec::new(),
@ -526,6 +530,22 @@ impl Coordinator {
self.timelines.positions() 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> { pub fn episode_request(&self) -> Option<&EpisodeRequest> {
self.episode.as_ref() self.episode.as_ref()
} }
@ -1676,6 +1696,22 @@ impl Coordinator {
self.fail_now(e, "task-evaluate") self.fail_now(e, "task-evaluate")
})?; })?;
self.audit.push(format!("evaluate:{k}")); 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 outcomes = evaluation.outcomes.clone();
let mut next_contexts = evaluation.next_contexts.clone(); let mut next_contexts = evaluation.next_contexts.clone();
for agent in self.agent_ids() { for agent in self.agent_ids() {

View file

@ -30,6 +30,8 @@ use flybus::{Client, ClientConfig, Router, ServiceConfig, Transport, UnixListene
use crate::agent::{AgentConfig, AgentFaults, FakeAgentWorker}; use crate::agent::{AgentConfig, AgentFaults, FakeAgentWorker};
use crate::environment::{CounterEnvironment, EnvironmentConfig, EnvironmentFaults}; 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::rpc::WorkerRef;
use crate::types::*; use crate::types::*;
use crate::worker::{StatusCell, WorkerHandle, serve}; use crate::worker::{StatusCell, WorkerHandle, serve};
@ -257,6 +259,44 @@ pub struct EnvironmentLaunch {
pub service: String, 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<String>,
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 // 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<WorkerIdentity, DomainError> {
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. /// Starts the environment, in the launcher's configured mode, and identifies it.
pub async fn launch_environment( pub async fn launch_environment(
&mut self, &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<WorkerIdentity, DomainError> {
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( async fn start_participant(
&mut self, &mut self,
identity: &WorkerIdentity, identity: &WorkerIdentity,
@ -690,11 +795,25 @@ impl Launcher {
let status = endpoint.status(); let status = endpoint.status();
(serve(client, service, 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) => { Started::Environment(spec) => {
let endpoint = CounterEnvironment::new(environment_config(spec)); let endpoint = CounterEnvironment::new(environment_config(spec));
let status = endpoint.status(); let status = endpoint.status();
(serve(client, service, 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 OMIT_AUDIO_AT_BOUNDARY: &str = "omit-audio-at-boundary";
pub const OVERLAPPING_AUDIO_AT_BOUNDARY: &str = "overlapping-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 MODE: &str = "mode";
pub const AGENTS: &str = "agents"; pub const AGENTS: &str = "agents";
pub const STEPS: &str = "steps"; pub const STEPS: &str = "steps";
@ -1281,6 +1411,8 @@ pub(crate) mod flags {
FAIL_STAGE_RESTORE, FAIL_STAGE_RESTORE,
FAIL_ACTIVATE_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. /// What only the environment is given, media options included.
pub const ENVIRONMENT_ONLY: &[&str] = &[ pub const ENVIRONMENT_ONLY: &[&str] = &[
WORKER, WORKER,
@ -1297,6 +1429,17 @@ pub(crate) mod flags {
FAIL_STAGE_RESTORE, FAIL_STAGE_RESTORE,
FAIL_ACTIVATE_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. /// What a measurement run or one of its row children is given.
pub const MEASURE: &[&str] = &[MODE, AGENTS, STEPS, WARMUP_STEPS, WORKER_THREADS, MODES]; 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)] #[derive(Clone, Debug)]
pub(crate) enum Started { pub(crate) enum Started {
Agent(AgentLaunch), Agent(AgentLaunch),
LegacyAgent(LegacyAgentLaunch),
Environment(EnvironmentLaunch), Environment(EnvironmentLaunch),
LegacyEnvironment(LegacyEnvironmentLaunch),
} }
impl Started { impl Started {
pub(crate) fn subcommand(&self) -> &'static str { pub(crate) fn subcommand(&self) -> &'static str {
match self { match self {
Started::Agent(_) => "agent", Started::Agent(_) => "agent",
Started::LegacyAgent(_) => "legacy-agent",
Started::Environment(_) => "environment", Started::Environment(_) => "environment",
Started::LegacyEnvironment(_) => "legacy-environment",
} }
} }
@ -1350,6 +1497,17 @@ impl Started {
} }
args 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) => { Started::Environment(spec) => {
let mut args = vec![ let mut args = vec![
arg(flags::SESSION, &spec.session_id), arg(flags::SESSION, &spec.session_id),
@ -1387,6 +1545,18 @@ impl Started {
} }
args 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 { pub(crate) fn environment_config(spec: &EnvironmentLaunch) -> EnvironmentConfig {
EnvironmentConfig { EnvironmentConfig {
session_id: spec.session_id.clone(), 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, /// Connects, registers and serves one participant. Used by a thread with its own runtime and,
/// through the worker subcommand, by a separate process. /// through the worker subcommand, by a separate process.
pub(crate) async fn serve_one( pub(crate) async fn serve_one(
@ -1441,9 +1637,19 @@ pub(crate) async fn serve_one(
service, service,
FakeAgentWorker::new(agent_config(spec, worker_threads)), FakeAgentWorker::new(agent_config(spec, worker_threads)),
), ),
Started::LegacyAgent(spec) => serve(
client,
service,
LegacyAgentWorker::new(legacy_agent_config(spec, worker_threads)),
),
Started::Environment(spec) => { Started::Environment(spec) => {
serve(client, service, CounterEnvironment::new(environment_config(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 /// 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 /// 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. /// 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], [flags::COMMON, flags::ENVIRONMENT_ONLY],
), ),
(Started::Agent(agent_launch()), [flags::COMMON, flags::AGENT_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(); let arguments = started.arguments();
assert!(!arguments.is_empty()); assert!(!arguments.is_empty());

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -29,6 +29,11 @@ pub mod dedup;
pub mod environment; pub mod environment;
pub mod harness; pub mod harness;
pub mod launcher; 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 measure;
pub mod media; pub mod media;
pub mod metrics; pub mod metrics;

View file

@ -208,6 +208,10 @@ pub enum Terminal {
Counter(i64), Counter(i64),
/// This many transitions were evaluated. /// This many transitions were evaluated.
AfterTransitions(u64), 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. /// 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 { let terminal = match self.terminal {
Terminal::Never => false, Terminal::Never => false,
Terminal::Counter(target) => new >= target, 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 let rollback = matches!(self.terminal, Terminal::RollbackAfterTransitions(_));
// composition that declares a rollback policy (workers-v1 section 4, 2026-09-23). // The synthetic task asks for the end of the episode; `rollback` belongs to a composition
let episode = terminal.then(|| EpisodeRequest { // that declares a rollback policy (workers-v1 section 4, 2026-09-23), and the synthetic
kind: EpisodeRequestKind::Terminal, // composition declares none, so asking for one is how a test meets the refusal.
reason: id("counter-target"), let episode = terminal.then(|| {
outcome: TypedValue::new(episode_schema(), json!({"counter": new, "transitions": self.transitions})) 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"), .expect("a synthetic typed value fits the contract"),
}
}
}); });
Ok(Evaluation { Ok(Evaluation {
outcomes, outcomes,

View file

@ -606,6 +606,13 @@ async fn execute<E: WorkerEndpoint>(
fn classify_default(method: &str) -> Option<OpClass> { fn classify_default(method: &str) -> Option<OpClass> {
match method { match method {
"Agent.Prepare" | "Agent.Commit" | "Environment.Advance" => Some(OpClass::StepMutation), "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 // `ipc-v1` section 5 retains lifecycle *and capture* replies until
// `Worker.Acknowledge`. The restore methods join them: their replies carry a // `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 // once-only token and, for an environment, the restored observation's artifact, and a

View file

@ -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<ParityRecord> {
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<ParityRecord> {
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<String> {
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<ParityRecord> {
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<fly_session::rpc::DomainReply, DomainError>) -> 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<std::path::PathBuf> {
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<String> {
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<String> {
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<String> = agent.network.rates.keys().cloned().collect();
let file = fly_session_types::fixtures::load("gameboy-rate-roles.json").expect("fixture");
let want: Vec<String> = 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<Value> {
let mut lines: Vec<Value> = 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::<Vec<_>>(),
"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::<Vec<_>>(),
"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<Value>)| {
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}");
}
}

View file

@ -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<Vec<u8>>,
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<fly_session::rpc::DomainReply, DomainError>) -> 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<u8> = (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<Vec<u8>>, 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`: `<name>.trace.jsonl` with its
/// start `<name>.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
);

View file

@ -24,6 +24,8 @@ both_transports!(
bootstrap_cannot_advance_the_world_or_produce_a_reward, bootstrap_cannot_advance_the_world_or_produce_a_reward,
the_committed_snapshot_names_the_boundary_that_just_ended, the_committed_snapshot_names_the_boundary_that_just_ended,
a_terminal_episode_pauses_at_its_own_boundary, 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, status_answers_with_the_committed_boundary,
a_worker_refuses_a_second_initialize, a_worker_refuses_a_second_initialize,
a_single_agent_composition_runs_the_same_transaction, 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; 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. /// `Worker.Status` answers with the worker's own committed boundary and progress.
async fn status_answers_with_the_committed_boundary(via: Via) { async fn status_answers_with_the_committed_boundary(via: Via) {
let mut f = default_fixture(via).await; let mut f = default_fixture(via).await;

View file

@ -15,6 +15,7 @@ ROM bytes -> Emulator::run_frame -> RGBA frame + PCM + WRAM
| Module | What it is | | Module | What it is |
| --- | --- | | --- | --- |
| `emulator` | Safe wrapper over binjgb: frames, framebuffer, buttons, WRAM, audio, save states, ROM hash | | `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` | | `adapter` | `GameAdapter`, `RewardEvent`, `ProgressSnapshot`, `MemoryReader`, `adapter_for` |
| `pokemon_red` | The `pokered-unique8-v7` reward adapter, its catalog and its generated symbol table | | `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 | | `platformer` | The `sml-progress-v1` Super Mario Land adapter, its catalog and its RAM map |

View file

@ -127,6 +127,51 @@ u8 fly_gb_read_mem(FlyGb* gb, u16 address) {
return emulator_read_mem(gb->e, 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) { u32 fly_gb_audio_frequency(FlyGb* gb) {
return emulator_get_audio_buffer(gb->e)->frequency; return emulator_get_audio_buffer(gb->e)->frequency;
} }

View file

@ -3,10 +3,9 @@
use std::ffi::c_void; use std::ffi::c_void;
use std::fmt; use std::fmt;
use sha2::{Digest, Sha256};
use crate::adapter::MemoryReader; use crate::adapter::MemoryReader;
use crate::ffi; use crate::ffi;
use crate::image::{Cartridge, MEMORY_IMAGE_LEN, MemoryImage};
/// Game Boy screen geometry, from `emulator.h`. /// Game Boy screen geometry, from `emulator.h`.
pub const SCREEN_WIDTH: usize = 160; 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. /// so there is no `NEW_FRAME` event to wait for yet.
const MAX_FRAME_ATTEMPTS: u32 = 120; 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 /// Audio frequency flysim runs the emulator at. binjgb resamples internally to
/// whatever is requested, so this is only a default. /// whatever is requested, so this is only a default.
pub const DEFAULT_AUDIO_FREQUENCY: u32 = 48_000; 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 /// 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 /// 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 /// workspace writes a ROM byte, and the bank-addressed read is the only
/// reason it is kept. /// reason it is kept. The same [`Cartridge`] an image-backed executor holds
rom: std::sync::Arc<[u8]>, /// (MEM-01), so a bank read is one rule over one set of bytes on both sides.
rom_sha256: [u8; 32], rom: Cartridge,
audio_frequency: u32, audio_frequency: u32,
/// Raw binjgb samples drained since the last [`Emulator::take_audio`]. /// Raw binjgb samples drained since the last [`Emulator::take_audio`].
pending_audio: Vec<u8>, pending_audio: Vec<u8>,
@ -178,8 +173,7 @@ impl Emulator {
debug_assert_eq!(unsafe { ffi::fly_gb_frame_buffer_size() }, FRAMEBUFFER_LEN); debug_assert_eq!(unsafe { ffi::fly_gb_frame_buffer_size() }, FRAMEBUFFER_LEN);
Ok(Self { Ok(Self {
gb, gb,
rom: rom.into(), rom: Cartridge::new(rom),
rom_sha256: Sha256::digest(rom).into(),
audio_frequency, audio_frequency,
pending_audio: Vec::new(), pending_audio: Vec::new(),
cache: FrameCache::new(), cache: FrameCache::new(),
@ -263,14 +257,45 @@ impl Emulator {
/// No bank register is written and the emulator's state does not move: this /// No bank register is written and the emulator's state does not move: this
/// is a read of bytes the process already owns. /// is a read of bytes the process already owns.
pub fn read_rom_bank(&self, bank: u8, address: u16) -> Option<u8> { pub fn read_rom_bank(&self, bank: u8, address: u16) -> Option<u8> {
let offset = match address { self.rom.read_bank(bank, address)
0x0000..=0x3fff => usize::from(address), }
0x4000..=0x7fff => {
usize::from(bank) * ROM_BANK_BYTES + usize::from(address) - ROM_BANK_BYTES /// The cartridge this emulator runs, as the executor's ROM asset holds it.
} pub fn cartridge(&self) -> Cartridge {
_ => return None, self.rom.clone()
}; }
self.rom.get(offset).copied()
/// 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. /// 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 /// SHA-256 of the ROM bytes as supplied, lowercase hex. This is the
/// `romSha256` half of the checkpoint compatibility string. /// `romSha256` half of the checkpoint compatibility string.
pub fn rom_sha256(&self) -> String { pub fn rom_sha256(&self) -> String {
let mut hex = String::with_capacity(64); self.rom.sha256_hex()
for byte in self.rom_sha256 {
use fmt::Write;
let _ = write!(hex, "{byte:02x}");
}
hex
} }
/// Emulated CPU ticks since boot. /// Emulated CPU ticks since boot.

View file

@ -38,6 +38,8 @@ unsafe extern "C" {
pub fn fly_gb_set_buttons(gb: *mut FlyGb, mask: u32); 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_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_frequency(gb: *mut FlyGb) -> u32;
pub fn fly_gb_audio_size(gb: *mut FlyGb) -> usize; pub fn fly_gb_audio_size(gb: *mut FlyGb) -> usize;

View file

@ -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<Self, ImageError> {
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<Self, ImageError> {
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<u8> {
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<u8> {
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<u8> = (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<u8> = (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 { .. })
));
}
}

View file

@ -20,6 +20,7 @@ pub mod adapter;
pub mod compatibility; pub mod compatibility;
pub mod emulator; pub mod emulator;
mod ffi; mod ffi;
pub mod image;
pub mod macros; pub mod macros;
mod ordered; mod ordered;
pub mod platformer; pub mod platformer;
@ -32,6 +33,10 @@ pub use adapter::{
adapter_for, adapter_for_with_rom_pin, adapter_for, adapter_for_with_rom_pin,
}; };
pub use compatibility::Compatibility; 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::{ pub use emulator::{
DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, FRAMEBUFFER_LEN, GbError, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, FRAMEBUFFER_LEN, GbError,
SCREEN_HEIGHT, SCREEN_WIDTH, buttons, SCREEN_HEIGHT, SCREEN_WIDTH, buttons,

View file

@ -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<Vec<u8>> {
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::<Vec<_>>()
.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<Duration>| {
samples.sort();
let at = |q: f64| samples[((samples.len() - 1) as f64 * q) as usize].as_secs_f64() * 1e6;
let mean = samples.iter().sum::<Duration>().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");
}

View file

@ -0,0 +1,27 @@
[package]
name = "flysim-store"
version.workspace = true
edition = "2024"
rust-version.workspace = true
license.workspace = true
publish = false
description = "The FLYSIM01 checkpoint store (envelope, generations, milestone archives) and the sugar journal, shared by flysim and the session runtime."
[lib]
name = "flysim_store"
path = "src/lib.rs"
# STATE-02: `flysim` (the legacy loop) and `fly-session` (the session runtime) write and read
# the same store, so the code lives here once and both link it. No dependency on either of
# them, and nothing async: the writer threads belong to the callers.
[dependencies]
flybrain-core = { path = "../flybrain-core" }
flybrain-gb = { path = "../flybrain-gb" }
anyhow = "1.0"
serde = { workspace = true }
serde_json = { workspace = true }
tracing = "0.1"
[dev-dependencies]
tempfile = "3"

View file

@ -0,0 +1,515 @@
//! The sugar journal: every admitted audience input, stamped with the frame it was applied before.
//!
//! `sugar-journal.jsonl` in `[paths] hot_dir`, one JSON object per line, append-only. It is not
//! part of a checkpoint and nothing reads it back into the fly: it is the record a shadow run
//! (the session framework's CUT-01, `docs/design/session-framework/legacy-gameboy-v1.md` section
//! 15) replays audience input from. The legacy loop applies an admitted sugar at once, in the
//! command drain at the top of a frame, so an input is fully placed by the transition it precedes:
//!
//! ```json
//! {"frame":"6465126","brainMs":108246189,"kind":"sugar","durationMs":400,"by":"viewer","source":"twitch","eventId":81234,"wallMs":1790000000000}
//! ```
//!
//! - `frame` is the frame counter when the input was applied, which is the `step` of the next
//! transition in the frame trace (`crate::trace`): replay applies it before that transition's
//! ticks. A restore carries the frame counter, so stamps continue across restarts.
//! - `kind` is `sugar` (a `reward-pulse` stimulation of `durationMs`, after the admission rules
//! and the clamp) or `reward` (an operator's `POST /reward`, one reinforcement of `value`).
//! - `brainMs` cross-checks the stamp; `eventId` joins the event log; `wallMs` is for people.
//!
//! Refused requests are not journalled: admission is wall-clock policy, and a replay applies what
//! was admitted. A write that fails is a warning, never a refusal: the input has already reached
//! the fly.
//!
//! **Boot header, rotation and reset (STATE-02, before SHADOW-01).** Three things a replay needs
//! that the first version left open:
//!
//! - *Boot header.* Every process writes one header line when it starts, before any input:
//!
//! ```json
//! {"journal":"flysim-sugar-journal-v1","boot":{"runtime":"flysim","startFrame":"6465126","brainMs":108246189,"origin":"hot latest generation 230739","generation":230739,"compatibility":"…","wallMs":1790000000000}}
//! ```
//!
//! A restore splits a run into processes, and a restored process starts from a checkpoint that
//! can be older than the last input the previous process journalled (a hot copy is up to five
//! seconds old, a milestone reset much more). The header is where a reader cuts the journal
//! into per-process segments ([`read_segments`]) and learns which checkpoint each one replays
//! from. It has no `frame` member, so [`read`], which keeps input lines only, skips it.
//! - *Rotation.* The journal lives on tmpfs. When the next line would take it past
//! [`MAX_BYTES`], the file becomes `sugar-journal-1.jsonl` (older ones shift up, the oldest
//! beyond [`KEEP_ROTATIONS`] is removed) and a fresh file starts with a `continues` line that
//! repeats the boot header, so every file can be read on its own.
//! - *Reset.* [`clear`] removes the journal and its rotations. `flysim --reset-to-milestone`
//! calls it (after copying the stores aside), because a reset rewinds the frame counter to the
//! rung's: inputs stamped with the abandoned run's frames would otherwise sit in front of the
//! new run's and read as if they were in its future.
use std::fs::{File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
/// The journal's file name inside the hot directory.
pub const FILE_NAME: &str = "sugar-journal.jsonl";
/// The format name in every header line.
pub const FORMAT: &str = "flysim-sugar-journal-v1";
/// The size a journal file may reach before it is rotated. Sugar is rate-limited per minute, so
/// this is days of input; the bound exists because the hot directory is tmpfs.
pub const MAX_BYTES: u64 = 4 << 20;
/// Rotated files kept beside the live one: `sugar-journal-1.jsonl` (newest) and up.
pub const KEEP_ROTATIONS: usize = 3;
/// What was applied.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Input {
Sugar { duration_ms: f64 },
Reward { value: f64 },
}
/// One journal line.
#[derive(Debug, Clone, PartialEq)]
pub struct Entry<'a> {
pub frame: u64,
pub brain_ms: f64,
pub input: Input,
pub by: &'a str,
pub source: &'a str,
pub event_id: u64,
pub wall_ms: u64,
}
impl Entry<'_> {
pub fn to_json(&self) -> Value {
let mut line = json!({ "frame": self.frame.to_string(), "brainMs": self.brain_ms });
let map = line.as_object_mut().expect("an object");
match self.input {
Input::Sugar { duration_ms } => {
map.insert("kind".into(), "sugar".into());
map.insert("durationMs".into(), json!(duration_ms));
}
Input::Reward { value } => {
map.insert("kind".into(), "reward".into());
map.insert("value".into(), json!(value));
}
}
map.insert("by".into(), self.by.into());
map.insert("source".into(), self.source.into());
map.insert("eventId".into(), self.event_id.into());
map.insert("wallMs".into(), self.wall_ms.into());
line
}
}
/// The header a process writes when it starts: where its inputs begin.
#[derive(Debug, Clone, PartialEq)]
pub struct BootHeader {
/// `flysim` for the legacy loop, `fly-session` for the session runtime.
pub runtime: String,
/// The frame counter the process starts at: its first input can be stamped no earlier.
pub start_frame: u64,
pub brain_ms: f64,
/// `fresh start`, or the restore candidate's origin (`hot latest generation 7`, ...).
pub origin: String,
/// The generation restored from, if the candidate names one.
pub generation: Option<u64>,
pub compatibility: String,
pub wall_ms: u64,
}
impl BootHeader {
pub fn to_json(&self) -> Value {
json!({
"runtime": self.runtime,
"startFrame": self.start_frame.to_string(),
"brainMs": self.brain_ms,
"origin": self.origin,
"generation": self.generation,
"compatibility": self.compatibility,
"wallMs": self.wall_ms,
})
}
}
/// The append-only journal, rotated at [`MAX_BYTES`].
pub struct SugarJournal {
dir: PathBuf,
path: PathBuf,
file: Option<File>,
/// Bytes in the live file, as far as this process knows.
bytes: u64,
max_bytes: u64,
keep: usize,
/// The boot header this process wrote, repeated at the top of every rotated-in file.
boot: Option<Value>,
}
impl SugarJournal {
pub fn new(hot_dir: &Path) -> Self {
Self::with_limits(hot_dir, MAX_BYTES, KEEP_ROTATIONS)
}
pub fn with_limits(hot_dir: &Path, max_bytes: u64, keep: usize) -> Self {
Self {
dir: hot_dir.to_path_buf(),
path: hot_dir.join(FILE_NAME),
file: None,
bytes: 0,
max_bytes: max_bytes.max(1),
keep,
boot: None,
}
}
pub fn path(&self) -> &Path {
&self.path
}
/// Write this process's boot header. Called once, when the process knows where it starts
/// (after its restore or its warm-up) and before it admits anything.
pub fn boot(&mut self, header: &BootHeader) {
let boot = header.to_json();
self.append(&json!({ "journal": FORMAT, "boot": boot.clone() }));
// Set after the line is written: a rotation that line itself triggers must not open
// the new file with a `continues` naming a boot that is not in the journal yet.
self.boot = Some(boot);
}
/// Append one input line.
pub fn record(&mut self, entry: &Entry<'_>) {
self.append(&entry.to_json());
}
/// One line, one `write` of the whole line, so a crash leaves at most a torn last line,
/// which a reader skips and the next open terminates.
fn append(&mut self, value: &Value) {
let mut line = value.to_string();
line.push('\n');
if self.file.is_none() && !self.open() {
return;
}
if self.bytes > 0 && self.bytes + line.len() as u64 > self.max_bytes {
self.rotate();
if !self.open() {
return;
}
}
if let Some(file) = self.file.as_mut() {
match file.write_all(line.as_bytes()) {
Ok(()) => self.bytes += line.len() as u64,
Err(error) => {
tracing::warn!(%error, path = %self.path.display(), "could not append to the sugar journal");
// Reopen on the next input rather than write through a broken handle.
self.file = None;
}
}
}
}
/// Open the live file for appending. One whose last line is torn gets its newline, so the
/// next line is whole; one already at the limit is rotated by the caller's next append.
fn open(&mut self) -> bool {
let file = OpenOptions::new().create(true).read(true).append(true).open(&self.path);
let mut file = match file {
Ok(file) => file,
Err(error) => {
tracing::warn!(%error, path = %self.path.display(), "could not open the sugar journal");
return false;
}
};
let mut length = file.metadata().map(|m| m.len()).unwrap_or(0);
if length > 0 && !ends_with_newline(&mut file, length) && file.write_all(b"\n").is_ok() {
length += 1;
}
self.bytes = length;
let fresh = length == 0;
self.file = Some(file);
if fresh && let Some(boot) = self.boot.clone() {
// A file this process starts after a rotation says whose inputs follow.
self.append(&json!({ "journal": FORMAT, "continues": boot }));
}
true
}
fn rotate(&mut self) {
self.file = None;
self.shift_rotations();
}
/// `sugar-journal.jsonl` -> `-1`, `-1` -> `-2`, ..., dropping what falls past `keep`.
fn shift_rotations(&mut self) {
if self.keep == 0 {
let _ = std::fs::remove_file(&self.path);
return;
}
let _ = std::fs::remove_file(rotation_path(&self.dir, self.keep));
for index in (1..self.keep).rev() {
let from = rotation_path(&self.dir, index);
if from.exists() {
let _ = std::fs::rename(&from, rotation_path(&self.dir, index + 1));
}
}
if let Err(error) = std::fs::rename(&self.path, rotation_path(&self.dir, 1)) {
tracing::warn!(%error, path = %self.path.display(), "could not rotate the sugar journal");
}
}
}
fn ends_with_newline(file: &mut File, length: u64) -> bool {
let mut last = [0u8; 1];
file.seek(SeekFrom::Start(length - 1))
.and_then(|_| file.read_exact(&mut last))
.map(|()| last[0] == b'\n')
.unwrap_or(true)
}
/// `sugar-journal-<index>.jsonl`: index 1 is the newest rotation.
pub fn rotation_path(hot_dir: &Path, index: usize) -> PathBuf {
hot_dir.join(format!("sugar-journal-{index}.jsonl"))
}
/// Is `name` the journal or one of its rotations?
pub fn is_journal_file(name: &str) -> bool {
name == FILE_NAME
|| name
.strip_prefix("sugar-journal-")
.and_then(|rest| rest.strip_suffix(".jsonl"))
.is_some_and(|index| !index.is_empty() && index.bytes().all(|b| b.is_ascii_digit()))
}
/// Remove the journal and every rotation from `hot_dir`: a reset starts a new record. Returns
/// how many files went. A missing directory is zero files.
pub fn clear(hot_dir: &Path) -> std::io::Result<usize> {
if !hot_dir.is_dir() {
return Ok(0);
}
let mut removed = 0;
for entry in std::fs::read_dir(hot_dir)?.flatten() {
if is_journal_file(&entry.file_name().to_string_lossy()) {
std::fs::remove_file(entry.path())?;
removed += 1;
}
}
Ok(removed)
}
/// Read a journal back: every whole input line, in order. A torn or unreadable line is skipped,
/// and so is every header.
pub fn read(path: &Path) -> std::io::Result<Vec<Value>> {
let text = std::fs::read_to_string(path)?;
Ok(text
.lines()
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
.filter(|value| value.get("frame").is_some())
.collect())
}
/// One process's inputs: its boot header (absent for lines written before headers existed) and
/// the inputs it admitted, in order.
#[derive(Debug, Clone, PartialEq)]
pub struct Segment {
pub boot: Option<Value>,
pub inputs: Vec<Value>,
}
/// The whole journal of `hot_dir`, oldest rotation first, cut into per-process segments at each
/// boot header. A `continues` line keeps the segment it names open across a rotation.
pub fn read_segments(hot_dir: &Path) -> std::io::Result<Vec<Segment>> {
let mut files: Vec<(usize, PathBuf)> = Vec::new();
if hot_dir.is_dir() {
for entry in std::fs::read_dir(hot_dir)?.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if let Some(index) = name
.strip_prefix("sugar-journal-")
.and_then(|rest| rest.strip_suffix(".jsonl"))
.and_then(|index| index.parse::<usize>().ok())
{
files.push((index, entry.path()));
}
}
}
files.sort_by(|a, b| b.0.cmp(&a.0));
let live = hot_dir.join(FILE_NAME);
if live.exists() {
files.push((0, live));
}
let mut segments: Vec<Segment> = Vec::new();
for (_, path) in files {
let text = std::fs::read_to_string(&path)?;
for value in text.lines().filter_map(|line| serde_json::from_str::<Value>(line).ok()) {
if let Some(boot) = value.get("boot") {
segments.push(Segment { boot: Some(boot.clone()), inputs: Vec::new() });
} else if let Some(boot) = value.get("continues") {
let open = segments.last().is_some_and(|s| s.boot.as_ref() == Some(boot));
if !open {
segments.push(Segment { boot: Some(boot.clone()), inputs: Vec::new() });
}
} else if value.get("frame").is_some() {
if segments.is_empty() {
segments.push(Segment { boot: None, inputs: Vec::new() });
}
segments.last_mut().expect("a segment").inputs.push(value);
}
}
}
Ok(segments)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn inputs_are_appended_with_their_frame_and_survive_a_reopen() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut journal = SugarJournal::new(dir.path());
assert!(
!journal.path().exists(),
"nothing is written before an input"
);
let sugar = Entry {
frame: 42,
brain_ms: 703.0,
input: Input::Sugar { duration_ms: 400.0 },
by: "viewer",
source: "test",
event_id: 7,
wall_ms: 1,
};
journal.record(&sugar);
drop(journal);
let mut journal = SugarJournal::new(dir.path());
journal.record(&Entry {
frame: 43,
input: Input::Reward { value: 0.5 },
event_id: 8,
..sugar
});
// A torn tail from a crash is skipped, not fatal.
std::fs::OpenOptions::new()
.append(true)
.open(journal.path())
.and_then(|mut file| file.write_all(b"{\"frame\":\"44\",\"kin"))
.expect("appending a torn line");
let lines = read(journal.path()).expect("the journal reads back");
assert_eq!(lines.len(), 2);
assert_eq!(lines[0]["frame"], "42");
assert_eq!(lines[0]["kind"], "sugar");
assert_eq!(lines[0]["durationMs"], 400.0);
assert_eq!(lines[1]["frame"], "43");
assert_eq!(lines[1]["kind"], "reward");
assert_eq!(lines[1]["value"], 0.5);
assert_eq!(lines[1]["eventId"], 8);
}
fn header(frame: u64, origin: &str) -> BootHeader {
BootHeader {
runtime: "flysim".to_string(),
start_frame: frame,
brain_ms: frame as f64 * 16.74,
origin: origin.to_string(),
generation: Some(frame),
compatibility: "kernel/adapter/fingerprint".to_string(),
wall_ms: 1,
}
}
fn sugar(frame: u64, event_id: u64) -> Entry<'static> {
Entry {
frame,
brain_ms: frame as f64,
input: Input::Sugar { duration_ms: 300.0 },
by: "viewer",
source: "test",
event_id,
wall_ms: 1,
}
}
#[test]
fn each_process_writes_a_boot_header_that_cuts_the_journal_into_segments() {
let dir = tempfile::tempdir().unwrap();
let mut journal = SugarJournal::new(dir.path());
journal.boot(&header(100, "fresh start"));
journal.record(&sugar(120, 1));
journal.record(&sugar(130, 2));
drop(journal);
// A crash tore the last line; the next process terminates it before its header.
std::fs::OpenOptions::new()
.append(true)
.open(dir.path().join(FILE_NAME))
.and_then(|mut file| file.write_all(b"{\"frame\":\"13"))
.unwrap();
// The restart restored an older hot copy: its inputs start below the torn one's frame.
let mut journal = SugarJournal::new(dir.path());
journal.boot(&header(125, "hot latest generation 125"));
journal.record(&sugar(126, 3));
let segments = read_segments(dir.path()).unwrap();
assert_eq!(segments.len(), 2);
assert_eq!(segments[0].boot.as_ref().unwrap()["origin"], "fresh start");
assert_eq!(segments[0].inputs.len(), 2);
assert_eq!(segments[1].boot.as_ref().unwrap()["startFrame"], "125");
assert_eq!(segments[1].boot.as_ref().unwrap()["generation"], 125);
assert_eq!(segments[1].inputs.len(), 1);
assert_eq!(segments[1].inputs[0]["frame"], "126");
// The input-only reader skips headers and the torn line, as before.
let inputs = read(journal.path()).unwrap();
assert_eq!(inputs.len(), 3);
}
#[test]
fn the_journal_rotates_at_its_limit_and_keeps_a_bounded_number_of_files() {
let dir = tempfile::tempdir().unwrap();
let mut journal = SugarJournal::with_limits(dir.path(), 600, 2);
journal.boot(&header(1, "fresh start"));
for event in 0..40 {
journal.record(&sugar(10 + event, event));
}
for path in [dir.path().join(FILE_NAME), rotation_path(dir.path(), 1), rotation_path(dir.path(), 2)] {
let length = std::fs::metadata(&path).unwrap().len();
assert!(length <= 600, "{} is {length} bytes", path.display());
}
assert!(!rotation_path(dir.path(), 3).exists(), "only two rotations are kept");
// Every file says whose inputs it holds, and the segments join across the rotations.
let live = std::fs::read_to_string(dir.path().join(FILE_NAME)).unwrap();
let first: Value = serde_json::from_str(live.lines().next().unwrap()).unwrap();
assert_eq!(first["journal"], FORMAT);
assert_eq!(first["continues"]["origin"], "fresh start", "{live}");
let segments = read_segments(dir.path()).unwrap();
assert_eq!(segments.len(), 1, "one process, one segment: {segments:?}");
let frames: Vec<u64> = segments[0]
.inputs
.iter()
.map(|v| v["frame"].as_str().unwrap().parse().unwrap())
.collect();
assert!(frames.windows(2).all(|w| w[1] == w[0] + 1), "in order, no gap inside the kept files");
assert_eq!(*frames.last().unwrap(), 49);
}
#[test]
fn clear_removes_the_journal_and_its_rotations_and_nothing_else() {
let dir = tempfile::tempdir().unwrap();
let mut journal = SugarJournal::with_limits(dir.path(), 300, 3);
journal.boot(&header(1, "fresh start"));
for event in 0..10 {
journal.record(&sugar(10 + event, event));
}
std::fs::write(dir.path().join("manifest.json"), "{}").unwrap();
std::fs::write(dir.path().join("sugar-journal-x.jsonl"), "").unwrap();
let removed = clear(dir.path()).unwrap();
assert!(removed >= 2, "{removed}");
let left: Vec<String> = std::fs::read_dir(dir.path())
.unwrap()
.flatten()
.map(|e| e.file_name().to_string_lossy().to_string())
.collect();
let mut left = left;
left.sort();
assert_eq!(left, vec!["manifest.json", "sugar-journal-x.jsonl"]);
assert_eq!(clear(&dir.path().join("missing")).unwrap(), 0);
assert!(read_segments(dir.path()).unwrap().is_empty());
}
}

View file

@ -0,0 +1,12 @@
//! The `FLYSIM01` checkpoint store and the sugar journal.
//!
//! `FLYSIM01` is the checkpoint format of record for the legacy Game Boy composition until
//! RETIRE-01 (`docs/design/session-framework/legacy-gameboy-v1.md` section 16). Two runtimes write
//! and read it: the legacy loop (`flysim`) and the session runtime (`fly-session`, STATE-02). This
//! crate is the one copy of the code both use, moved here unchanged from `flysim::store` and
//! `flysim::journal`, which re-export it, so a store written by either is the other's store: the
//! same envelope bytes, the same generations and `manifest.json`, the same milestone archives and
//! rotation, and the same restore order.
pub mod journal;
pub mod store;

View file

@ -0,0 +1,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 `<gen>.checkpoint.tmp`, fsyncs it, renames it, fsyncs the directory, and
//! then does the same for `manifest.json`. **The manifest rename is the commit point**: a
//! crash before it leaves an unreferenced file that is never loaded;
//! - durable commits go to `save_dir` every `checkpoint_seconds` (default 300) and on every
//! event that matters; a hot copy goes to `hot_dir` (tmpfs) every `hot_seconds` (default 5);
//! - the first commit at a new best rank also writes `milestone-<rank>.checkpoint`, which later
//! rotations never unlink.
use std::collections::BTreeMap;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use flybrain_core::envelope::{EnvelopeParts, decode_envelope, encode_envelope};
use flybrain_core::json::JsonValue;
use serde::{Deserialize, Serialize};
/// Envelope magic. Chunk names stay `[a-zA-Z]+` so the TypeScript `decodeEnvelope` can read a
/// flysim checkpoint for recap and inspection tooling.
pub const MAGIC: &str = "FLYSIM01";
/// Chunk names flysim adds to `flybrain-core`'s `AGENT_CHUNK_NAMES`.
pub const EMULATOR_CHUNK: &str = "emulator";
pub const FRAMEBUFFER_CHUNK: &str = "framebuffer";
pub const RATCHET_GAME_CHUNK: &str = "ratchetGame";
pub const RATCHET_FRAME_CHUNK: &str = "ratchetFrame";
/// `manifest.json`: which generations are current, and which are archived forever.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct StoreManifest {
/// Highest generation ever allocated in this store.
pub generation: u64,
/// The generation to restore first.
pub latest: Option<u64>,
/// The generation to restore if `latest` will not load.
pub previous: Option<u64>,
/// Best-rank archives, rank to generation. Their files are never rotated away.
pub archives: BTreeMap<u32, u64>,
}
impl StoreManifest {
fn record(&mut self, generation: u64, archive_rank: Option<u32>) {
self.generation = self.generation.max(generation);
if self.latest != Some(generation) {
self.previous = self.latest;
self.latest = Some(generation);
}
if let Some(rank) = archive_rank {
self.archives.insert(rank, generation);
}
}
/// Generations that must survive rotation.
fn referenced(&self) -> Vec<u64> {
let mut out: Vec<u64> = self.latest.into_iter().chain(self.previous).collect();
out.extend(self.archives.values().copied());
out
}
}
/// One restore candidate, in the order it should be tried.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Candidate {
pub path: PathBuf,
/// Human description for the log and for `/status`'s fallback reporting.
pub origin: String,
pub generation: Option<u64>,
}
/// A checkpoint directory: `<gen>.checkpoint`, `milestone-<rank>.checkpoint`, `manifest.json`.
#[derive(Debug, Clone)]
pub struct Store {
dir: PathBuf,
keep_generations: usize,
}
impl Store {
pub fn new(dir: impl Into<PathBuf>, keep_generations: usize) -> Self {
Self { dir: dir.into(), keep_generations: keep_generations.max(1) }
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn create(&self) -> Result<()> {
std::fs::create_dir_all(&self.dir)
.with_context(|| format!("creating checkpoint directory {}", self.dir.display()))
}
pub fn manifest_path(&self) -> PathBuf {
self.dir.join("manifest.json")
}
pub fn generation_path(&self, generation: u64) -> PathBuf {
self.dir.join(format!("{generation}.checkpoint"))
}
pub fn archive_path(&self, rank: u32) -> PathBuf {
self.dir.join(format!("milestone-{rank}.checkpoint"))
}
/// Read `manifest.json`, or `None` when it is absent or unreadable.
pub fn manifest(&self) -> Option<StoreManifest> {
let text = std::fs::read_to_string(self.manifest_path()).ok()?;
match serde_json::from_str(&text) {
Ok(manifest) => Some(manifest),
Err(error) => {
tracing::warn!(%error, path = %self.manifest_path().display(), "unreadable store manifest");
None
}
}
}
/// Highest generation the store has ever allocated, from the manifest and from the files on
/// disk (an unreferenced file from a crashed commit still counts, so a generation number is
/// never reused).
pub fn highest_generation(&self) -> u64 {
let mut highest = self.manifest().map_or(0, |manifest| manifest.generation);
if let Ok(entries) = std::fs::read_dir(&self.dir) {
for entry in entries.flatten() {
if let Some(generation) = parse_generation(&entry.file_name().to_string_lossy()) {
highest = highest.max(generation);
}
}
}
highest
}
/// Restore candidates from this store, in order: latest, previous, then the archives by
/// descending rank.
pub fn candidates(&self, label: &str) -> Vec<Candidate> {
let Some(manifest) = self.manifest() else {
return Vec::new();
};
let mut out = Vec::new();
for (kind, generation) in [("latest", manifest.latest), ("previous", manifest.previous)] {
if let Some(generation) = generation {
out.push(Candidate {
path: self.generation_path(generation),
origin: format!("{label} {kind} generation {generation}"),
generation: Some(generation),
});
}
}
for (rank, generation) in manifest.archives.iter().rev() {
out.push(Candidate {
path: self.generation_path(*generation),
origin: format!("{label} archived generation {generation} (rank {rank})"),
generation: Some(*generation),
});
out.push(Candidate {
path: self.archive_path(*rank),
origin: format!("{label} milestone archive rank {rank}"),
generation: Some(*generation),
});
}
out.retain(|candidate| candidate.path.exists());
out
}
/// Write `bytes` as `generation`, commit it, archive it if `archive_rank` is set, then rotate.
///
/// The sequence is exactly section 8's: payload tmp, fsync, rename, dir fsync, then manifest
/// tmp, fsync, rename, dir fsync.
pub fn commit(
&self,
generation: u64,
bytes: &[u8],
archive_rank: Option<u32>,
) -> Result<StoreManifest> {
self.create()?;
write_atomic(&self.generation_path(generation), bytes)?;
if let Some(rank) = archive_rank {
write_atomic(&self.archive_path(rank), bytes)?;
}
let mut manifest = self.manifest().unwrap_or_default();
manifest.record(generation, archive_rank);
let text = serde_json::to_vec_pretty(&manifest)?;
write_atomic(&self.manifest_path(), &text)?;
self.rotate(&manifest)?;
Ok(manifest)
}
/// Stage a payload without committing it. Only the crash-simulation test uses this: it is
/// the state a `kill -9` between the tmp write and the rename leaves behind.
pub fn stage_for_test(&self, generation: u64, bytes: &[u8]) -> Result<PathBuf> {
self.create()?;
let path = tmp_path(&self.generation_path(generation));
write_and_sync(&path, bytes)?;
Ok(path)
}
/// Remove generation files that the manifest no longer references, keeping the newest
/// `keep_generations` and never touching an archive.
fn rotate(&self, manifest: &StoreManifest) -> Result<()> {
let referenced = manifest.referenced();
let mut generations: Vec<u64> = Vec::new();
for entry in std::fs::read_dir(&self.dir)?.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if let Some(generation) = parse_generation(&name) {
generations.push(generation);
} else if name.ends_with(".checkpoint.tmp") {
// A tmp file from an interrupted commit is never loadable; clean it up.
let _ = std::fs::remove_file(entry.path());
}
}
generations.sort_unstable_by(|a, b| b.cmp(a));
for (index, generation) in generations.iter().enumerate() {
if referenced.contains(generation) || index < self.keep_generations {
continue;
}
let path = self.generation_path(*generation);
if let Err(error) = std::fs::remove_file(&path) {
tracing::warn!(%error, path = %path.display(), "could not rotate a checkpoint");
}
}
Ok(())
}
}
/// `milestone-<rank>.checkpoint` is an independent file, so it is not a generation.
fn parse_generation(name: &str) -> Option<u64> {
name.strip_suffix(".checkpoint")?.parse().ok()
}
fn tmp_path(path: &Path) -> PathBuf {
let mut name = path.as_os_str().to_os_string();
name.push(".tmp");
PathBuf::from(name)
}
/// tmp write, fsync, rename, directory fsync.
pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
let tmp = tmp_path(path);
write_and_sync(&tmp, bytes)?;
std::fs::rename(&tmp, path)
.with_context(|| format!("renaming {} to {}", tmp.display(), path.display()))?;
sync_dir(path.parent().unwrap_or(Path::new(".")))
}
fn write_and_sync(path: &Path, bytes: &[u8]) -> Result<()> {
let mut file = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(path)
.with_context(|| format!("creating {}", path.display()))?;
file.write_all(bytes)?;
file.flush()?;
file.sync_all().with_context(|| format!("fsync {}", path.display()))?;
Ok(())
}
fn sync_dir(dir: &Path) -> Result<()> {
// Opening a directory read-only and fsyncing it is what makes the rename durable.
File::open(dir)
.and_then(|file| file.sync_all())
.with_context(|| format!("fsync directory {}", dir.display()))
}
// ---------------------------------------------------------------------------------------------
// The envelope
// ---------------------------------------------------------------------------------------------
/// Everything a checkpoint carries besides the agent's own chunks.
#[derive(Debug, Clone, PartialEq)]
pub struct RuntimeState {
pub generation: u64,
pub wall_ms: u64,
pub rom_sha256: String,
pub emulator_frame: u64,
pub compatibility: String,
pub speed: f64,
pub buttons: u32,
/// Simulated milliseconds at which the current milestone rank was reached.
pub rank_since_ms: f64,
pub last_event_id: u64,
/// The adapter's own lifetime reward state.
pub reward: serde_json::Value,
pub ratchet: flybrain_gb::RatchetState,
/// 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<u64>,
pub emulator: Vec<u8>,
pub framebuffer: Vec<u8>,
/// The ratchet's best safe snapshot, if it has one.
pub ratchet_game: Vec<u8>,
pub ratchet_frame: Vec<u8>,
}
/// A decoded checkpoint: the agent half plus the runtime half.
#[derive(Debug, Clone)]
pub struct Checkpoint {
pub agent: flybrain_core::agent::AgentState,
pub runtime: RuntimeState,
}
/// Encode an agent state plus the runtime state into one `FLYSIM01` envelope.
pub fn encode(
agent: &flybrain_core::agent::AgentState,
runtime: &RuntimeState,
) -> Result<Vec<u8>> {
let parts = flybrain_core::envelope::agent_to_chunks(agent);
let mut manifest = parts.manifest;
manifest.set("generation", (runtime.generation as f64).into());
manifest.set("wallMs", (runtime.wall_ms as f64).into());
manifest.set("romHash", runtime.rom_sha256.as_str().into());
manifest.set("emulatorFrame", (runtime.emulator_frame as f64).into());
manifest.set("compatibility", runtime.compatibility.as_str().into());
manifest.set("speed", runtime.speed.into());
manifest.set("buttons", f64::from(runtime.buttons).into());
manifest.set("rankSinceMs", runtime.rank_since_ms.into());
manifest.set("lastEventId", (runtime.last_event_id as f64).into());
manifest.set("reward", to_json_value(&runtime.reward)?);
manifest.set("ratchet", to_json_value(&serde_json::to_value(runtime.ratchet)?)?);
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<Checkpoint> {
let parts: EnvelopeParts =
decode_envelope(bytes, MAGIC).map_err(|error| anyhow::anyhow!("{error}"))?;
let manifest = parts.manifest.clone();
let agent = flybrain_core::envelope::agent_from_chunks(&manifest, &parts)
.map_err(|error| anyhow::anyhow!("{error}"))?;
let string = |key: &str| -> Result<String> {
manifest
.get(key)
.and_then(JsonValue::as_str)
.map(str::to_string)
.ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}"))
};
let number = |key: &str| -> Result<f64> {
manifest
.get(key)
.and_then(JsonValue::as_f64)
.ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}"))
};
let chunk = |name: &str| -> Result<Vec<u8>> {
parts
.chunk(name)
.map(<[u8]>::to_vec)
.ok_or_else(|| anyhow::anyhow!("checkpoint is missing the {name} chunk"))
};
let ratchet_json = manifest
.get("ratchet")
.ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing ratchet"))?;
let ratchet: flybrain_gb::RatchetState = serde_json::from_str(&ratchet_json.stringify())
.context("checkpoint ratchet state is not readable")?;
let reward = manifest
.get("reward")
.map(|value| serde_json::from_str(&value.stringify()))
.transpose()
.context("checkpoint reward state is not readable")?
.unwrap_or(serde_json::Value::Null);
Ok(Checkpoint {
agent,
runtime: RuntimeState {
generation: number("generation")? as u64,
wall_ms: number("wallMs")? as u64,
rom_sha256: string("romHash")?,
emulator_frame: number("emulatorFrame")? as u64,
compatibility: string("compatibility")?,
speed: number("speed")?,
buttons: number("buttons")? as u32,
rank_since_ms: number("rankSinceMs").unwrap_or(0.0),
last_event_id: number("lastEventId").unwrap_or(0.0) as u64,
reward,
ratchet,
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<Checkpoint> {
let bytes =
std::fs::read(path).with_context(|| format!("reading checkpoint {}", path.display()))?;
decode(&bytes).with_context(|| format!("decoding checkpoint {}", path.display()))
}
fn to_json_value(value: &serde_json::Value) -> Result<JsonValue> {
JsonValue::parse(&serde_json::to_string(value)?).map_err(|error| anyhow::anyhow!("{error}"))
}
/// The restore order: the tmpfs hot copy first, then the durable store.
///
/// The hot copy is written every few seconds and the durable one every few minutes, so the hot
/// copy is normally the newest state that exists; it is a first-class candidate because it uses
/// the identical envelope and the identical atomic sequence, and not a partial dump.
/// The compatibility string the newest decodable checkpoint in `dir` carries, if any.
///
/// The store's own `manifest.json` is only an index (generation, latest, previous, archives) —
/// the compatibility string lives in each checkpoint's own `FLYSIM01` envelope manifest, so
/// answering "what will this build refuse?" means decoding a checkpoint. Candidates are tried
/// newest first and a corrupt one is skipped, which is the same order and the same tolerance
/// `Sim::boot` restores with.
///
/// `flysim --print-state-compatibility DIR` is this, and `infra/05-deploy.sh` compares its
/// answer with `--print-compatibility` before flipping the `current` symlink.
pub fn state_compatibility(dir: &Path) -> Option<String> {
let store = Store::new(dir, 8);
for candidate in store.candidates("durable") {
if let Ok(checkpoint) = load(&candidate.path) {
return Some(checkpoint.runtime.compatibility);
}
}
None
}
pub fn restore_order(hot: &Store, durable: &Store) -> Vec<Candidate> {
let mut out = hot.candidates("hot");
out.extend(durable.candidates("durable"));
out
}
#[cfg(test)]
mod tests {
use super::*;
fn runtime(generation: u64) -> RuntimeState {
RuntimeState {
generation,
wall_ms: 1_700_000_000_000,
rom_sha256: "ab".repeat(32),
emulator_frame: 12_345,
compatibility: "kernel/adapter/fingerprint".to_string(),
speed: 1.0,
buttons: 0b0001_0000,
rank_since_ms: 4_242.0,
last_event_id: 77,
reward: serde_json::json!({ "version": 3, "total": 1.25 }),
ratchet: flybrain_gb::RatchetState { best: 3, ..Default::default() },
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<String> =
restore_order(&hot, &durable).into_iter().map(|c| c.origin).collect();
assert_eq!(
order,
vec![
"hot latest generation 7",
"durable latest generation 3",
"durable previous generation 2",
"durable archived generation 2 (rank 4)",
"durable milestone archive rank 4",
"durable archived generation 1 (rank 1)",
"durable milestone archive rank 1",
]
);
}
#[test]
fn rotation_keeps_the_referenced_generations_and_never_unlinks_an_archive() {
let dir = tempfile::tempdir().unwrap();
let store = Store::new(dir.path(), 2);
let bytes = encode(&agent_state(), &runtime(1)).unwrap();
store.commit(1, &bytes, Some(2)).unwrap();
for generation in 2..=6 {
store.commit(generation, &bytes, None).unwrap();
}
assert!(store.generation_path(6).exists(), "latest");
assert!(store.generation_path(5).exists(), "previous");
assert!(store.generation_path(1).exists(), "archived generation");
assert!(store.archive_path(2).exists(), "milestone archive");
assert!(!store.generation_path(3).exists(), "rotated away");
assert!(!store.generation_path(4).exists(), "rotated away");
}
#[test]
fn an_empty_or_manifestless_directory_offers_no_candidates() {
let dir = tempfile::tempdir().unwrap();
let store = Store::new(dir.path().join("missing"), 2);
assert!(store.candidates("durable").is_empty());
assert_eq!(store.highest_generation(), 0);
let store = Store::new(dir.path(), 2);
store.create().unwrap();
std::fs::write(store.manifest_path(), "{ not json").unwrap();
assert!(store.candidates("durable").is_empty(), "an unreadable manifest is not fatal");
}
}

View file

@ -31,6 +31,8 @@ cuda = ["flybrain-core/cuda"]
flybrain-core = { path = "../flybrain-core" } flybrain-core = { path = "../flybrain-core" }
flybrain-gb = { path = "../flybrain-gb" } flybrain-gb = { path = "../flybrain-gb" }
flybus = { path = "../flybus" } flybus = { path = "../flybus" }
# The FLYSIM01 store and the sugar journal, shared with the session runtime (STATE-02).
flysim-store = { path = "../flysim-store" }
anyhow = "1.0" anyhow = "1.0"
axum = { version = "0.8", features = ["ws"] } axum = { version = "0.8", features = ["ws"] }
@ -55,6 +57,9 @@ unicode-normalization = "0.1"
# The legacy profile's pinned identities (`tests/legacy_profile_identity.rs`): test-only, so the # The legacy profile's pinned identities (`tests/legacy_profile_identity.rs`): test-only, so the
# service itself does not link the session types. # service itself does not link the session types.
fly-session-types = { path = "../fly-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" futures-util = "0.3"
# `default-features = false` drops the remote-reference resolver (and with it reqwest and a # `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. # TLS stack): `packages/feed/src/schema.json` is self-contained, so nothing has to be fetched.

View file

@ -198,6 +198,11 @@ pub struct LegacyFrame {
pub location: Option<(u32, u32, u32)>, pub location: Option<(u32, u32, u32)>,
pub held_channel: Option<String>, pub held_channel: Option<String>,
pub blocked_since_ms: f64, 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<FrameTrace>, trace: Option<FrameTrace>,
} }
@ -219,6 +224,7 @@ impl LegacyFrame {
location: None, location: None,
held_channel: None, held_channel: None,
blocked_since_ms: 0.0, blocked_since_ms: 0.0,
reinforcements: 0,
trace: None, trace: None,
} }
} }
@ -248,6 +254,7 @@ impl LegacyFrame {
.map_err(|error| anyhow!("running the first frame: {error}"))?; .map_err(|error| anyhow!("running the first frame: {error}"))?;
self.frame_buffer.copy_from_slice(emulator.framebuffer()); self.frame_buffer.copy_from_slice(emulator.framebuffer());
self.frame_counter = 1; self.frame_counter = 1;
self.reinforcements = 0;
let audio = emulator.take_audio_u8(); let audio = emulator.take_audio_u8();
agent agent
.warmup(Some(&self.frame_buffer)) .warmup(Some(&self.frame_buffer))
@ -305,6 +312,11 @@ impl LegacyFrame {
.map_err(|error| anyhow!("{error}"))?; .map_err(|error| anyhow!("{error}"))?;
self.remainder = checkpoint.agent.remainder; 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.frame_counter = runtime.emulator_frame;
self.buttons = runtime.buttons; self.buttons = runtime.buttons;
self.frame_buffer.copy_from_slice(&runtime.framebuffer); self.frame_buffer.copy_from_slice(&runtime.framebuffer);
@ -576,6 +588,7 @@ impl LegacyFrame {
} }
if agent.network.plasticity.enabled { if agent.network.plasticity.enabled {
agent.network.plasticity.reinforce(total, ms); agent.network.plasticity.reinforce(total, ms);
self.reinforcements += 1;
} }
} }

View file

@ -1,176 +1,6 @@
//! The sugar journal: every admitted audience input, stamped with the frame it was applied before. //! The sugar journal: every admitted audience input, stamped with the frame it was applied before.
//! //!
//! `sugar-journal.jsonl` in `[paths] hot_dir`, one JSON object per line, append-only. It is not //! The code lives in the `flysim-store` crate, which the session runtime links too (STATE-02).
//! part of a checkpoint and nothing reads it back into the fly: it is the record a shadow run //! This module re-exports it.
//! (the session framework's CUT-01, `docs/design/session-framework/legacy-gameboy-v1.md` section
//! 15) replays audience input from. The legacy loop applies an admitted sugar at once, in the
//! command drain at the top of a frame, so an input is fully placed by the transition it precedes:
//!
//! ```json
//! {"frame":"6465126","brainMs":108246189,"kind":"sugar","durationMs":400,"by":"viewer","source":"twitch","eventId":81234,"wallMs":1790000000000}
//! ```
//!
//! - `frame` is the frame counter when the input was applied, which is the `step` of the next
//! transition in the frame trace (`crate::trace`): replay applies it before that transition's
//! ticks. A restore carries the frame counter, so stamps continue across restarts.
//! - `kind` is `sugar` (a `reward-pulse` stimulation of `durationMs`, after the admission rules
//! and the clamp) or `reward` (an operator's `POST /reward`, one reinforcement of `value`).
//! - `brainMs` cross-checks the stamp; `eventId` joins the event log; `wallMs` is for people.
//!
//! Refused requests are not journalled: admission is wall-clock policy, and a replay applies what
//! was admitted. A write that fails is a warning, never a refusal: the input has already reached
//! the fly.
use std::fs::{File, OpenOptions}; pub use flysim_store::journal::*;
use std::io::Write;
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
/// The journal's file name inside the hot directory.
pub const FILE_NAME: &str = "sugar-journal.jsonl";
/// What was applied.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Input {
Sugar { duration_ms: f64 },
Reward { value: f64 },
}
/// One journal line.
#[derive(Debug, Clone, PartialEq)]
pub struct Entry<'a> {
pub frame: u64,
pub brain_ms: f64,
pub input: Input,
pub by: &'a str,
pub source: &'a str,
pub event_id: u64,
pub wall_ms: u64,
}
impl Entry<'_> {
pub fn to_json(&self) -> Value {
let mut line = json!({ "frame": self.frame.to_string(), "brainMs": self.brain_ms });
let map = line.as_object_mut().expect("an object");
match self.input {
Input::Sugar { duration_ms } => {
map.insert("kind".into(), "sugar".into());
map.insert("durationMs".into(), json!(duration_ms));
}
Input::Reward { value } => {
map.insert("kind".into(), "reward".into());
map.insert("value".into(), json!(value));
}
}
map.insert("by".into(), self.by.into());
map.insert("source".into(), self.source.into());
map.insert("eventId".into(), self.event_id.into());
map.insert("wallMs".into(), self.wall_ms.into());
line
}
}
/// The append-only journal. Opened on the first input, so a run nobody feeds writes no file.
pub struct SugarJournal {
path: PathBuf,
file: Option<File>,
}
impl SugarJournal {
pub fn new(hot_dir: &Path) -> Self {
Self {
path: hot_dir.join(FILE_NAME),
file: None,
}
}
pub fn path(&self) -> &Path {
&self.path
}
/// Append one line. Each line is one `write` of the whole line, so a crash leaves at most a
/// torn last line, which a reader skips.
pub fn record(&mut self, entry: &Entry<'_>) {
if self.file.is_none() {
match OpenOptions::new()
.create(true)
.append(true)
.open(&self.path)
{
Ok(file) => self.file = Some(file),
Err(error) => {
tracing::warn!(%error, path = %self.path.display(), "could not open the sugar journal");
return;
}
}
}
let mut line = entry.to_json().to_string();
line.push('\n');
if let Some(file) = self.file.as_mut()
&& let Err(error) = file.write_all(line.as_bytes())
{
tracing::warn!(%error, path = %self.path.display(), "could not append to the sugar journal");
// Reopen on the next input rather than write through a broken handle.
self.file = None;
}
}
}
/// Read a journal back: every whole line, in order. A torn or unreadable line is skipped.
pub fn read(path: &Path) -> std::io::Result<Vec<Value>> {
let text = std::fs::read_to_string(path)?;
Ok(text
.lines()
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
.filter(|value| value.get("frame").is_some())
.collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn inputs_are_appended_with_their_frame_and_survive_a_reopen() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut journal = SugarJournal::new(dir.path());
assert!(
!journal.path().exists(),
"nothing is written before an input"
);
let sugar = Entry {
frame: 42,
brain_ms: 703.0,
input: Input::Sugar { duration_ms: 400.0 },
by: "viewer",
source: "test",
event_id: 7,
wall_ms: 1,
};
journal.record(&sugar);
drop(journal);
let mut journal = SugarJournal::new(dir.path());
journal.record(&Entry {
frame: 43,
input: Input::Reward { value: 0.5 },
event_id: 8,
..sugar
});
// A torn tail from a crash is skipped, not fatal.
std::fs::OpenOptions::new()
.append(true)
.open(journal.path())
.and_then(|mut file| file.write_all(b"{\"frame\":\"44\",\"kin"))
.expect("appending a torn line");
let lines = read(journal.path()).expect("the journal reads back");
assert_eq!(lines.len(), 2);
assert_eq!(lines[0]["frame"], "42");
assert_eq!(lines[0]["kind"], "sugar");
assert_eq!(lines[0]["durationMs"], 400.0);
assert_eq!(lines[1]["frame"], "43");
assert_eq!(lines[1]["kind"], "reward");
assert_eq!(lines[1]["value"], 0.5);
assert_eq!(lines[1]["eventId"], 8);
}
}

View file

@ -32,6 +32,10 @@
//! talked, reached, pushed-back) are memory-only by contract //! talked, reached, pushed-back) are memory-only by contract
//! (`docs/design/macros.md` section 12.1: "a restored run offers every target once more"), //! (`docs/design/macros.md` section 12.1: "a restored run offers every target once more"),
//! so stopping flysim is what resets those and this has nothing to do. //! so stopping flysim is what resets those and this has nothing to do.
//! 6. **clears the sugar journal** (`crate::journal::clear`): the journal and its rotations in the
//! hot store. The reset rewinds the frame counter to the rung's, so inputs stamped with the
//! abandoned run's frames would otherwise precede the new run's and read as its future. The
//! dated archive of step 1 keeps the old journal.
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -161,6 +165,11 @@ pub fn reset_to_milestone(
memory-only and are reset by stopping flysim)" memory-only and are reset by stopping flysim)"
)); ));
// 6. The sugar journal, copied aside in step 1.
let journals = crate::journal::clear(hot_dir)
.with_context(|| format!("clearing the sugar journal in {}", hot_dir.display()))?;
report.push(format!("cleared the sugar journal: {journals} files removed"));
Ok(report) Ok(report)
} }
@ -317,6 +326,7 @@ mod tests {
}, },
}; };
let runtime = store::RuntimeState { let runtime = store::RuntimeState {
reinforcements: None,
generation, generation,
wall_ms: 1_700_000_000_000, wall_ms: 1_700_000_000_000,
rom_sha256: "ab".repeat(32), rom_sha256: "ab".repeat(32),
@ -379,6 +389,21 @@ mod tests {
}; };
state_dir(&durable, &[3, 5, 9, 11], spent); state_dir(&durable, &[3, 5, 9, 11], spent);
state_dir(&hot, &[11], spent); state_dir(&hot, &[11], spent);
// The abandoned run's sugar journal, rotated once.
let mut journal = crate::journal::SugarJournal::with_limits(&hot, 200, 3);
for frame in 0..4 {
journal.record(&crate::journal::Entry {
frame: 900 + frame,
brain_ms: 0.0,
input: crate::journal::Input::Sugar { duration_ms: 300.0 },
by: "viewer",
source: "test",
event_id: frame,
wall_ms: 1,
});
}
drop(journal);
assert!(crate::journal::rotation_path(&hot, 1).is_file());
let archive = tmp.path().join("archive-20260922"); let archive = tmp.path().join("archive-20260922");
let report = reset_to_milestone(&durable, &hot, 5, &archive).unwrap(); let report = reset_to_milestone(&durable, &hot, 5, &archive).unwrap();
@ -397,6 +422,11 @@ mod tests {
assert!(!durable.join("events.jsonl").exists()); assert!(!durable.join("events.jsonl").exists());
assert!(!durable.join("events-20260921.jsonl").exists()); assert!(!durable.join("events-20260921.jsonl").exists());
assert!(!hot.join("milestone-11.checkpoint").exists()); assert!(!hot.join("milestone-11.checkpoint").exists());
// The journal is cleared, and the archive keeps it.
assert!(!hot.join(crate::journal::FILE_NAME).exists());
assert!(!crate::journal::rotation_path(&hot, 1).exists());
assert!(archive.join("hot").join(crate::journal::FILE_NAME).is_file());
assert!(report.iter().any(|line| line.starts_with("cleared the sugar journal: 4 files")), "{report:?}");
// Both stores restore the rung, and the counters are back. // Both stores restore the rung, and the counters are back.
for store in [Store::new(&hot, KEEP_GENERATIONS), Store::new(&durable, KEEP_GENERATIONS)] { for store in [Store::new(&hot, KEEP_GENERATIONS), Store::new(&durable, KEEP_GENERATIONS)] {

View file

@ -389,6 +389,9 @@ pub struct Sim {
compatibility: String, compatibility: String,
semantic_rewards: bool, semantic_rewards: bool,
restored: bool, restored: bool,
/// Where this process started, for the sugar journal's boot header: the restore candidate's
/// origin and generation, or a fresh start.
boot_origin: (String, Option<u64>),
/// Per-phase timing, off unless `FLY_PROFILE_SECONDS` is set (`crate::profile`). /// Per-phase timing, off unless `FLY_PROFILE_SECONDS` is set (`crate::profile`).
profiler: Profiler, profiler: Profiler,
} }
@ -595,6 +598,7 @@ impl Sim {
compatibility, compatibility,
semantic_rewards, semantic_rewards,
restored: false, restored: false,
boot_origin: ("fresh start".to_string(), None),
profiler: Profiler::from_env(now), profiler: Profiler::from_env(now),
agent, agent,
emulator, emulator,
@ -641,6 +645,17 @@ impl Sim {
// the whole warm-up — or, after a restore, every neuron that has ever fired, since the // the whole warm-up — or, after a restore, every neuron that has ever fired, since the
// checkpoint's `lastSpikeMs` values are absolute brain milliseconds. // checkpoint's `lastSpikeMs` values are absolute brain milliseconds.
sim.last_publish_ms = sim.agent.network.ms; sim.last_publish_ms = sim.agent.network.ms;
// The journal's boot header: this process's inputs start here, whatever the previous
// process journalled after the checkpoint it restored (`crate::journal`).
sim.journal.boot(&crate::journal::BootHeader {
runtime: "flysim".to_string(),
start_frame: sim.frame.frame_counter,
brain_ms: sim.agent.network.ms,
origin: sim.boot_origin.0.clone(),
generation: sim.boot_origin.1,
compatibility: sim.compatibility.clone(),
wall_ms: now_wall_ms(),
});
sim.status = FeedStatus::Running; sim.status = FeedStatus::Running;
// A durable commit immediately after startup or restore (section 8), so the 300-second // A durable commit immediately after startup or restore (section 8), so the 300-second
// interval is a ceiling on routine loss only, and so a broken write path is found now // interval is a ceiling on routine loss only, and so a broken write path is found now
@ -685,6 +700,7 @@ impl Sim {
"restored" "restored"
); );
self.restored = true; self.restored = true;
self.boot_origin = (candidate.origin.clone(), candidate.generation);
self.emit(NewEvent::new( self.emit(NewEvent::new(
FeedEventKind::System, FeedEventKind::System,
format!("Restored from {}", candidate.origin), format!("Restored from {}", candidate.origin),
@ -1380,6 +1396,7 @@ impl Sim {
last_event_id: self.log.next_id().saturating_sub(1), last_event_id: self.log.next_id().saturating_sub(1),
reward: self.adapter.export_state(), reward: self.adapter.export_state(),
ratchet: self.ratchet.state, ratchet: self.ratchet.state,
reinforcements: Some(self.frame.reinforcements),
emulator: self emulator: self
.emulator .emulator
.export_state() .export_state()

View file

@ -1,645 +1,8 @@
//! Checkpoint persistence: the `FLYSIM01` envelope, the atomic commit, the generations and the //! Checkpoint persistence: the `FLYSIM01` envelope, the atomic commit, the generations and the
//! milestone archives. //! milestone archives.
//! //!
//! `docs/design/flysim.md` section 8, as amended by the contract override at the top of that //! The code lives in the `flysim-store` crate, which the session runtime links too (STATE-02), so
//! document: //! both write byte-identical checkpoints into the same store. This module re-exports it, and every
//! //! `flysim::store` path keeps working.
//! - the envelope is `flybrain-core`'s frozen `encodeEnvelope` layout with the magic `FLYSIM01`,
//! carrying the seven agent chunks plus `emulator`, `framebuffer`, `ratchetGame` and
//! `ratchetFrame`;
//! - a commit writes `<gen>.checkpoint.tmp`, fsyncs it, renames it, fsyncs the directory, and
//! then does the same for `manifest.json`. **The manifest rename is the commit point**: a
//! crash before it leaves an unreferenced file that is never loaded;
//! - durable commits go to `save_dir` every `checkpoint_seconds` (default 300) and on every
//! event that matters; a hot copy goes to `hot_dir` (tmpfs) every `hot_seconds` (default 5);
//! - the first commit at a new best rank also writes `milestone-<rank>.checkpoint`, which later
//! rotations never unlink.
use std::collections::BTreeMap; pub use flysim_store::store::*;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use flybrain_core::envelope::{EnvelopeParts, decode_envelope, encode_envelope};
use flybrain_core::json::JsonValue;
use serde::{Deserialize, Serialize};
/// Envelope magic. Chunk names stay `[a-zA-Z]+` so the TypeScript `decodeEnvelope` can read a
/// flysim checkpoint for recap and inspection tooling.
pub const MAGIC: &str = "FLYSIM01";
/// Chunk names flysim adds to `flybrain-core`'s `AGENT_CHUNK_NAMES`.
pub const EMULATOR_CHUNK: &str = "emulator";
pub const FRAMEBUFFER_CHUNK: &str = "framebuffer";
pub const RATCHET_GAME_CHUNK: &str = "ratchetGame";
pub const RATCHET_FRAME_CHUNK: &str = "ratchetFrame";
/// `manifest.json`: which generations are current, and which are archived forever.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct StoreManifest {
/// Highest generation ever allocated in this store.
pub generation: u64,
/// The generation to restore first.
pub latest: Option<u64>,
/// The generation to restore if `latest` will not load.
pub previous: Option<u64>,
/// Best-rank archives, rank to generation. Their files are never rotated away.
pub archives: BTreeMap<u32, u64>,
}
impl StoreManifest {
fn record(&mut self, generation: u64, archive_rank: Option<u32>) {
self.generation = self.generation.max(generation);
if self.latest != Some(generation) {
self.previous = self.latest;
self.latest = Some(generation);
}
if let Some(rank) = archive_rank {
self.archives.insert(rank, generation);
}
}
/// Generations that must survive rotation.
fn referenced(&self) -> Vec<u64> {
let mut out: Vec<u64> = self.latest.into_iter().chain(self.previous).collect();
out.extend(self.archives.values().copied());
out
}
}
/// One restore candidate, in the order it should be tried.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Candidate {
pub path: PathBuf,
/// Human description for the log and for `/status`'s fallback reporting.
pub origin: String,
pub generation: Option<u64>,
}
/// A checkpoint directory: `<gen>.checkpoint`, `milestone-<rank>.checkpoint`, `manifest.json`.
#[derive(Debug, Clone)]
pub struct Store {
dir: PathBuf,
keep_generations: usize,
}
impl Store {
pub fn new(dir: impl Into<PathBuf>, keep_generations: usize) -> Self {
Self { dir: dir.into(), keep_generations: keep_generations.max(1) }
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn create(&self) -> Result<()> {
std::fs::create_dir_all(&self.dir)
.with_context(|| format!("creating checkpoint directory {}", self.dir.display()))
}
pub fn manifest_path(&self) -> PathBuf {
self.dir.join("manifest.json")
}
pub fn generation_path(&self, generation: u64) -> PathBuf {
self.dir.join(format!("{generation}.checkpoint"))
}
pub fn archive_path(&self, rank: u32) -> PathBuf {
self.dir.join(format!("milestone-{rank}.checkpoint"))
}
/// Read `manifest.json`, or `None` when it is absent or unreadable.
pub fn manifest(&self) -> Option<StoreManifest> {
let text = std::fs::read_to_string(self.manifest_path()).ok()?;
match serde_json::from_str(&text) {
Ok(manifest) => Some(manifest),
Err(error) => {
tracing::warn!(%error, path = %self.manifest_path().display(), "unreadable store manifest");
None
}
}
}
/// Highest generation the store has ever allocated, from the manifest and from the files on
/// disk (an unreferenced file from a crashed commit still counts, so a generation number is
/// never reused).
pub fn highest_generation(&self) -> u64 {
let mut highest = self.manifest().map_or(0, |manifest| manifest.generation);
if let Ok(entries) = std::fs::read_dir(&self.dir) {
for entry in entries.flatten() {
if let Some(generation) = parse_generation(&entry.file_name().to_string_lossy()) {
highest = highest.max(generation);
}
}
}
highest
}
/// Restore candidates from this store, in order: latest, previous, then the archives by
/// descending rank.
pub fn candidates(&self, label: &str) -> Vec<Candidate> {
let Some(manifest) = self.manifest() else {
return Vec::new();
};
let mut out = Vec::new();
for (kind, generation) in [("latest", manifest.latest), ("previous", manifest.previous)] {
if let Some(generation) = generation {
out.push(Candidate {
path: self.generation_path(generation),
origin: format!("{label} {kind} generation {generation}"),
generation: Some(generation),
});
}
}
for (rank, generation) in manifest.archives.iter().rev() {
out.push(Candidate {
path: self.generation_path(*generation),
origin: format!("{label} archived generation {generation} (rank {rank})"),
generation: Some(*generation),
});
out.push(Candidate {
path: self.archive_path(*rank),
origin: format!("{label} milestone archive rank {rank}"),
generation: Some(*generation),
});
}
out.retain(|candidate| candidate.path.exists());
out
}
/// Write `bytes` as `generation`, commit it, archive it if `archive_rank` is set, then rotate.
///
/// The sequence is exactly section 8's: payload tmp, fsync, rename, dir fsync, then manifest
/// tmp, fsync, rename, dir fsync.
pub fn commit(
&self,
generation: u64,
bytes: &[u8],
archive_rank: Option<u32>,
) -> Result<StoreManifest> {
self.create()?;
write_atomic(&self.generation_path(generation), bytes)?;
if let Some(rank) = archive_rank {
write_atomic(&self.archive_path(rank), bytes)?;
}
let mut manifest = self.manifest().unwrap_or_default();
manifest.record(generation, archive_rank);
let text = serde_json::to_vec_pretty(&manifest)?;
write_atomic(&self.manifest_path(), &text)?;
self.rotate(&manifest)?;
Ok(manifest)
}
/// Stage a payload without committing it. Only the crash-simulation test uses this: it is
/// the state a `kill -9` between the tmp write and the rename leaves behind.
pub fn stage_for_test(&self, generation: u64, bytes: &[u8]) -> Result<PathBuf> {
self.create()?;
let path = tmp_path(&self.generation_path(generation));
write_and_sync(&path, bytes)?;
Ok(path)
}
/// Remove generation files that the manifest no longer references, keeping the newest
/// `keep_generations` and never touching an archive.
fn rotate(&self, manifest: &StoreManifest) -> Result<()> {
let referenced = manifest.referenced();
let mut generations: Vec<u64> = Vec::new();
for entry in std::fs::read_dir(&self.dir)?.flatten() {
let name = entry.file_name().to_string_lossy().to_string();
if let Some(generation) = parse_generation(&name) {
generations.push(generation);
} else if name.ends_with(".checkpoint.tmp") {
// A tmp file from an interrupted commit is never loadable; clean it up.
let _ = std::fs::remove_file(entry.path());
}
}
generations.sort_unstable_by(|a, b| b.cmp(a));
for (index, generation) in generations.iter().enumerate() {
if referenced.contains(generation) || index < self.keep_generations {
continue;
}
let path = self.generation_path(*generation);
if let Err(error) = std::fs::remove_file(&path) {
tracing::warn!(%error, path = %path.display(), "could not rotate a checkpoint");
}
}
Ok(())
}
}
/// `milestone-<rank>.checkpoint` is an independent file, so it is not a generation.
fn parse_generation(name: &str) -> Option<u64> {
name.strip_suffix(".checkpoint")?.parse().ok()
}
fn tmp_path(path: &Path) -> PathBuf {
let mut name = path.as_os_str().to_os_string();
name.push(".tmp");
PathBuf::from(name)
}
/// tmp write, fsync, rename, directory fsync.
pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
let tmp = tmp_path(path);
write_and_sync(&tmp, bytes)?;
std::fs::rename(&tmp, path)
.with_context(|| format!("renaming {} to {}", tmp.display(), path.display()))?;
sync_dir(path.parent().unwrap_or(Path::new(".")))
}
fn write_and_sync(path: &Path, bytes: &[u8]) -> Result<()> {
let mut file = OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(path)
.with_context(|| format!("creating {}", path.display()))?;
file.write_all(bytes)?;
file.flush()?;
file.sync_all().with_context(|| format!("fsync {}", path.display()))?;
Ok(())
}
fn sync_dir(dir: &Path) -> Result<()> {
// Opening a directory read-only and fsyncing it is what makes the rename durable.
File::open(dir)
.and_then(|file| file.sync_all())
.with_context(|| format!("fsync directory {}", dir.display()))
}
// ---------------------------------------------------------------------------------------------
// The envelope
// ---------------------------------------------------------------------------------------------
/// Everything a checkpoint carries besides the agent's own chunks.
#[derive(Debug, Clone, PartialEq)]
pub struct RuntimeState {
pub generation: u64,
pub wall_ms: u64,
pub rom_sha256: String,
pub emulator_frame: u64,
pub compatibility: String,
pub speed: f64,
pub buttons: u32,
/// Simulated milliseconds at which the current milestone rank was reached.
pub rank_since_ms: f64,
pub last_event_id: u64,
/// The adapter's own lifetime reward state.
pub reward: serde_json::Value,
pub ratchet: flybrain_gb::RatchetState,
pub emulator: Vec<u8>,
pub framebuffer: Vec<u8>,
/// The ratchet's best safe snapshot, if it has one.
pub ratchet_game: Vec<u8>,
pub ratchet_frame: Vec<u8>,
}
/// A decoded checkpoint: the agent half plus the runtime half.
#[derive(Debug, Clone)]
pub struct Checkpoint {
pub agent: flybrain_core::agent::AgentState,
pub runtime: RuntimeState,
}
/// Encode an agent state plus the runtime state into one `FLYSIM01` envelope.
pub fn encode(
agent: &flybrain_core::agent::AgentState,
runtime: &RuntimeState,
) -> Result<Vec<u8>> {
let parts = flybrain_core::envelope::agent_to_chunks(agent);
let mut manifest = parts.manifest;
manifest.set("generation", (runtime.generation as f64).into());
manifest.set("wallMs", (runtime.wall_ms as f64).into());
manifest.set("romHash", runtime.rom_sha256.as_str().into());
manifest.set("emulatorFrame", (runtime.emulator_frame as f64).into());
manifest.set("compatibility", runtime.compatibility.as_str().into());
manifest.set("speed", runtime.speed.into());
manifest.set("buttons", f64::from(runtime.buttons).into());
manifest.set("rankSinceMs", runtime.rank_since_ms.into());
manifest.set("lastEventId", (runtime.last_event_id as f64).into());
manifest.set("reward", to_json_value(&runtime.reward)?);
manifest.set("ratchet", to_json_value(&serde_json::to_value(runtime.ratchet)?)?);
let mut chunks = parts.chunks;
chunks.push((EMULATOR_CHUNK.to_string(), runtime.emulator.clone()));
chunks.push((FRAMEBUFFER_CHUNK.to_string(), runtime.framebuffer.clone()));
chunks.push((RATCHET_GAME_CHUNK.to_string(), runtime.ratchet_game.clone()));
chunks.push((RATCHET_FRAME_CHUNK.to_string(), runtime.ratchet_frame.clone()));
encode_envelope(MAGIC, &manifest, &chunks).map_err(|error| anyhow::anyhow!("{error}"))
}
/// Decode and structurally validate a `FLYSIM01` envelope.
///
/// Value-level validation belongs to the importers: `NeuralAgent::import_state` is
/// self-validating and a no-op on failure, and `Ratchet::import` rejects an impossible state.
pub fn decode(bytes: &[u8]) -> Result<Checkpoint> {
let parts: EnvelopeParts =
decode_envelope(bytes, MAGIC).map_err(|error| anyhow::anyhow!("{error}"))?;
let manifest = parts.manifest.clone();
let agent = flybrain_core::envelope::agent_from_chunks(&manifest, &parts)
.map_err(|error| anyhow::anyhow!("{error}"))?;
let string = |key: &str| -> Result<String> {
manifest
.get(key)
.and_then(JsonValue::as_str)
.map(str::to_string)
.ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}"))
};
let number = |key: &str| -> Result<f64> {
manifest
.get(key)
.and_then(JsonValue::as_f64)
.ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing {key}"))
};
let chunk = |name: &str| -> Result<Vec<u8>> {
parts
.chunk(name)
.map(<[u8]>::to_vec)
.ok_or_else(|| anyhow::anyhow!("checkpoint is missing the {name} chunk"))
};
let ratchet_json = manifest
.get("ratchet")
.ok_or_else(|| anyhow::anyhow!("checkpoint manifest is missing ratchet"))?;
let ratchet: flybrain_gb::RatchetState = serde_json::from_str(&ratchet_json.stringify())
.context("checkpoint ratchet state is not readable")?;
let reward = manifest
.get("reward")
.map(|value| serde_json::from_str(&value.stringify()))
.transpose()
.context("checkpoint reward state is not readable")?
.unwrap_or(serde_json::Value::Null);
Ok(Checkpoint {
agent,
runtime: RuntimeState {
generation: number("generation")? as u64,
wall_ms: number("wallMs")? as u64,
rom_sha256: string("romHash")?,
emulator_frame: number("emulatorFrame")? as u64,
compatibility: string("compatibility")?,
speed: number("speed")?,
buttons: number("buttons")? as u32,
rank_since_ms: number("rankSinceMs").unwrap_or(0.0),
last_event_id: number("lastEventId").unwrap_or(0.0) as u64,
reward,
ratchet,
emulator: chunk(EMULATOR_CHUNK)?,
framebuffer: chunk(FRAMEBUFFER_CHUNK)?,
ratchet_game: chunk(RATCHET_GAME_CHUNK)?,
ratchet_frame: chunk(RATCHET_FRAME_CHUNK)?,
},
})
}
/// Read and decode a candidate, so a caller can try the next one on any failure.
pub fn load(path: &Path) -> Result<Checkpoint> {
let bytes =
std::fs::read(path).with_context(|| format!("reading checkpoint {}", path.display()))?;
decode(&bytes).with_context(|| format!("decoding checkpoint {}", path.display()))
}
fn to_json_value(value: &serde_json::Value) -> Result<JsonValue> {
JsonValue::parse(&serde_json::to_string(value)?).map_err(|error| anyhow::anyhow!("{error}"))
}
/// The restore order: the tmpfs hot copy first, then the durable store.
///
/// The hot copy is written every few seconds and the durable one every few minutes, so the hot
/// copy is normally the newest state that exists; it is a first-class candidate because it uses
/// the identical envelope and the identical atomic sequence, and not a partial dump.
/// The compatibility string the newest decodable checkpoint in `dir` carries, if any.
///
/// The store's own `manifest.json` is only an index (generation, latest, previous, archives) —
/// the compatibility string lives in each checkpoint's own `FLYSIM01` envelope manifest, so
/// answering "what will this build refuse?" means decoding a checkpoint. Candidates are tried
/// newest first and a corrupt one is skipped, which is the same order and the same tolerance
/// `Sim::boot` restores with.
///
/// `flysim --print-state-compatibility DIR` is this, and `infra/05-deploy.sh` compares its
/// answer with `--print-compatibility` before flipping the `current` symlink.
pub fn state_compatibility(dir: &Path) -> Option<String> {
let store = Store::new(dir, 8);
for candidate in store.candidates("durable") {
if let Ok(checkpoint) = load(&candidate.path) {
return Some(checkpoint.runtime.compatibility);
}
}
None
}
pub fn restore_order(hot: &Store, durable: &Store) -> Vec<Candidate> {
let mut out = hot.candidates("hot");
out.extend(durable.candidates("durable"));
out
}
#[cfg(test)]
mod tests {
use super::*;
fn runtime(generation: u64) -> RuntimeState {
RuntimeState {
generation,
wall_ms: 1_700_000_000_000,
rom_sha256: "ab".repeat(32),
emulator_frame: 12_345,
compatibility: "kernel/adapter/fingerprint".to_string(),
speed: 1.0,
buttons: 0b0001_0000,
rank_since_ms: 4_242.0,
last_event_id: 77,
reward: serde_json::json!({ "version": 3, "total": 1.25 }),
ratchet: flybrain_gb::RatchetState { best: 3, ..Default::default() },
emulator: vec![7; 64],
framebuffer: vec![9; 32],
ratchet_game: vec![1, 2, 3],
ratchet_frame: vec![4, 5, 6],
}
}
fn agent_state() -> flybrain_core::agent::AgentState {
use flybrain_core::decoder::DecoderState;
use flybrain_core::lif::LifState;
use flybrain_core::ordered::NumberMap;
use flybrain_core::plasticity::PlasticityState;
flybrain_core::agent::AgentState {
version: 1,
remainder: 0.75,
warmed_up: true,
network: LifState {
membrane: vec![0.5, -0.25],
refractory: vec![0, 3],
last_spike_ms: vec![-1_000_000.0, 12.0],
visual_drive: vec![0.1],
rng: -12_345,
reward_remaining: 40.0,
ms: 9_000.0,
population_rate: 1.5,
rates: NumberMap::from_pairs([("forward", 2.0), ("reward_pam", 0.5)]),
plasticity: PlasticityState {
version: "fly-kc-mbon-rstdp-v2".to_string(),
topology: 42,
enabled: true,
updates: 3.0,
signal: 0.25,
gains: vec![1.0, 0.9],
traces: vec![0.0, 0.1],
touched: vec![0.0, 8_000.0],
},
},
decoder: DecoderState {
version: 4,
calibrated: true,
baseline: NumberMap::from_pairs([("forward", 1.0)]),
held_until: NumberMap::new(),
next_allowed: NumberMap::new(),
next_decision: 100.0,
current: Some("a".to_string()),
fatigue: NumberMap::new(),
macro_next_decision: 0.0,
macro_current: None,
macro_fatigue: NumberMap::new(),
},
}
}
#[test]
fn the_envelope_round_trips_every_field_and_chunk() {
let agent = agent_state();
let runtime = runtime(4);
let bytes = encode(&agent, &runtime).unwrap();
assert!(bytes.starts_with(MAGIC.as_bytes()));
let back = decode(&bytes).unwrap();
assert_eq!(back.agent, agent);
assert_eq!(back.runtime, runtime);
// Re-encoding the decoded state is byte-identical, so a restore-and-save cycle is stable.
assert_eq!(encode(&back.agent, &back.runtime).unwrap(), bytes);
}
#[test]
fn a_corrupted_or_truncated_envelope_is_rejected() {
let bytes = encode(&agent_state(), &runtime(1)).unwrap();
assert!(decode(&bytes[..bytes.len() - 1]).is_err(), "truncated");
let mut flipped = bytes.clone();
let middle = flipped.len() / 2;
flipped[middle] ^= 0xff;
assert!(decode(&flipped).is_err(), "checksum");
let mut trailing = bytes.clone();
trailing.push(0);
assert!(decode(&trailing).is_err(), "trailing bytes");
let mut wrong_magic = bytes;
wrong_magic[0] = b'X';
assert!(decode(&wrong_magic).is_err(), "magic");
}
#[test]
fn a_commit_is_atomic_and_a_crash_before_the_rename_leaves_a_loadable_store() {
let dir = tempfile::tempdir().unwrap();
let store = Store::new(dir.path(), 2);
let first = encode(&agent_state(), &runtime(1)).unwrap();
store.commit(1, &first, None).unwrap();
// kill -9 between the tmp write and the rename.
let mut broken = encode(&agent_state(), &runtime(2)).unwrap();
broken.truncate(broken.len() / 2);
let staged = store.stage_for_test(2, &broken).unwrap();
assert!(staged.exists());
let manifest = store.manifest().unwrap();
assert_eq!(manifest.latest, Some(1));
let candidates = store.candidates("durable");
assert_eq!(candidates.len(), 1, "the staged tmp file is not a candidate: {candidates:?}");
assert_eq!(load(&candidates[0].path).unwrap().runtime.generation, 1);
// The next successful commit cleans the orphan up.
let second = encode(&agent_state(), &runtime(3)).unwrap();
store.commit(3, &second, None).unwrap();
assert!(!staged.exists());
assert_eq!(store.manifest().unwrap().latest, Some(3));
assert_eq!(store.manifest().unwrap().previous, Some(1));
}
#[test]
fn a_payload_renamed_without_its_manifest_is_never_loaded() {
let dir = tempfile::tempdir().unwrap();
let store = Store::new(dir.path(), 2);
store.commit(1, &encode(&agent_state(), &runtime(1)).unwrap(), None).unwrap();
// The payload rename succeeded, the manifest rename did not: the commit point is the
// manifest, so generation 2 is invisible.
write_atomic(&store.generation_path(2), b"not even an envelope").unwrap();
let candidates = store.candidates("durable");
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].generation, Some(1));
assert_eq!(store.highest_generation(), 2, "but the number is not reused");
}
#[test]
fn the_restore_order_is_hot_then_durable_then_archives_by_descending_rank() {
let dir = tempfile::tempdir().unwrap();
let durable = Store::new(dir.path().join("durable"), 2);
let hot = Store::new(dir.path().join("hot"), 2);
let bytes = encode(&agent_state(), &runtime(1)).unwrap();
durable.commit(1, &bytes, Some(1)).unwrap();
durable.commit(2, &bytes, Some(4)).unwrap();
durable.commit(3, &bytes, None).unwrap();
hot.commit(7, &bytes, None).unwrap();
let order: Vec<String> =
restore_order(&hot, &durable).into_iter().map(|c| c.origin).collect();
assert_eq!(
order,
vec![
"hot latest generation 7",
"durable latest generation 3",
"durable previous generation 2",
"durable archived generation 2 (rank 4)",
"durable milestone archive rank 4",
"durable archived generation 1 (rank 1)",
"durable milestone archive rank 1",
]
);
}
#[test]
fn rotation_keeps_the_referenced_generations_and_never_unlinks_an_archive() {
let dir = tempfile::tempdir().unwrap();
let store = Store::new(dir.path(), 2);
let bytes = encode(&agent_state(), &runtime(1)).unwrap();
store.commit(1, &bytes, Some(2)).unwrap();
for generation in 2..=6 {
store.commit(generation, &bytes, None).unwrap();
}
assert!(store.generation_path(6).exists(), "latest");
assert!(store.generation_path(5).exists(), "previous");
assert!(store.generation_path(1).exists(), "archived generation");
assert!(store.archive_path(2).exists(), "milestone archive");
assert!(!store.generation_path(3).exists(), "rotated away");
assert!(!store.generation_path(4).exists(), "rotated away");
}
#[test]
fn an_empty_or_manifestless_directory_offers_no_candidates() {
let dir = tempfile::tempdir().unwrap();
let store = Store::new(dir.path().join("missing"), 2);
assert!(store.candidates("durable").is_empty());
assert_eq!(store.highest_generation(), 0);
let store = Store::new(dir.path(), 2);
store.create().unwrap();
std::fs::write(store.manifest_path(), "{ not json").unwrap();
assert!(store.candidates("durable").is_empty(), "an unreadable manifest is not fatal");
}
}

View file

@ -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<Vec<u8>> {
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<Vec<u8>>,
index: HashMap<String, usize>,
}
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<TraceTransition>,
/// The agent state the run started from, for a restored start.
start: Option<AgentState>,
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<BrainDataset>,
start: Start<'_>,
mode: MacroMode,
frames: usize,
sugar: &[(usize, f64)],
rollback_at: Option<usize>,
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<RewardEvent> = 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<ExecutionMode> {
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<ParityRecord> {
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<ParityRecord>,
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;
}

View file

@ -113,6 +113,7 @@ fn v6_checkpoint() -> Vec<u8> {
}, },
}; };
let runtime = RuntimeState { let runtime = RuntimeState {
reinforcements: None,
generation: 41, generation: 41,
wall_ms: 1_790_000_000_000, wall_ms: 1_790_000_000_000,
rom_sha256: flybrain_gb::pokemon_red::SUPPORTED_ROM.to_string(), rom_sha256: flybrain_gb::pokemon_red::SUPPORTED_ROM.to_string(),

View file

@ -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<Vec<u8>> {
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<u64>,
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<u8> {
self.inner.read_rom(bank, address)
}
}
/// Every `MacroState` answer this frame, as text, in a fixed order.
fn sweep(state: &mut dyn MacroState) -> Vec<String> {
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<u8> = (0..=u8::MAX).filter(|&map| state.map_visited(map)).collect();
q!("maps_visited", maps);
let moves: Vec<u8> = (1..=165).filter(|&id| state.move_without_effect(id)).collect();
q!("moves_without_effect", moves);
let items: Vec<u8> = (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<u32>,
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<String>,
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<Vec<u8>> = 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<u8> = (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<u8> = (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());
}

View file

@ -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<PathBuf> {
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<PathBuf, String> = 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<EnvRecord>, Vec<u8>) {
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<Snapshot>) -> 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<MacroLayer>,
}
fn legacy_world(
rom: &[u8],
data: &Arc<BrainDataset>,
mode: MacroMode,
trace: Option<&Path>,
) -> (LegacyWorld, Vec<String>) {
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<u8> {
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<Vec<u8>>,
index: HashMap<String, usize>,
}
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<BrainDataset>,
checkpoint: &Checkpoint,
mode: MacroMode,
n: usize,
sugar: &[(usize, f64)],
rollback_at: Option<usize>,
trace_path: &Path,
) -> (LegacyWorld, LegacyScript, Vec<TraceTransition>) {
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<RewardEvent> = 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<BrainDataset>,
dataset_dir: PathBuf,
profile: LegacyProfileKind,
start: &[u8],
mode: MacroMode,
n: usize,
sugar: &[(usize, f64)],
rollback_at: Option<usize>,
) -> 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,
);
}

View file

@ -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<u32> {
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<lc::Restored<lc::Halves>> {
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);
}

View file

@ -67,6 +67,7 @@ fn agent_state() -> flybrain_core::agent::AgentState {
fn checkpoint(generation: u64, frame: u64, rom: &str, compatibility: &str) -> Vec<u8> { fn checkpoint(generation: u64, frame: u64, rom: &str, compatibility: &str) -> Vec<u8> {
let runtime = RuntimeState { let runtime = RuntimeState {
reinforcements: None,
generation, generation,
wall_ms: 1_757_000_000_000 + generation, wall_ms: 1_757_000_000_000 + generation,
rom_sha256: rom.to_string(), rom_sha256: rom.to_string(),