diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index a11fa4c..39f88ef 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -176,6 +176,35 @@ window and last location as private readout state; report `stimulusRemainingMs`; legacy rate-role names (`command_0`, `macro_*`, which are not `Id`s) to `AgentGraph.rateRoles`, which that contract leaves open. +**2026-09-23 (AGENT-01 built, `feat/agent-legacy-worker`).** `LegacyAgentWorker` +(`fly-session/src/legacy_agent.rs`) serves the legacy profile under the launcher in all three +execution modes (`legacy-agent` subcommand). Its parity harness (`legacy_parity.rs`) drives +`NeuralAgent` directly in `Sim::step_frame` order from recorded inputs. On the committed toy +connectome, the worker's records match that reference exactly in every mode, including a +rollback and a restore, and are pinned as goldens. A gated FAFB run +(`FLY_AGENT01_FAFB=1`) shows the same on `gameboy-legacy-fafb-v783-v1`. The rate-role mapping +turned out to be the identity: the legacy names are already `Id`s. It is recorded in +[legacy-gameboy-v1](legacy-gameboy-v1.md) section 13, with the other agent-adapter choices. The +harness's `ReferenceSource` is the seam for FND-01's `FLY_TRACE`. + +**2026-09-29 (AGENT-01 rebased onto v0.6.5 and checked against FND-01's trace).** The rebase onto +main had no conflicts. Main changed nothing the worker reads except the adapter id in the +fixtures (v7). The toy goldens and the FAFB reference digest are unchanged. `FLY_TRACE` carries +the frames only as digests and not the `{boot, bound, location}` context, so it checks a worker +and cannot drive one. `legacy_parity::read_frame_trace` and `check_against_trace` hold a run's +records to it: ticks, clock, exact remainder, rates digest, spike-set digest and decision. The +script is checked too: the same sugar, frames, reward events and rollback. +`flysim/tests/agent_trace_parity.rs` is the host. It runs `LegacyFrame` on the ROM with the trace +on, records the missing inputs and checks the worker (in-process, thread and process) and the +direct reference against the trace: + +- the toy connectome in raw mode from power-on, for every ROM run; +- `gameboy-legacy-fafb-v783-v1` in macros mode from stream checkpoints (`FLY_AGENT01_FAFB=1`), + with sugar and a ratchet rollback, the worker seeded from the checkpoint's agent state. + +Both are identical. Found on the way: a `FLYSIM01` import must start `learning.updates` at the +legacy `plasticity.updates` (legacy-gameboy-v1 section 13, amendment of 2026-09-29). + **Implement:** adapter over existing LIF, plasticity, retina and fixed readout primitives; reference-first composition/goldens; independently seeded agent state and shared immutable data. Avoid using the old whole-frame `tick` wrapper if it changes the specified phase ordering. diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 163934e..343eee2 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -125,7 +125,8 @@ interface GameboyReadoutContext { ``` `ChannelName` is `^[a-z][a-z0-9_]{0,63}$`. Decoder channel and rate-role names carry `_`, so -they are not `Id`s. The context is what the task hands the decoder with each Prepare (the +they are not `Id`s (corrected 2026-09-23, AGENT-01: they are; see the section 13 amendment). +The context is what the task hands the decoder with each Prepare (the `initialDecisionContext`, then every `nextDecisionContext`). `bound` is an ordered subset of the composition's `macroChannels`. @@ -351,6 +352,79 @@ stale files. valid `Id`s, while `AgentGraph.rateRoles` and `AgentTelemetry.rates[].roleId` are `Id`s. The mapping belongs to the agent adapter. This contract does not choose it. +**Amendment, 2026-09-23 (AGENT-01): the rate-role mapping `legacy-rate-role-id-v1`.** The +premise above is wrong. The session `Id` grammar is `^[a-z0-9][a-z0-9._-]{0,63}$` +([session RPC](ipc-v1.md) section 1, `flybus::wire::is_id`, `isId` in `@flybrain/session-types`), +and it admits `_`. Every role `data/fafb-v783` declares, including the 31 `macro_*` populations +merged after the fingerprint, and every role the kernel tracks, is already an `Id`; so is every +`ChannelName`, whose grammar is a subset. The mapping is therefore the identity: + +- a legacy rate-role name `n` is published as `roleId = n` when `n` is an `Id`, and a `roleId` + names the rate role of the same spelling. The mapping is reversible by construction; +- a name that is not an `Id` has no `roleId`. The agent refuses to initialize over a dataset + that tracks one (`INCOMPATIBLE_STATE`), rather than invent an encoding no consumer could read + back. No shipped dataset has one; +- the published list keeps the kernel's tracked-role order and its bounds: at most 64 + (`MAX_RATE_ROLES`, the kernel's role bitmask) and unique. On `fafb-v783` it is 45 roles. + +`gameboy::rate_role_id`, `rate_role_name` and `rate_role_ids` in `fly-session-types`, and +`rateRoleId`, `rateRoleName` and `rateRoleIds` in `@flybrain/session-types`, implement it. +`fixtures/gameboy-rate-roles.json` holds both languages to the same accepted and refused names and +records the FAFB tracked list, which `fly-session`'s gated FAFB test recomputes from the +committed dataset. The mapping changes no schema, digest or fixture digest. + +**Amendment, 2026-09-23 (AGENT-01): what the legacy agent reports and captures.** These are +agent-adapter choices that the sections above leave open. `LegacyAgentWorker` +(`fly-session/src/legacy_agent.rs`) implements them: + +- *Seed.* The kernel version `lif-1ms-f64-v2` hashes the LIF seed. Every seed except the legacy + default `22222` gives a different kernel version, so the profile pins the seed. + `Agent.Initialize` refuses any other seed (`INCOMPATIBLE_STATE`) before it builds a model. The + coordinator of this composition passes `22222`. It does not use a seed derived under + [seed-derivation-v1](seed-derivation-v1.md). +- *Learning telemetry.* `AgentTelemetry.learning` requires `changed <= updates`. The legacy + counters mean something else, so they map as follows. `updates` is the number of reinforcement + calls the agent has applied: one per commit while the rule is enabled, zero sums included. + `changed` is the legacy `plasticity.updates`: the reinforcements that moved at least one gain. + `signal` is `plasticity.signal`. The legacy per-synapse count (`LearningStats.changed`, the + gains away from 1.0) is not carried. It can still be read from a captured state. + `stimulusRemainingMs` is the network's `reward_remaining` after the operation. + *Amended 2026-09-29 (AGENT-01 rebase):* `FLYSIM01` records `plasticity.updates` but not the + reinforcement calls. An agent imported from a `FLYSIM01` agent state therefore starts + `updates` at that state's `plasticity.updates`, which is a lower bound on the calls made. Starting + it at zero makes the first telemetry violate `changed <= updates`: on the live fly `changed` is + in the thousands. `legacy_parity::legacy_reinforcements` is the rule. The import that ENV-01 + or STATE-01 ships must apply it. +- *Spikes.* Each `Agent.Commit` reply carries the attachment `telemetry.spikes`, with content type + `application/x-fly-spike-bitset`. It uses the legacy feed's layout: bit *i* is neuron *i*, + `ceil(neurons/8)` bytes. It covers the transition's ticks: a neuron is set when its last spike + is at or after the brain time before that transition's Prepare ticked. The mapping of bit + *i* is the graph's `indexDigest`. +- *Graph.* `datasetDigest` is the SHA-256 of the schema-1 fingerprint string. `indexDigest` is the + SHA-256 of `fly-session/legacy-agent-index-v1`, the fingerprint, the neuron count and every + `macro_*` population's members. The macro populations are the profile's declared + `macro-roles-outside-fingerprint` exception. Two datasets that relabel them differently + therefore get the same fingerprint and different index digests. +- *Initialize.* The readout transient starts as it does in a fresh legacy process: no held + channel, no last location, and a blocked window from 0 ms. `initialDecisionContext.location` + is **not** taken as the last location. The legacy loop reads a location only at the end of a + frame, so the window first restarts on it at the first commit, as it does in the legacy loop. +- *Capture.* The `State.Capture` payload is a `flybrain-core` checkpoint envelope with magic + `FLYAGT01`. Its manifest and chunks are exactly `agent_to_chunks`, with the frame remainder + taken from the session accumulator, as `Sim::checkpoint` does. It adds one `session` member: the + accumulator, the context, the profile, the seed, the reinforcement count, the macro channels + and the decoder configuration digest. It does not carry the readout transient (section 14). It + is not FLYSIM01. Writing a FLYSIM01 export from it and from the environment's state is still + STATE-01/ENV-01 work (section 16). +- *Restore.* `State.StageRestore` builds a replacement network over the same dataset, imports + the state and refuses any mismatch between the state's clock and the accumulator. + `ActivateRestore` then installs the state and resets the readout transient, as a fresh legacy + process does. The visual drive is the restored `visualDrive` chunk. Legacy `try_restore` + instead re-projects the saved framebuffer, and the two are the same values (the parity + harness compares the full state after a restore). +- *Decision.* `macro` is the first channel in the context's `bound` order that the decode holds. + This is the channel the legacy macro layer's `asked` would start. + ## 14. Restore `legacy-transient-reset` The legacy composition declares that a restore (a FLYSIM01 load today, and any group restore diff --git a/packages/session-types/src/gameboy.ts b/packages/session-types/src/gameboy.ts index 261e708..ec44ba5 100644 --- a/packages/session-types/src/gameboy.ts +++ b/packages/session-types/src/gameboy.ts @@ -14,8 +14,8 @@ import { digestOf, fail } from './canonical'; import { readRational, readSchemaRef } from './common'; import { Reader, readArtifactRef, requireUnique, u64 } from './reader'; import type { ArtifactRef, Digest, Id, RationalNs, SchemaRef, TypedValue } from './scalar'; -import { isDigest } from './scalar'; -import { type AssetRef, readAssetRef } from './workers'; +import { isDigest, isId } from './scalar'; +import { type AssetRef, MAX_RATE_ROLES, readAssetRef } from './workers'; import { MAX_SLOTS, ROLLBACK_POLICY, SLOTS_CAPABILITY } from './extensions'; export const PROFILE_ID = 'gameboy-legacy-fafb-v783-v1'; @@ -93,7 +93,10 @@ export const PAYLOAD_SCHEMAS: readonly SchemaRef[] = [ /** The legacy profile document's AssetRef digest: SHA-256 of its canonical JSON. */ export const PROFILE_DIGEST = '41e5d1ac62ab23f1b2d7252d52faac08b269c85e6b4c9ed7a370c74032c60878'; -/** `ChannelName`: a decoder channel or rate-role name. Not an Id: legacy names carry '_'. */ +/** + * `ChannelName`: a decoder channel or rate-role name, `^[a-z][a-z0-9_]{0,63}$`. A subset of the + * `Id` grammar (which admits '_'); see `rateRoleId` below (amendment 2026-09-23). + */ export function isChannelName(value: unknown): value is string { return typeof value === 'string' && /^[a-z][a-z0-9_]{0,63}$/.test(value); } @@ -558,3 +561,40 @@ export function decoderConfigForm(config: DecoderConfigLike): unknown { export function decoderConfigDigest(config: DecoderConfigLike): Digest { return digestOf(decoderConfigForm(config)); } + +// Rate roles: legacy-rate-role-id-v1 (amendment 2026-09-23, AGENT-01) ---------------------- + +/** + * The mapping from a legacy rate-role name to `AgentGraph.rateRoles` / `rates[].roleId`. + * + * The contract left it open on the premise that `command_0`, `macro_go_item` and the rest are + * not `Id`s; they are, because the `Id` grammar `^[a-z0-9][a-z0-9._-]{0,63}$` admits '_'. So the + * mapping is the identity on the `Id` grammar and a name outside it has no roleId: the agent + * refuses such a dataset. `fly-session-types/src/gameboy.rs` is the twin and + * `fixtures/gameboy-rate-roles.json` holds both to it. + */ +export const RATE_ROLE_MAPPING = 'legacy-rate-role-id-v1'; + +/** The roleId of a legacy rate-role name: the name itself, when it is an Id. */ +export function rateRoleId(name: string): Id { + if (!isId(name)) { + fail(`${RATE_ROLE_MAPPING}: rate role ${JSON.stringify(name)} is not an Id and has no roleId`); + } + return name; +} + +/** The legacy rate-role name a roleId stands for: the inverse of `rateRoleId`. */ +export function rateRoleName(roleId: string): string { + if (!isId(roleId)) fail(`${RATE_ROLE_MAPPING}: ${JSON.stringify(roleId)} is not a roleId`); + return roleId; +} + +/** Maps a tracked-role list in order, holding it to `AgentGraph.rateRoles`' bounds. */ +export function rateRoleIds(names: readonly string[]): Id[] { + const ids = names.map(rateRoleId); + if (ids.length > MAX_RATE_ROLES) { + fail(`${RATE_ROLE_MAPPING}: ${ids.length} tracked rate roles; AgentGraph.rateRoles holds at most ${MAX_RATE_ROLES}`); + } + requireUnique(ids, 'rateRoles'); + return ids; +} diff --git a/packages/session-types/tests/gameboy.test.ts b/packages/session-types/tests/gameboy.test.ts index b92ebd9..a5cadea 100644 --- a/packages/session-types/tests/gameboy.test.ts +++ b/packages/session-types/tests/gameboy.test.ts @@ -174,3 +174,24 @@ test('the decoderConfigDigest vectors are what the TypeScript oracle preset comp assert.equal(example.decoderConfigDigest, cases[1]!.digest); assert.deepEqual(example.executor.macroChannels, cases[1]!.macroChannels); }); + +test('legacy-rate-role-id-v1 is the identity on the Id grammar and refuses the rest', () => { + const file = fixtures.load('gameboy-rate-roles.json') as Record; + assert.equal(file.mapping, gameboy.RATE_ROLE_MAPPING); + assert.ok(file.accepted.length > 0); + for (const { name, roleId } of file.accepted as { name: string; roleId: string }[]) { + assert.equal(gameboy.rateRoleId(name), roleId, name); + assert.equal(gameboy.rateRoleName(roleId), name, `${roleId} maps back`); + } + for (const { name } of file.refused as { name: string }[]) { + assert.throws(() => gameboy.rateRoleId(name), `${JSON.stringify(name)} has no roleId`); + assert.throws(() => gameboy.rateRoleName(name)); + } + const tracked = file.fafbTrackedRoles as string[]; + assert.deepEqual(gameboy.rateRoleIds(tracked), tracked); + for (const role of tracked.filter((r) => r.startsWith('macro_'))) { + assert.ok(gameboy.isChannelName(role)); + } + assert.throws(() => gameboy.rateRoleIds(Array.from({ length: 65 }, (_, i) => `role_${i}`))); + assert.throws(() => gameboy.rateRoleIds(['command_0', 'command_0'])); +}); diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index 25f88d6..90899cb 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -439,7 +439,9 @@ dependencies = [ name = "fly-session" version = "0.1.1" dependencies = [ + "flate2", "fly-session-types", + "flybrain-core", "flybus", "serde_json", "tempfile", @@ -500,6 +502,7 @@ dependencies = [ "anyhow", "axum", "clap", + "fly-session", "fly-session-types", "flybrain-core", "flybrain-gb", diff --git a/services/flysim/crates/fly-session-types/fixtures/gameboy-rate-roles.json b/services/flysim/crates/fly-session-types/fixtures/gameboy-rate-roles.json new file mode 100644 index 0000000..b562ecb --- /dev/null +++ b/services/flysim/crates/fly-session-types/fixtures/gameboy-rate-roles.json @@ -0,0 +1,332 @@ +{ + "description": "legacy-rate-role-id-v1 (legacy-gameboy-v1 section 13, amendment 2026-09-23, AGENT-01): the roleId of a legacy rate-role name is the name itself when it matches the session Id grammar, and a name outside it has no roleId. fafbTrackedRoles is the rate-role list the kernel tracks on data/fafb-v783 in network order (AgentGraph.rateRoles order); fly-session's gated test recomputes it from the committed dataset. Both languages must map every accepted name to itself and back, and refuse every refused name.", + "mapping": "legacy-rate-role-id-v1", + "idPattern": "^[a-z0-9][a-z0-9._-]{0,63}$", + "fafbTrackedRoles": [ + "backward", + "command_0", + "command_1", + "command_2", + "command_3", + "command_4", + "command_5", + "command_6", + "command_7", + "forward", + "proboscis", + "reward_pam", + "steer_left", + "steer_right", + "macro_go_objective", + "macro_go_out", + "macro_go_warp", + "macro_go_route", + "macro_go_item", + "macro_go_npc", + "macro_go_frontier", + "macro_go_shop", + "macro_go_heal", + "macro_talk", + "macro_menu", + "macro_next", + "macro_yes", + "macro_no", + "macro_close", + "macro_confirm", + "macro_back", + "macro_move_1", + "macro_move_2", + "macro_move_3", + "macro_move_4", + "macro_switch", + "macro_item", + "macro_throw_ball", + "macro_run", + "macro_buy_potion", + "macro_buy_ball", + "macro_buy_antidote", + "macro_buy_repel", + "macro_heal", + "macro_leave" + ], + "accepted": [ + { + "name": "backward", + "roleId": "backward" + }, + { + "name": "command_0", + "roleId": "command_0" + }, + { + "name": "command_1", + "roleId": "command_1" + }, + { + "name": "command_2", + "roleId": "command_2" + }, + { + "name": "command_3", + "roleId": "command_3" + }, + { + "name": "command_4", + "roleId": "command_4" + }, + { + "name": "command_5", + "roleId": "command_5" + }, + { + "name": "command_6", + "roleId": "command_6" + }, + { + "name": "command_7", + "roleId": "command_7" + }, + { + "name": "forward", + "roleId": "forward" + }, + { + "name": "proboscis", + "roleId": "proboscis" + }, + { + "name": "reward_pam", + "roleId": "reward_pam" + }, + { + "name": "steer_left", + "roleId": "steer_left" + }, + { + "name": "steer_right", + "roleId": "steer_right" + }, + { + "name": "macro_go_objective", + "roleId": "macro_go_objective" + }, + { + "name": "macro_go_out", + "roleId": "macro_go_out" + }, + { + "name": "macro_go_warp", + "roleId": "macro_go_warp" + }, + { + "name": "macro_go_route", + "roleId": "macro_go_route" + }, + { + "name": "macro_go_item", + "roleId": "macro_go_item" + }, + { + "name": "macro_go_npc", + "roleId": "macro_go_npc" + }, + { + "name": "macro_go_frontier", + "roleId": "macro_go_frontier" + }, + { + "name": "macro_go_shop", + "roleId": "macro_go_shop" + }, + { + "name": "macro_go_heal", + "roleId": "macro_go_heal" + }, + { + "name": "macro_talk", + "roleId": "macro_talk" + }, + { + "name": "macro_menu", + "roleId": "macro_menu" + }, + { + "name": "macro_next", + "roleId": "macro_next" + }, + { + "name": "macro_yes", + "roleId": "macro_yes" + }, + { + "name": "macro_no", + "roleId": "macro_no" + }, + { + "name": "macro_close", + "roleId": "macro_close" + }, + { + "name": "macro_confirm", + "roleId": "macro_confirm" + }, + { + "name": "macro_back", + "roleId": "macro_back" + }, + { + "name": "macro_move_1", + "roleId": "macro_move_1" + }, + { + "name": "macro_move_2", + "roleId": "macro_move_2" + }, + { + "name": "macro_move_3", + "roleId": "macro_move_3" + }, + { + "name": "macro_move_4", + "roleId": "macro_move_4" + }, + { + "name": "macro_switch", + "roleId": "macro_switch" + }, + { + "name": "macro_item", + "roleId": "macro_item" + }, + { + "name": "macro_throw_ball", + "roleId": "macro_throw_ball" + }, + { + "name": "macro_run", + "roleId": "macro_run" + }, + { + "name": "macro_buy_potion", + "roleId": "macro_buy_potion" + }, + { + "name": "macro_buy_ball", + "roleId": "macro_buy_ball" + }, + { + "name": "macro_buy_antidote", + "roleId": "macro_buy_antidote" + }, + { + "name": "macro_buy_repel", + "roleId": "macro_buy_repel" + }, + { + "name": "macro_heal", + "roleId": "macro_heal" + }, + { + "name": "macro_leave", + "roleId": "macro_leave" + }, + { + "name": "up", + "roleId": "up" + }, + { + "name": "down", + "roleId": "down" + }, + { + "name": "left", + "roleId": "left" + }, + { + "name": "right", + "roleId": "right" + }, + { + "name": "a", + "roleId": "a" + }, + { + "name": "b", + "roleId": "b" + }, + { + "name": "start", + "roleId": "start" + }, + { + "name": "select", + "roleId": "select" + }, + { + "name": "kenyon", + "roleId": "kenyon" + }, + { + "name": "mbon", + "roleId": "mbon" + }, + { + "name": "visual_l1", + "roleId": "visual_l1" + }, + { + "name": "descending", + "roleId": "descending" + }, + { + "name": "motor", + "roleId": "motor" + }, + { + "name": "sensory", + "roleId": "sensory" + }, + { + "name": "7th.role-x", + "roleId": "7th.role-x" + }, + { + "name": "0", + "roleId": "0" + }, + { + "name": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "roleId": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr" + } + ], + "refused": [ + { + "name": "Command_0", + "why": "uppercase" + }, + { + "name": "_command", + "why": "leading underscore" + }, + { + "name": "-x", + "why": "leading hyphen" + }, + { + "name": "", + "why": "empty" + }, + { + "name": "steer left", + "why": "space" + }, + { + "name": "macro_é", + "why": "non-ASCII" + }, + { + "name": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "why": "65 characters" + } + ] +} diff --git a/services/flysim/crates/fly-session-types/src/gameboy.rs b/services/flysim/crates/fly-session-types/src/gameboy.rs index 29e88f8..c644612 100644 --- a/services/flysim/crates/fly-session-types/src/gameboy.rs +++ b/services/flysim/crates/fly-session-types/src/gameboy.rs @@ -413,6 +413,60 @@ pub fn extension_set_digest() -> String { canonical::digest_of(&extension_set()).expect("canonicalizable") } +// --------------------------------------------------------------------------------------------- +// Rate roles: `legacy-rate-role-id-v1` (amendment 2026-09-23, AGENT-01) + +/// The name of the mapping from a legacy rate-role name to `AgentGraph.rateRoles` / +/// `AgentTelemetry.rates[].roleId`. +/// +/// `legacy-gameboy-v1` section 13 left this to AGENT-01 on the premise that the legacy names +/// (`command_0`, `macro_go_item`, `steer_left`, ...) are not `Id`s. They are: the session `Id` +/// grammar is `^[a-z0-9][a-z0-9._-]{0,63}$` (`ipc-v1` section 1), which admits `_`, and every +/// role `data/fafb-v783` declares or the kernel tracks matches it. So the mapping is the identity +/// on the `Id` grammar, trivially reversible, and a name outside the grammar is not mapped at +/// all: the agent refuses to initialize on such a dataset rather than invent an encoding that +/// no consumer could read back. `fixtures/gameboy-rate-roles.json` pins it in both languages. +pub const RATE_ROLE_MAPPING: &str = "legacy-rate-role-id-v1"; + +/// The `roleId` a legacy rate-role name is published under: the name itself, when it is an +/// `Id`. Anything else is refused. +pub fn rate_role_id(name: &str) -> Result { + if is_id(name) { + Ok(name.to_owned()) + } else { + err(format!( + "{RATE_ROLE_MAPPING}: rate role {name:?} is not an Id (^[a-z0-9][a-z0-9._-]{{0,63}}$) and has no roleId" + )) + } +} + +/// The legacy rate-role name a `roleId` stands for: the inverse of [`rate_role_id`]. +pub fn rate_role_name(role_id: &str) -> Result { + if is_id(role_id) { + Ok(role_id.to_owned()) + } else { + err(format!("{RATE_ROLE_MAPPING}: {role_id:?} is not a roleId")) + } +} + +/// Maps a tracked-role list, in order, and holds it to `AgentGraph.rateRoles`' own bounds: +/// at most 64 (`MAX_RATE_ROLES`, the kernel's role bitmask) and unique. +pub fn rate_role_ids<'a>(names: impl IntoIterator) -> Result> { + let ids = names + .into_iter() + .map(rate_role_id) + .collect::>>()?; + if ids.len() > crate::workers::MAX_RATE_ROLES { + return err(format!( + "{RATE_ROLE_MAPPING}: {} tracked rate roles; AgentGraph.rateRoles holds at most {}", + ids.len(), + crate::workers::MAX_RATE_ROLES + )); + } + require_unique(ids.iter().map(String::as_str), "rateRoles")?; + Ok(ids) +} + // --------------------------------------------------------------------------------------------- // Scalars and helpers diff --git a/services/flysim/crates/fly-session-types/tests/gameboy_legacy.rs b/services/flysim/crates/fly-session-types/tests/gameboy_legacy.rs index c305f29..659fee7 100644 --- a/services/flysim/crates/fly-session-types/tests/gameboy_legacy.rs +++ b/services/flysim/crates/fly-session-types/tests/gameboy_legacy.rs @@ -348,3 +348,44 @@ fn the_extension_methods_check_their_scope() { assert_eq!(SLOTS_CAPABILITY, "gameboy-slots-v1"); assert_eq!(ROLLBACK_CAPABILITY, ROLLBACK_POLICY); } + +/// `legacy-rate-role-id-v1`: every accepted name is its own roleId and maps back; every refused +/// name has none. The TypeScript twin reads the same file. +#[test] +fn the_rate_role_mapping_is_the_identity_on_the_id_grammar_and_refuses_the_rest() { + let file = fixtures::load("gameboy-rate-roles.json").expect("gameboy-rate-roles.json"); + assert_eq!(file["mapping"].as_str(), Some(gameboy::RATE_ROLE_MAPPING)); + let accepted = file["accepted"].as_array().expect("accepted"); + assert!(!accepted.is_empty()); + for case in accepted { + let name = case["name"].as_str().expect("name"); + let role_id = case["roleId"].as_str().expect("roleId"); + assert_eq!(gameboy::rate_role_id(name).expect(name), role_id, "{name}"); + assert_eq!(gameboy::rate_role_name(role_id).expect(role_id), name, "{role_id} maps back"); + } + for case in file["refused"].as_array().expect("refused") { + let name = case["name"].as_str().expect("name"); + assert!(gameboy::rate_role_id(name).is_err(), "{name:?} must have no roleId"); + assert!(gameboy::rate_role_name(name).is_err(), "{name:?} is no roleId either"); + } + // The FAFB tracked list fits AgentGraph.rateRoles as it stands: <= 64, unique, in order. + let tracked: Vec<&str> = file["fafbTrackedRoles"] + .as_array() + .expect("fafbTrackedRoles") + .iter() + .map(|v| v.as_str().expect("a role name")) + .collect(); + let ids = gameboy::rate_role_ids(tracked.iter().copied()).expect("the FAFB roles map"); + assert_eq!(ids, tracked); + // Every decoder channel is a ChannelName, and every ChannelName is an Id, so a macro + // channel's role is its own roleId too. + for role in &tracked { + if role.starts_with("macro_") { + assert!(gameboy::is_channel_name(role)); + } + } + // The list bound and uniqueness are the contract's, not the mapping's convenience. + let many: Vec = (0..65).map(|i| format!("role_{i}")).collect(); + assert!(gameboy::rate_role_ids(many.iter().map(String::as_str)).is_err()); + assert!(gameboy::rate_role_ids(["command_0", "command_0"]).is_err()); +} diff --git a/services/flysim/crates/fly-session/Cargo.toml b/services/flysim/crates/fly-session/Cargo.toml index 25d9a76..9be8436 100644 --- a/services/flysim/crates/fly-session/Cargo.toml +++ b/services/flysim/crates/fly-session/Cargo.toml @@ -23,6 +23,11 @@ path = "src/bin/fly-session.rs" # Everything else this crate needs is std or Tokio. fly-session-types = { path = "../fly-session-types" } flybus = { path = "../flybus" } +# AGENT-01: the legacy agent worker is an adapter over the existing neural core (LIF kernel, +# plasticity, retina, fixed readout, checkpoint chunks). Pure Rust, no emulator. +flybrain-core = { path = "../flybrain-core" } +# The toy connectome fixture is written as gzipped `.binz` arrays, the dataset loader's format. +flate2 = { workspace = true } serde_json = { workspace = true } # `rt-multi-thread` is not only for the tests: a worker process and a dedicated-thread diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/circuit-roles.json b/services/flysim/crates/fly-session/fixtures/legacy-toy/circuit-roles.json new file mode 100644 index 0000000..8bac168 --- /dev/null +++ b/services/flysim/crates/fly-session/fixtures/legacy-toy/circuit-roles.json @@ -0,0 +1 @@ +{"neurons":4096,"roles":{"kenyon":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,893,894,895,896,897,898,899,900,901,902,903,904,905,906,907,908,909,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999,1000,1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1011,1012,1013,1014,1015,1016,1017,1018,1019,1020,1021,1022,1023],"mbon":[1024,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131,1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147,1148,1149,1150,1151,1152,1153,1154,1155,1156,1157,1158,1159,1160,1161,1162,1163,1164,1165,1166,1167,1168,1169,1170,1171,1172,1173,1174,1175,1176,1177,1178,1179,1180,1181,1182,1183,1184,1185,1186,1187,1188,1189,1190,1191,1192,1193,1194,1195,1196,1197,1198,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229,1230,1231,1232,1233,1234,1235,1236,1237,1238,1239,1240,1241,1242,1243,1244,1245,1246,1247,1248,1249,1250,1251,1252,1253,1254,1255,1256,1257,1258,1259,1260,1261,1262,1263,1264,1265,1266,1267,1268,1269,1270,1271,1272,1273,1274,1275,1276,1277,1278,1279],"macro_go_out":[1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115],"macro_talk":[1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131],"macro_menu":[1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147],"macro_next":[1148,1149,1150,1151,1152,1153,1154,1155,1156,1157,1158,1159,1160,1161,1162,1163]}} diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/indptr.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/indptr.binz new file mode 100644 index 0000000..41935a3 Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/indptr.binz differ diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/meta.json b/services/flysim/crates/fly-session/fixtures/legacy-toy/meta.json new file mode 100644 index 0000000..ce8f896 --- /dev/null +++ b/services/flysim/crates/fly-session/fixtures/legacy-toy/meta.json @@ -0,0 +1 @@ +{"schemaVersion":1,"dataset":"legacy-toy","neurons":4096,"edges":40960,"roles":{"command_0":[1344,1345,1346,1347,1348,1349,1350,1351,1352,1353,1354,1355,1356,1357,1358,1359,1360,1361,1362,1363,1364,1365,1366,1367,1368,1369,1370,1371,1372,1373,1374,1375],"command_1":[1376,1377,1378,1379,1380,1381,1382,1383,1384,1385,1386,1387,1388,1389,1390,1391,1392,1393,1394,1395,1396,1397,1398,1399,1400,1401,1402,1403,1404,1405,1406,1407],"command_2":[1408,1409,1410,1411,1412,1413,1414,1415,1416,1417,1418,1419,1420,1421,1422,1423,1424,1425,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439],"command_3":[1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1470,1471],"command_4":[1472,1473,1474,1475,1476,1477,1478,1479,1480,1481,1482,1483,1484,1485,1486,1487,1488,1489,1490,1491,1492,1493,1494,1495,1496,1497,1498,1499,1500,1501,1502,1503],"command_5":[1504,1505,1506,1507,1508,1509,1510,1511,1512,1513,1514,1515,1516,1517,1518,1519,1520,1521,1522,1523,1524,1525,1526,1527,1528,1529,1530,1531,1532,1533,1534,1535],"command_6":[1536,1537,1538,1539,1540,1541,1542,1543,1544,1545,1546,1547,1548,1549,1550,1551,1552,1553,1554,1555,1556,1557,1558,1559,1560,1561,1562,1563,1564,1565,1566,1567],"command_7":[1568,1569,1570,1571,1572,1573,1574,1575,1576,1577,1578,1579,1580,1581,1582,1583,1584,1585,1586,1587,1588,1589,1590,1591,1592,1593,1594,1595,1596,1597,1598,1599],"reward_pam":[1280,1281,1282,1283,1284,1285,1286,1287,1288,1289,1290,1291,1292,1293,1294,1295,1296,1297,1298,1299,1300,1301,1302,1303,1304,1305,1306,1307,1308,1309,1310,1311,1312,1313,1314,1315,1316,1317,1318,1319,1320,1321,1322,1323,1324,1325,1326,1327,1328,1329,1330,1331,1332,1333,1334,1335,1336,1337,1338,1339,1340,1341,1342,1343],"steer_left":[2400,2401,2402,2403,2404,2405,2406,2407,2408,2409,2410,2411,2412,2413,2414,2415,2416,2417,2418,2419,2420,2421,2422,2423,2424,2425,2426,2427,2428,2429,2430,2431],"steer_right":[2432,2433,2434,2435,2436,2437,2438,2439,2440,2441,2442,2443,2444,2445,2446,2447,2448,2449,2450,2451,2452,2453,2454,2455,2456,2457,2458,2459,2460,2461,2462,2463],"visual_l1":[1600,1601,1602,1603,1604,1605,1606,1607,1608,1609,1610,1611,1612,1613,1614,1615,1616,1617,1618,1619,1620,1621,1622,1623,1624,1625,1626,1627,1628,1629,1630,1631,1632,1633,1634,1635,1636,1637,1638,1639,1640,1641,1642,1643,1644,1645,1646,1647,1648,1649,1650,1651,1652,1653,1654,1655,1656,1657,1658,1659,1660,1661,1662,1663,1664,1665,1666,1667,1668,1669,1670,1671,1672,1673,1674,1675,1676,1677,1678,1679,1680,1681,1682,1683,1684,1685,1686,1687,1688,1689,1690,1691,1692,1693,1694,1695,1696,1697,1698,1699,1700,1701,1702,1703,1704,1705,1706,1707,1708,1709,1710,1711,1712,1713,1714,1715,1716,1717,1718,1719,1720,1721,1722,1723,1724,1725,1726,1727,1728,1729,1730,1731,1732,1733,1734,1735,1736,1737,1738,1739,1740,1741,1742,1743,1744,1745,1746,1747,1748,1749,1750,1751,1752,1753,1754,1755,1756,1757,1758,1759,1760,1761,1762,1763,1764,1765,1766,1767,1768,1769,1770,1771,1772,1773,1774,1775,1776,1777,1778,1779,1780,1781,1782,1783,1784,1785,1786,1787,1788,1789,1790,1791,1792,1793,1794,1795,1796,1797,1798,1799,1800,1801,1802,1803,1804,1805,1806,1807,1808,1809,1810,1811,1812,1813,1814,1815,1816,1817,1818,1819,1820,1821,1822,1823,1824,1825,1826,1827,1828,1829,1830,1831,1832,1833,1834,1835,1836,1837,1838,1839,1840,1841,1842,1843,1844,1845,1846,1847,1848,1849,1850,1851,1852,1853,1854,1855,1856,1857,1858,1859,1860,1861,1862,1863,1864,1865,1866,1867,1868,1869,1870,1871,1872,1873,1874,1875,1876,1877,1878,1879,1880,1881,1882,1883,1884,1885,1886,1887,1888,1889,1890,1891,1892,1893,1894,1895,1896,1897,1898,1899,1900,1901,1902,1903,1904,1905,1906,1907,1908,1909,1910,1911,1912,1913,1914,1915,1916,1917,1918,1919,1920,1921,1922,1923,1924,1925,1926,1927,1928,1929,1930,1931,1932,1933,1934,1935,1936,1937,1938,1939,1940,1941,1942,1943,1944,1945,1946,1947,1948,1949,1950,1951,1952,1953,1954,1955,1956,1957,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1968,1969,1970,1971,1972,1973,1974,1975,1976,1977,1978,1979,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022,2023,2024,2025,2026,2027,2028,2029,2030,2031,2032,2033,2034,2035,2036,2037,2038,2039,2040,2041,2042,2043,2044,2045,2046,2047,2048,2049,2050,2051,2052,2053,2054,2055,2056,2057,2058,2059,2060,2061,2062,2063,2064,2065,2066,2067,2068,2069,2070,2071,2072,2073,2074,2075,2076,2077,2078,2079,2080,2081,2082,2083,2084,2085,2086,2087,2088,2089,2090,2091,2092,2093,2094,2095,2096,2097,2098,2099,2100,2101,2102,2103,2104,2105,2106,2107,2108,2109,2110,2111,2112,2113,2114,2115,2116,2117,2118,2119,2120,2121,2122,2123,2124,2125,2126,2127,2128,2129,2130,2131,2132,2133,2134,2135,2136,2137,2138,2139,2140,2141,2142,2143,2144,2145,2146,2147,2148,2149,2150,2151,2152,2153,2154,2155,2156,2157,2158,2159,2160,2161,2162,2163,2164,2165,2166,2167,2168,2169,2170,2171,2172,2173,2174,2175,2176,2177,2178,2179,2180,2181,2182,2183,2184,2185,2186,2187,2188,2189,2190,2191,2192,2193,2194,2195,2196,2197,2198,2199,2200,2201,2202,2203,2204,2205,2206,2207,2208,2209,2210,2211,2212,2213,2214,2215,2216,2217,2218,2219,2220,2221,2222,2223,2224,2225,2226,2227,2228,2229,2230,2231,2232,2233,2234,2235,2236,2237,2238,2239,2240,2241,2242,2243,2244,2245,2246,2247,2248,2249,2250,2251,2252,2253,2254,2255,2256,2257,2258,2259,2260,2261,2262,2263,2264,2265,2266,2267,2268,2269,2270,2271,2272,2273,2274,2275,2276,2277,2278,2279,2280,2281,2282,2283,2284,2285,2286,2287,2288,2289,2290,2291,2292,2293,2294,2295,2296,2297,2298,2299,2300,2301,2302,2303,2304,2305,2306,2307,2308,2309,2310,2311,2312,2313,2314,2315,2316,2317,2318,2319,2320,2321,2322,2323,2324,2325,2326,2327,2328,2329,2330,2331,2332,2333,2334,2335,2336,2337,2338,2339,2340,2341,2342,2343,2344,2345,2346,2347,2348,2349,2350,2351,2352,2353,2354,2355,2356,2357,2358,2359,2360,2361,2362,2363,2364,2365,2366,2367,2368,2369,2370,2371,2372,2373,2374,2375,2376,2377,2378,2379,2380,2381,2382,2383,2384,2385,2386,2387,2388,2389,2390,2391,2392,2393,2394,2395,2396,2397,2398,2399]},"visual":{"population":"toy-retina","count":800}} diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/targets.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/targets.binz new file mode 100644 index 0000000..84d574d Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/targets.binz differ diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-hemisphere.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-hemisphere.binz new file mode 100644 index 0000000..4203e09 Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-hemisphere.binz differ diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-indices.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-indices.binz new file mode 100644 index 0000000..1c50f0e Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-indices.binz differ diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-xy.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-xy.binz new file mode 100644 index 0000000..feb31e6 Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/visual-xy.binz differ diff --git a/services/flysim/crates/fly-session/fixtures/legacy-toy/weights.binz b/services/flysim/crates/fly-session/fixtures/legacy-toy/weights.binz new file mode 100644 index 0000000..c148f83 Binary files /dev/null and b/services/flysim/crates/fly-session/fixtures/legacy-toy/weights.binz differ diff --git a/services/flysim/crates/fly-session/fixtures/toy-macros.golden.json b/services/flysim/crates/fly-session/fixtures/toy-macros.golden.json new file mode 100644 index 0000000..ddb6a66 --- /dev/null +++ b/services/flysim/crates/fly-session/fixtures/toy-macros.golden.json @@ -0,0 +1,276 @@ +{ + "scenario": "toy-macros", + "macroChannels": [ + "macro_go_out", + "macro_talk", + "macro_menu", + "macro_next" + ], + "records": 263, + "digest": "5139fb8a99c6503ac2315f5a5ed754a6054e6eb8068acdd2b649931ccd40a02f", + "rows": [ + "0 initialize b0 t2500 bt2500 m-- - p0 d676a54ce95aef0e", + "1 frame b1 t16 bt2516 m61 - p0 42a0dfdbf7fe8f55", + "2 frame b2 t17 bt2533 m61 - p0 bc0b415d8f485283", + "3 frame b3 t17 bt2550 m71 - p0 b953d63ad5548f84", + "4 frame b4 t16 bt2566 m71 - p0 5c6d3fef3c75b7e0", + "5 frame b5 t17 bt2583 m31 - p0 81b637fc70c20259", + "6 frame b6 t17 bt2600 m31 - p0 94e77ebf0653ed58", + "7 frame b7 t17 bt2617 m11 - p0 e9dc82d6837e1251", + "8 frame b8 t16 bt2633 m11 - p0 0997f4d5d11c3b28", + "9 frame b9 t17 bt2650 m01 - p0 ba71c1d68725ebd8", + "10 frame b10 t17 bt2667 m01 - p0 eb276406234e10c3", + "11 frame b11 t17 bt2684 m01 - p0 f51fa31f018683e7", + "12 frame b12 t16 bt2700 m01 - p0 91bfe963a2c0b0a4", + "13 frame b13 t17 bt2717 m01 - p0 6cb4d3b49ec11d37", + "14 frame b14 t17 bt2734 m01 - p0 7fb10c988bdfaafa", + "15 frame b15 t17 bt2751 m01 - p0 0277076d6c3855b1", + "16 frame b16 t16 bt2767 m01 - p0 f6b44b410581a903", + "17 frame b17 t17 bt2784 m01 - p120 5d5605f21806a2e8", + "18 frame b18 t17 bt2801 m01 - p103 e19f8f734ab1f79b", + "19 frame b19 t17 bt2818 m01 - p86 08c3045b0edda21d", + "20 frame b20 t16 bt2834 m01 - p70 70183eb4539388c6", + "21 frame b21 t17 bt2851 m01 - p53 ee10901597a34ff7", + "22 frame b22 t17 bt2868 m01 - p36 083b83cf159f8210", + "23 frame b23 t17 bt2885 m01 - p19 8e145a0fbe7439c6", + "24 frame b24 t16 bt2901 m01 - p3 b78dce0e1c9a4943", + "25 frame b25 t17 bt2918 m01 - p283 dfb93db9b8f19e8d", + "26 frame b26 t17 bt2935 m01 - p266 0c06868a06292d58", + "27 frame b27 t17 bt2952 m01 - p249 db4407e92950062d", + "28 frame b28 t16 bt2968 m01 - p233 c1eb8900546ebae6", + "29 frame b29 t17 bt2985 m01 - p216 0713b6bacce29e09", + "30 frame b30 t17 bt3002 m21 - p199 9e9fdbd1da35dddf", + "31 frame b31 t17 bt3019 m21 - p182 a67b8a9886ed6406", + "32 frame b32 t16 bt3035 m31 - p166 5de0bb3548fa8221", + "33 frame b33 t17 bt3052 m31 - p149 e443c6858ccfeefd", + "34 frame b34 t17 bt3069 m31 - p132 aad26ee01fcd8305", + "35 frame b35 t16 bt3085 m31 - p116 cbccd5cba4cf7428", + "36 frame b36 t17 bt3102 m11 - p99 2cb0a9bb493b3125", + "37 frame b37 t17 bt3119 m11 - p82 2c7d70fcdcfe1837", + "38 frame b38 t17 bt3136 m01 - p65 fbf14295f4fe432d", + "39 frame b39 t16 bt3152 m01 - p49 451f9f5b82706d20", + "40 frame b40 t17 bt3169 m01 - p32 683611e4e6578d1a state", + "41 frame b41 t17 bt3186 m01 - p15 83171b3ea9a7ea1e", + "42 frame b42 t17 bt3203 m01 - p0 05132a48c701a11b", + "43 frame b43 t16 bt3219 m01 - p0 32f1b389f783cfea", + "44 frame b44 t17 bt3236 m01 - p0 4399da53e142a8f7", + "45 frame b45 t17 bt3253 m01 - p0 83549f68a27e4a9f", + "46 frame b46 t17 bt3270 m01 - p0 8694cd49107aed69", + "47 frame b47 t16 bt3286 m01 - p0 b25ba2454528cca3", + "48 frame b48 t17 bt3303 m01 - p0 2623228af9f21266", + "49 frame b49 t17 bt3320 m02 - p0 6c82e578ef54c4c6", + "50 frame b50 t17 bt3337 m02 - p200 fa26f4f2b6e85a66", + "51 frame b51 t16 bt3353 m02 - p184 a6519d51e6a73409", + "52 frame b52 t17 bt3370 m02 - p167 804482d83c7ab25c", + "53 frame b53 t17 bt3387 m02 - p150 470afd9213bc9c69", + "54 frame b54 t17 bt3404 m02 - p133 672eb341bbee0c13", + "55 frame b55 t16 bt3420 m02 - p117 c6fdf33189fdb90a", + "56 frame b56 t17 bt3437 m02 - p100 a8b9177d330a06e1", + "57 frame b57 t17 bt3454 m02 - p83 0a96ab3adaf4ad87", + "58 frame b58 t17 bt3471 m02 - p66 89a10bb29ad693b6", + "59 frame b59 t16 bt3487 m22 - p50 d21f628e694c9a30", + "60 frame b60 t17 bt3504 m22 - p33 1a90f7e1f39f8a9d", + "61 frame b61 t17 bt3521 m32 macro_go_out p16 6b4e16812d8e4f98", + "62 frame b62 t17 bt3538 m32 macro_go_out p0 6617f27084cbb4c4", + "63 frame b63 t16 bt3554 m32 macro_go_out p0 352dde16702d22e1", + "64 frame b64 t17 bt3571 m32 macro_go_out p0 f91ec167d9a58161", + "65 frame b65 t17 bt3588 m12 macro_go_out p0 e2bbebc4ae5bb7c4", + "66 frame b66 t17 bt3605 m12 macro_go_out p0 71c1ebb6dfd44c1d", + "67 frame b67 t16 bt3621 m02 macro_go_out p0 6eb754b6d554ba64", + "68 frame b68 t17 bt3638 m02 macro_go_out p120 df0f4262f12a1cf7", + "69 frame b69 t17 bt3655 m02 macro_go_out p103 86c885bef55e8a76", + "70 frame b70 t16 bt3671 m02 macro_go_out p87 2de699b76b49ab85", + "71 frame b71 t17 bt3688 m02 macro_go_out p70 c73ebc28ca5f17ef", + "72 frame b72 t17 bt3705 m02 macro_go_out p53 5183a17558475ba4", + "73 frame b73 t17 bt3722 m02 macro_go_out p36 89a85c2d5f3a00dc", + "74 frame b74 t16 bt3738 m02 macro_go_out p20 504f6dca39cd12b9", + "75 frame b75 t17 bt3755 m02 macro_go_out p3 a23856ba2da98a74", + "76 frame b76 t17 bt3772 m02 macro_go_out p0 ff33e61ab59ca37e", + "77 frame b77 t17 bt3789 m02 macro_go_out p60 2e8876d54628e0da", + "78 frame b78 t16 bt3805 m02 macro_go_out p44 dbeca8ee685d0192", + "79 frame b79 t17 bt3822 m02 macro_go_out p27 3e2b6d875dba48c8", + "80 frame b80 t17 bt3839 m02 macro_go_out p10 31db168c0f6eef32 state", + "81 frame b81 t17 bt3856 m02 macro_go_out p0 af13492eb695dca6", + "82 frame b82 t16 bt3872 m02 macro_go_out p0 f9dca4bdd2edc20f", + "83 frame b83 t17 bt3889 m02 macro_go_out p0 19e59572d5922d09", + "84 frame b84 t17 bt3906 m02 macro_go_out p0 75e97690028f994d", + "85 frame b85 t17 bt3923 m02 macro_go_out p120 c68320e6515dd1d5", + "86 frame b86 t16 bt3939 m02 macro_go_out p104 89f1b529935223dc", + "87 frame b87 t17 bt3956 m02 macro_go_out p87 14bc1a0bbc7c9f48", + "88 frame b88 t17 bt3973 m22 macro_go_out p70 a04f92a4392e353c", + "89 frame b89 t17 bt3990 m22 macro_go_out p53 7ebb5b12ec25c397", + "90 frame b90 t16 bt4006 m32 macro_go_out p37 27ac565dda76999b", + "91 frame b91 t17 bt4023 m32 macro_go_out p20 61796a4ab7529877", + "92 frame b92 t17 bt4040 m32 macro_go_out p3 1f3dbcc2c303ff24", + "93 frame b93 t17 bt4057 m32 macro_go_out p0 84de4dd82b9054d6", + "94 frame b94 t16 bt4073 m12 macro_go_out p0 4ad0f5fe4ec4e4e8", + "95 frame b95 t17 bt4090 m12 macro_go_out p0 f3c60e6d7467e642", + "96 frame b96 t17 bt4107 m02 macro_go_out p0 f152704b374b54d2", + "97 frame b97 t17 bt4124 m08 macro_go_out p0 db6caba8900aa0f8", + "98 frame b98 t16 bt4140 m08 macro_go_out p0 750ec56c0611e86d", + "99 frame b99 t17 bt4157 m08 macro_go_out p0 20ed8618ae84ea7b", + "100 frame b100 t17 bt4174 m08 macro_go_out p0 9f3c88a1d3080276", + "101 frame b101 t17 bt4191 m08 macro_go_out p0 37f0f8de463d1ea4", + "102 frame b102 t16 bt4207 m08 macro_go_out p120 c637dc590b738a73", + "103 frame b103 t17 bt4224 m08 macro_go_out p103 acd289090f10e216", + "104 frame b104 t17 bt4241 m08 macro_go_out p86 27ff70ebeb16accd", + "105 frame b105 t16 bt4257 m08 macro_go_out p70 f6391347be381599", + "106 frame b106 t17 bt4274 m08 macro_go_out p53 dce3a6ea9772cad6", + "107 frame b107 t17 bt4291 m08 macro_go_out p36 e0c159d74b32179e", + "108 frame b108 t17 bt4308 m08 macro_go_out p19 59f328f318d4159c", + "109 frame b109 t16 bt4324 m08 macro_go_out p3 8183d6905016268b", + "110 frame b110 t17 bt4341 m08 macro_go_out p0 2e4f1cae9730fd38", + "111 frame b111 t17 bt4358 m08 macro_go_out p0 93374d1d064911e7", + "112 frame b112 t17 bt4375 m08 macro_go_out p0 3970042f6f7aeada", + "113 frame b113 t16 bt4391 m08 macro_go_out p0 453c35f7fe1df367", + "114 frame b114 t17 bt4408 m08 macro_go_out p0 84122d1a4bb5d5e4", + "115 frame b115 t17 bt4425 m08 macro_go_out p0 01155fce277003d9", + "116 frame b116 t17 bt4442 m08 macro_go_out p0 b7b1aa630e0d7422", + "117 frame b117 t16 bt4458 m28 macro_go_out p0 36283b05d8e8d580", + "118 frame b118 t17 bt4475 m28 macro_go_out p0 717afeaef5a9d808", + "119 frame b119 t17 bt4492 m38 macro_go_out p120 e3e15c15455f12ef", + "120 frame b120 t17 bt4509 m38 macro_go_out p103 25384a06ed1ab907 state", + "121 rollback b120 t0 bt4509 m-- - p103 f04a32eda0fc7403", + "122 frame b121 t16 bt4525 m08 macro_go_out p87 d07e3db7b97d3c37", + "123 frame b122 t17 bt4542 m08 macro_go_out p70 de23a79c7027df50", + "124 frame b123 t17 bt4559 m08 macro_go_out p53 f9e8c1261be94efb", + "125 frame b124 t17 bt4576 m08 macro_go_out p36 d0f1d3a30b26834b", + "126 frame b125 t16 bt4592 m08 macro_go_out p20 07a54c7f905d51b7", + "127 frame b126 t17 bt4609 m08 macro_go_out p3 4f86202774d47232", + "128 frame b127 t17 bt4626 m08 macro_go_out p0 f81252ea7dfd5cd6", + "129 frame b128 t17 bt4643 m08 macro_go_out p0 c655922ec21d8af7", + "130 frame b129 t16 bt4659 m08 macro_go_out p0 00113d916da36b19", + "131 frame b130 t17 bt4676 m08 macro_go_out p0 b29c32b34131610a", + "132 frame b131 t17 bt4693 m08 - p0 03c2ac6516de6340", + "133 frame b132 t17 bt4710 m08 - p0 0f317ebc1c7b2dfd", + "134 frame b133 t16 bt4726 m08 - p0 82c898d80cef5165", + "135 frame b134 t17 bt4743 m08 - p0 e1f447fe884f0035", + "136 frame b135 t17 bt4760 m08 - p0 03cce25fe0406708", + "137 frame b136 t17 bt4777 m08 - p120 30ab44aeb9ac184a", + "138 frame b137 t16 bt4793 m08 - p104 ecaf6653c64f1604", + "139 frame b138 t17 bt4810 m08 - p87 b660e701b0879c98", + "140 frame b139 t17 bt4827 m08 - p70 5371979c169470f3", + "141 frame b140 t16 bt4843 m08 - p54 5445a7a361444935", + "142 frame b141 t17 bt4860 m08 - p37 057f91929f6d91b4", + "143 frame b142 t17 bt4877 m08 - p20 46c238c00d482155", + "144 frame b143 t17 bt4894 m08 - p3 f0584e9063d8fc90", + "145 frame b144 t16 bt4910 m08 - p0 0b4ddd703fcf5a54", + "146 frame b145 t17 bt4927 m08 - p0 dbd0b0a86b336bfa", + "147 frame b146 t17 bt4944 m08 - p0 2e8c45f2c2c49320", + "148 frame b147 t17 bt4961 m08 - p0 63d766cee52d420c", + "149 frame b148 t16 bt4977 m08 - p0 ce85563509e81dd3", + "150 frame b149 t17 bt4994 m38 - p0 5a5ed80dd7cdd643", + "151 frame b150 t17 bt5011 m38 - p0 2c2fe0f7265f9558", + "152 frame b151 t17 bt5028 m38 - p0 a3b63cdb6fd5cdb4", + "153 frame b152 t16 bt5044 m38 - p0 3f61ef5c3aa330bb", + "154 frame b153 t17 bt5061 m38 - p120 25a4fe291121ee26", + "155 frame b154 t17 bt5078 m38 - p103 543b851caad059e1", + "156 frame b155 t17 bt5095 m08 - p86 65aa23cddd7cb9e4", + "157 frame b156 t16 bt5111 m08 - p70 51ea9900cc7266c5", + "158 frame b157 t17 bt5128 m08 - p53 5e11712fb96da006", + "159 frame b158 t17 bt5145 m08 - p36 7051c00f84b30f6b", + "160 frame b159 t17 bt5162 m08 - p19 a68b2bc24c5348ab state", + "161 frame b160 t16 bt5178 m08 - p3 0ae35caf8548b14c", + "162 frame b161 t17 bt5195 m08 - p0 1d1a3536795012c9", + "163 frame b162 t17 bt5212 m08 - p0 fdd488a6cd816ee8", + "164 frame b163 t17 bt5229 m08 - p0 847aaf2c8540f821", + "165 frame b164 t16 bt5245 m08 - p0 4d0cf08f6ad85698", + "166 frame b165 t17 bt5262 m08 - p0 fd181536e34fc9d2", + "167 frame b166 t17 bt5279 m08 - p0 4e92f250e74a306a", + "168 frame b167 t17 bt5296 m08 - p0 35d5376db498ad57", + "169 frame b168 t16 bt5312 m08 - p0 c7584d3a45a5e773", + "170 frame b169 t17 bt5329 m04 macro_talk p0 b095f08524a7fb63", + "171 frame b170 t17 bt5346 m04 macro_talk p483 0ad3bf47cf3a9a9d", + "172 frame b171 t17 bt5363 m04 macro_talk p466 38257a6752c8e9ce", + "173 frame b172 t16 bt5379 m04 macro_talk p450 b09ba9a0d5ea49f3", + "174 frame b173 t17 bt5396 m04 macro_talk p433 1ac57d8b95f38072", + "175 frame b174 t17 bt5413 m04 macro_talk p416 123bc0e305bc3745", + "176 frame b175 t16 bt5429 m04 macro_talk p400 5305ecb6f1b5e620", + "177 frame b176 t17 bt5446 m04 macro_talk p383 e495eb473a3a2803", + "178 frame b177 t17 bt5463 m04 macro_talk p366 7e018a67f3b3eb57", + "179 frame b178 t17 bt5480 m34 macro_talk p349 bcd058f091970946", + "180 frame b179 t16 bt5496 m34 macro_talk p333 25b9e2c4cd50a5fa", + "181 frame b180 t17 bt5513 m34 macro_talk p316 1512b0fb16669893", + "182 frame b181 t17 bt5530 m34 macro_talk p299 3e808e0829436112", + "183 frame b182 t17 bt5547 m34 macro_talk p282 94e9a537eaf6f5d0", + "184 frame b183 t16 bt5563 m34 macro_talk p266 bd54d070787ccd2a", + "185 frame b184 t17 bt5580 m04 macro_talk p249 1c1cd476fca4e267", + "186 frame b185 t17 bt5597 m04 macro_talk p232 9907b3274367cbf5", + "187 frame b186 t17 bt5614 m04 macro_talk p215 38e5f8b325bb16b1", + "188 frame b187 t16 bt5630 m04 macro_talk p199 fb3d645fdde535a1", + "189 frame b188 t17 bt5647 m04 macro_talk p182 7d641ad4221b0747", + "190 frame b189 t17 bt5664 m04 macro_talk p165 8856a5a3a7ea0bd0", + "191 frame b190 t17 bt5681 m04 macro_talk p148 8729465d0c93729d", + "192 restore b190 t0 bt5681 m-- - p- 8f949318d4bb63eb state", + "193 frame b191 t16 bt5697 m04 macro_talk p132 45792c108b658d08", + "194 frame b192 t17 bt5714 m04 macro_talk p115 2e86ee32ef98edcb", + "195 frame b193 t17 bt5731 m04 macro_talk p98 70133bde0d47d8ac", + "196 frame b194 t17 bt5748 m04 macro_talk p81 14aee6172d1e8f12", + "197 frame b195 t16 bt5764 m04 macro_talk p65 760f253d0b98cffc", + "198 frame b196 t17 bt5781 m04 macro_talk p48 dc2fcd053a28f245", + "199 frame b197 t17 bt5798 m04 macro_talk p31 1838d2ac9c5a10b1", + "200 frame b198 t17 bt5815 m04 macro_talk p14 c92a4879ba2b7755 state", + "201 frame b199 t16 bt5831 m04 macro_talk p0 51ddb25342248c72", + "202 frame b200 t17 bt5848 m04 macro_talk p0 3f4b549fcfd40302", + "203 frame b201 t17 bt5865 m04 - p0 1ab673841a089025", + "204 frame b202 t17 bt5882 m04 - p0 9146ba27774f5937", + "205 frame b203 t16 bt5898 m04 - p0 d1c891868e0c48b4", + "206 frame b204 t17 bt5915 m04 - p120 1aa382cede74d36a", + "207 frame b205 t17 bt5932 m04 - p103 692f94397750c3b6", + "208 frame b206 t16 bt5948 m04 - p87 5d9ac6f1fa771385", + "209 frame b207 t17 bt5965 m34 - p70 0e96c0743aec05c7", + "210 frame b208 t17 bt5982 m34 - p53 d91b236ebe272fa3", + "211 frame b209 t17 bt5999 m34 - p36 4ad5374d47cdcdae", + "212 frame b210 t16 bt6015 m34 - p20 b37529a0105ba2c0", + "213 frame b211 t17 bt6032 m34 - p3 504d9d86dae0cb35", + "214 frame b212 t17 bt6049 m34 - p0 886a90e8c0b58461", + "215 frame b213 t17 bt6066 m04 - p0 9cc25421d7118f7f", + "216 frame b214 t16 bt6082 m04 - p0 b44009171671ff67", + "217 frame b215 t17 bt6099 m04 - p0 20c0af1b486dcce7", + "218 frame b216 t17 bt6116 m04 - p0 5f62d7ce7aaf7cba", + "219 frame b217 t17 bt6133 m02 macro_menu p0 3479097cfe92a45e", + "220 frame b218 t16 bt6149 m02 macro_menu p0 58da0f5bf3e746bc", + "221 frame b219 t17 bt6166 m02 macro_menu p0 c727e2ee2f68ab43", + "222 frame b220 t17 bt6183 m02 macro_menu p0 3cd2936775dfaa42", + "223 frame b221 t17 bt6200 m02 macro_menu p120 1618166702443d2a", + "224 frame b222 t16 bt6216 m02 macro_menu p104 cac3e979b5094f7e", + "225 frame b223 t17 bt6233 m02 macro_menu p87 6bc80216cd9307d0", + "226 frame b224 t17 bt6250 m02 macro_menu p70 158808c3270826e2", + "227 frame b225 t17 bt6267 m02 macro_menu p53 e864eee9eaed3100", + "228 frame b226 t16 bt6283 m02 macro_menu p37 2f4831892562df6c", + "229 frame b227 t17 bt6300 m02 macro_menu p20 f94333f42fb868e5", + "230 frame b228 t17 bt6317 m02 macro_menu p3 62b950c98af5ea1e", + "231 frame b229 t17 bt6334 m02 macro_menu p0 3995bffa513087f5", + "232 frame b230 t16 bt6350 m02 macro_menu p0 83ed01c9a19409db", + "233 frame b231 t17 bt6367 m02 macro_menu p0 7cad1b56d3abcd86", + "234 frame b232 t17 bt6384 m02 macro_menu p0 1e4f6b123bf7b16b", + "235 frame b233 t17 bt6401 m02 macro_menu p0 961794680cc8d12e", + "236 frame b234 t16 bt6417 m02 macro_menu p0 4452a80712b7eef8", + "237 frame b235 t17 bt6434 m02 macro_menu p0 5dde31f090f929dd", + "238 frame b236 t17 bt6451 m32 macro_menu p0 10016921e0075703", + "239 frame b237 t17 bt6468 m32 macro_menu p0 3c71e55a03bcff56", + "240 frame b238 t16 bt6484 m32 macro_menu p120 94bd075f6fa74a82 state", + "241 frame b239 t17 bt6501 m32 macro_menu p103 d2d653c50d3d61ab", + "242 frame b240 t17 bt6518 m72 macro_menu p86 e0eb01fdec42ae6b", + "243 frame b241 t16 bt6534 m72 macro_menu p70 819891d76b93ffb3", + "244 frame b242 t17 bt6551 m42 macro_menu p53 48e684dbcaa34252", + "245 frame b243 t17 bt6568 m42 macro_menu p36 6b5f7974c612b7a3", + "246 frame b244 t17 bt6585 m02 macro_menu p19 66184ee2c6b219d1", + "247 frame b245 t16 bt6601 m02 macro_menu p3 d2b0395a6f2d92ed", + "248 frame b246 t17 bt6618 m02 macro_menu p0 202c87574e9d0ebc", + "249 frame b247 t17 bt6635 m02 macro_menu p0 c021f470cca581d9", + "250 frame b248 t17 bt6652 m02 macro_menu p0 590e9ba836d9b1c8", + "251 frame b249 t16 bt6668 m02 macro_menu p0 5da2d0bac5889de6", + "252 frame b250 t17 bt6685 m02 macro_menu p0 b294d92e2460443b", + "253 frame b251 t17 bt6702 m02 macro_menu p0 6af20af6bb0d75c8", + "254 frame b252 t17 bt6719 m02 macro_menu p0 ee5b8463e04ddfaa", + "255 frame b253 t16 bt6735 m02 macro_menu p0 33ad8e7c4a740c20", + "256 frame b254 t17 bt6752 m02 macro_menu p0 2c8afafa80388840", + "257 frame b255 t17 bt6769 m02 macro_menu p120 e78d398f5e177908", + "258 frame b256 t17 bt6786 m02 macro_menu p103 a2bad8c1a35197c9", + "259 frame b257 t16 bt6802 m02 macro_menu p87 476decc6c7fdb03c", + "260 frame b258 t17 bt6819 m02 macro_menu p70 fb61281ced140083", + "261 frame b259 t17 bt6836 m02 macro_menu p53 eb14e0e8da15899c", + "262 frame b260 t17 bt6853 m02 macro_menu p36 14a5132bd706cea1 state" + ] +} diff --git a/services/flysim/crates/fly-session/fixtures/toy-raw.golden.json b/services/flysim/crates/fly-session/fixtures/toy-raw.golden.json new file mode 100644 index 0000000..b8c4ade --- /dev/null +++ b/services/flysim/crates/fly-session/fixtures/toy-raw.golden.json @@ -0,0 +1,90 @@ +{ + "scenario": "toy-raw", + "macroChannels": [], + "records": 82, + "digest": "b732f959c51784f833c8ce413f896845dd706d9f2b8a87871fc3fdf4b305bcfe", + "rows": [ + "0 initialize b0 t2500 bt2500 m-- - p0 d676a54ce95aef0e", + "1 frame b1 t16 bt2516 m61 - p0 4faf42ac1ad6bcb9", + "2 frame b2 t17 bt2533 m71 - p0 8486caa267aec201", + "3 frame b3 t17 bt2550 m71 - p0 b0d966a6997b1c97", + "4 frame b4 t16 bt2566 m71 - p0 64327c9a3acaab25", + "5 frame b5 t17 bt2583 m31 - p0 3798452f3ebb8d14", + "6 frame b6 t17 bt2600 m31 - p0 179c8090e3478edf", + "7 frame b7 t17 bt2617 m11 - p0 764ac5a70eaa61d5", + "8 frame b8 t16 bt2633 m01 - p0 4eebfeadc843551c", + "9 frame b9 t17 bt2650 m01 - p0 3a4d8b850a579039", + "10 frame b10 t17 bt2667 m01 - p233 2e0f5a9335fabcc1", + "11 frame b11 t17 bt2684 m01 - p216 463c0780050cad58", + "12 frame b12 t16 bt2700 m01 - p200 3cd1021570919827", + "13 frame b13 t17 bt2717 m01 - p183 1d94880645b962aa", + "14 frame b14 t17 bt2734 m01 - p166 46fe4904b3422551", + "15 frame b15 t17 bt2751 m01 - p149 fce03793e22fb350", + "16 frame b16 t16 bt2767 m01 - p133 e31bc8f885260567", + "17 frame b17 t17 bt2784 m01 - p116 fa18c9ba0836e754", + "18 frame b18 t17 bt2801 m01 - p99 1599f79d81c26afb", + "19 frame b19 t17 bt2818 m01 - p82 118a390d17e1bd1c", + "20 frame b20 t16 bt2834 m01 - p66 9ec9aa11d1798516", + "21 frame b21 t17 bt2851 m01 - p49 b204db618f624d2c", + "22 frame b22 t17 bt2868 m01 - p32 a23457482b2939ef", + "23 frame b23 t17 bt2885 m01 - p15 a8c14ddada3e932e", + "24 frame b24 t16 bt2901 m01 - p0 ba33d0462ebddaf1", + "25 frame b25 t17 bt2918 m01 - p0 67cc2d1bd2b9bb9b", + "26 frame b26 t17 bt2935 m01 - p120 14a2110ff7cab560", + "27 frame b27 t17 bt2952 m01 - p103 05a3fedc4ee71492", + "28 frame b28 t16 bt2968 m01 - p87 5f56e91792a8cde7", + "29 frame b29 t17 bt2985 m01 - p70 8c4a2900dd3c57a9", + "30 frame b30 t17 bt3002 m21 - p53 0a10535b52bfd50f state", + "31 frame b31 t17 bt3019 m31 - p36 719b19d5d7d38811", + "32 frame b32 t16 bt3035 m31 - p20 016145fcf339c081", + "33 frame b33 t17 bt3052 m31 - p3 3aaf41e08109ca4b", + "34 frame b34 t17 bt3069 m31 - p0 a8234c793afb94c9", + "35 frame b35 t16 bt3085 m31 - p0 58327823fc61314a", + "36 frame b36 t17 bt3102 m11 - p0 bcf2610c93f2ccbc", + "37 frame b37 t17 bt3119 m01 - p0 e1595a5774be4e17", + "38 frame b38 t17 bt3136 m01 - p0 16b1e96a6229a022", + "39 frame b39 t16 bt3152 m01 - p120 4a36e5436f44c5f5", + "40 frame b40 t17 bt3169 m01 - p103 1f3d420fa5f95980", + "41 frame b41 t17 bt3186 m01 - p86 b548ce6125948fa3", + "42 frame b42 t17 bt3203 m01 - p69 7750b42e6bad3b0e", + "43 frame b43 t16 bt3219 m01 - p53 05a53fc43e61453b", + "44 frame b44 t17 bt3236 m01 - p36 8a69135634af3790", + "45 frame b45 t17 bt3253 m01 - p19 eb08c832eae97b32", + "46 frame b46 t17 bt3270 m01 - p2 e6be429be207a75a", + "47 frame b47 t16 bt3286 m01 - p0 563592a0452cb518", + "48 frame b48 t17 bt3303 m01 - p0 ed298d7a151a5576", + "49 frame b49 t17 bt3320 m02 - p0 345c64ffddd498d7", + "50 frame b50 t17 bt3337 m02 - p0 f6b66191b92e78a6", + "51 frame b51 t16 bt3353 m02 - p0 5636f8375e2bd7af", + "52 frame b52 t17 bt3370 m02 - p120 a8379efb27af6c0b", + "53 frame b53 t17 bt3387 m02 - p103 a3ea7fd0062ef0f7", + "54 frame b54 t17 bt3404 m02 - p86 409e243195a1f031", + "55 frame b55 t16 bt3420 m02 - p70 18e41167f8ee76b5", + "56 frame b56 t17 bt3437 m02 - p53 2452a659ce895028", + "57 frame b57 t17 bt3454 m02 - p36 aea6a3b31521a657", + "58 frame b58 t17 bt3471 m02 - p19 abb6c797c4179f73", + "59 frame b59 t16 bt3487 m22 - p3 7f8278ec59a44a45", + "60 frame b60 t17 bt3504 m32 - p0 79f6fa3a61d3852c", + "61 rollback b60 t0 bt3504 m-- - p0 3a769108c95f6734", + "62 frame b61 t17 bt3521 m01 - p0 2d9f2dc819137ea8", + "63 frame b62 t17 bt3538 m01 - p0 4351b16cfffe379d", + "64 frame b63 t16 bt3554 m01 - p0 39286c3fcd1e0dfb", + "65 frame b64 t17 bt3571 m01 - p0 3c935521f3e6f9c1", + "66 frame b65 t17 bt3588 m01 - p120 fde92192bd9c3827", + "67 frame b66 t17 bt3605 m01 - p103 fe7a4a2e4bc2caea", + "68 frame b67 t16 bt3621 m01 - p87 a1e2ee1ff05cf73c", + "69 frame b68 t17 bt3638 m01 - p70 d676cc814f51c4e5", + "70 frame b69 t17 bt3655 m01 - p53 57e50efd3f7c7ece", + "71 frame b70 t16 bt3671 m01 - p37 2d286c3b9c9bdad5", + "72 frame b71 t17 bt3688 m01 - p20 3bdaad14aeafd436", + "73 frame b72 t17 bt3705 m01 - p3 d24ecab576a63abd", + "74 frame b73 t17 bt3722 m01 - p0 92344f9026ff8e6a", + "75 frame b74 t16 bt3738 m01 - p0 67296ab770e3083a", + "76 frame b75 t17 bt3755 m01 - p0 07a568151228ddd8", + "77 frame b76 t17 bt3772 m01 - p0 62d33c55f40ef71f", + "78 frame b77 t17 bt3789 m01 - p0 506824f70aec7fd2", + "79 frame b78 t16 bt3805 m01 - p120 b594e6a96e31d900", + "80 frame b79 t17 bt3822 m01 - p103 b11dd400cc4d2499", + "81 frame b80 t17 bt3839 m01 - p86 edab6faae36ee227 state" + ] +} diff --git a/services/flysim/crates/fly-session/src/cli.rs b/services/flysim/crates/fly-session/src/cli.rs index dcb0df7..823f7d2 100644 --- a/services/flysim/crates/fly-session/src/cli.rs +++ b/services/flysim/crates/fly-session/src/cli.rs @@ -22,14 +22,16 @@ use std::process::ExitCode; use crate::agent::AgentFaults; use crate::environment::EnvironmentFaults; use crate::launcher::{ - AgentLaunch, EnvironmentLaunch, ExecutionMode, Started, flags, serve_one, + AgentLaunch, EnvironmentLaunch, ExecutionMode, LegacyAgentLaunch, Started, flags, serve_one, }; +use crate::legacy_agent::LegacyProfileKind; use crate::types::*; const USAGE: &str = "\ fly-session [options] agent serve one agent worker on a launcher-created endpoint + legacy-agent serve one legacy Game Boy agent worker (AGENT-01) on a launcher endpoint environment serve the environment worker on a launcher-created endpoint measure compare the execution modes and print the measurement table measure-row measure one row and print it as JSON (one child per row) @@ -47,6 +49,8 @@ Worker options (agent and environment): --warmup-ticks N [--prepare-delay-ms N] [--commit-delay-ms N] [--fail-commit-at-step N] [--fail-stage-restore 0|1] [--fail-activate-restore 0|1] + legacy-agent: --agent ID --port ID --dataset DIR --profile production|toy + --macro-channels c1,c2 (empty in raw mode) environment: --worker ID --ports p1,p2 --step-numerator N --step-denominator N [--advance-delay-ms N] [--omit-view-at-boundary N] [--fail-stage-restore 0|1] [--fail-activate-restore 0|1] @@ -75,6 +79,8 @@ pub fn main() -> ExitCode { let result = match command.as_str() { "agent" => Options::parse(&rest, &[flags::COMMON, flags::AGENT_ONLY]) .and_then(|o| serve(&command, &o)), + "legacy-agent" => Options::parse(&rest, &[flags::COMMON, flags::LEGACY_AGENT_ONLY]) + .and_then(|o| serve(&command, &o)), "environment" => Options::parse(&rest, &[flags::COMMON, flags::ENVIRONMENT_ONLY]) .and_then(|o| serve(&command, &o)), "measure" => Options::parse(&rest, &[flags::MEASURE]).and_then(|o| measure(&o)), @@ -220,6 +226,18 @@ fn serve(role: &str, options: &Options) -> Result<(), String> { client_id: client_id.clone(), service: service.clone(), }), + "legacy-agent" => Started::LegacyAgent(LegacyAgentLaunch { + session_id, + agent_id: options.id(flags::AGENT)?, + port_id: options.id(flags::PORT)?, + incarnation_id, + worker_threads: threads, + dataset_dir: options.path(flags::DATASET)?, + profile: LegacyProfileKind::parse(options.required(flags::PROFILE)?)?, + macro_channels: parse_channels(options.required(flags::MACRO_CHANNELS)?)?, + client_id: client_id.clone(), + service: service.clone(), + }), _ => Started::Environment(EnvironmentLaunch { session_id, worker_id: options.id(flags::WORKER)?, @@ -259,6 +277,20 @@ fn serve(role: &str, options: &Options) -> Result<(), String> { }) } +fn parse_channels(value: &str) -> Result, String> { + value + .split(',') + .filter(|part| !part.is_empty()) + .map(|part| { + if fly_session_types::gameboy::is_channel_name(part) { + Ok(part.to_owned()) + } else { + Err(format!("--macro-channels: {part:?} is not a channel name")) + } + }) + .collect() +} + fn parse_ports(value: &str) -> Result, String> { value .split(',') diff --git a/services/flysim/crates/fly-session/src/launcher.rs b/services/flysim/crates/fly-session/src/launcher.rs index 65827b6..b36119d 100644 --- a/services/flysim/crates/fly-session/src/launcher.rs +++ b/services/flysim/crates/fly-session/src/launcher.rs @@ -30,6 +30,7 @@ use flybus::{Client, ClientConfig, Router, ServiceConfig, Transport, UnixListene use crate::agent::{AgentConfig, AgentFaults, FakeAgentWorker}; use crate::environment::{CounterEnvironment, EnvironmentConfig, EnvironmentFaults}; +use crate::legacy_agent::{LegacyAgentConfig, LegacyAgentWorker, LegacyProfileKind}; use crate::rpc::WorkerRef; use crate::types::*; use crate::worker::{StatusCell, WorkerHandle, serve}; @@ -257,6 +258,26 @@ pub struct EnvironmentLaunch { pub service: String, } +/// What one legacy agent participant (AGENT-01) is started with. +/// +/// Everything crosses a process boundary as argv, like the synthetic agent's configuration: a +/// dataset directory, the profile it serves and the composition's macro channels. The seed, +/// the profile `AssetRef` and the first frame arrive in `Agent.Initialize`, not here. +#[derive(Clone, Debug)] +pub struct LegacyAgentLaunch { + pub session_id: Id, + pub agent_id: Id, + pub port_id: Id, + pub incarnation_id: Id, + pub worker_threads: usize, + pub dataset_dir: PathBuf, + pub profile: LegacyProfileKind, + /// `executor.macroChannels` in composition order; empty in raw mode. + pub macro_channels: Vec, + pub client_id: String, + pub service: String, +} + // ------------------------------------------------------------------------------------------- // A launched participant @@ -581,6 +602,38 @@ impl Launcher { } } + /// Starts one legacy agent (AGENT-01), in the launcher's configured mode, and identifies it. + pub async fn launch_legacy_agent( + &mut self, + spec: LegacyAgentLaunch, + ) -> Result { + let threads = self.budget.allocate(&spec.agent_id, spec.worker_threads)?; + let identity = WorkerIdentity { + session_id: spec.session_id.clone(), + client_id: spec.client_id.clone(), + service: spec.service.clone(), + worker_id: spec.agent_id.clone(), + incarnation_id: spec.incarnation_id.clone(), + role: Role::Agent, + port_id: Some(spec.port_id.clone()), + worker_threads: threads, + }; + let started = self + .start_participant(&identity, Started::LegacyAgent(spec.clone()), threads) + .await; + match started { + Ok(worker) => { + let identity = worker.identity.clone(); + self.workers.insert(spec.agent_id.clone(), worker); + Ok(identity) + } + Err(e) => { + self.budget.release(&spec.agent_id); + Err(e) + } + } + } + /// Starts the environment, in the launcher's configured mode, and identifies it. pub async fn launch_environment( &mut self, @@ -690,6 +743,12 @@ impl Launcher { let status = endpoint.status(); (serve(client, service, endpoint), status) } + Started::LegacyAgent(spec) => { + let endpoint = + LegacyAgentWorker::new(legacy_agent_config(spec, identity.worker_threads)); + let status = endpoint.status(); + (serve(client, service, endpoint), status) + } Started::Environment(spec) => { let endpoint = CounterEnvironment::new(environment_config(spec)); let status = endpoint.status(); @@ -1250,6 +1309,10 @@ pub(crate) mod flags { pub const OMIT_AUDIO_AT_BOUNDARY: &str = "omit-audio-at-boundary"; pub const OVERLAPPING_AUDIO_AT_BOUNDARY: &str = "overlapping-audio-at-boundary"; + pub const DATASET: &str = "dataset"; + pub const PROFILE: &str = "profile"; + pub const MACRO_CHANNELS: &str = "macro-channels"; + pub const MODE: &str = "mode"; pub const AGENTS: &str = "agents"; pub const STEPS: &str = "steps"; @@ -1281,6 +1344,8 @@ pub(crate) mod flags { FAIL_STAGE_RESTORE, FAIL_ACTIVATE_RESTORE, ]; + /// What only a legacy agent (AGENT-01) is given. + pub const LEGACY_AGENT_ONLY: &[&str] = &[AGENT, PORT, DATASET, PROFILE, MACRO_CHANNELS]; /// What only the environment is given, media options included. pub const ENVIRONMENT_ONLY: &[&str] = &[ WORKER, @@ -1313,6 +1378,7 @@ fn arg(name: &str, value: impl std::fmt::Display) -> (String, String) { #[derive(Clone, Debug)] pub(crate) enum Started { Agent(AgentLaunch), + LegacyAgent(LegacyAgentLaunch), Environment(EnvironmentLaunch), } @@ -1320,6 +1386,7 @@ impl Started { pub(crate) fn subcommand(&self) -> &'static str { match self { Started::Agent(_) => "agent", + Started::LegacyAgent(_) => "legacy-agent", Started::Environment(_) => "environment", } } @@ -1350,6 +1417,17 @@ impl Started { } args } + Started::LegacyAgent(spec) => vec![ + arg(flags::SESSION, &spec.session_id), + arg(flags::AGENT, &spec.agent_id), + arg(flags::PORT, &spec.port_id), + arg(flags::INCARNATION, &spec.incarnation_id), + arg(flags::DATASET, spec.dataset_dir.display()), + arg(flags::PROFILE, spec.profile.label()), + // An empty list is raw mode; the flag is always written so the parser never + // has to guess which one a missing flag meant. + arg(flags::MACRO_CHANNELS, spec.macro_channels.join(",")), + ], Started::Environment(spec) => { let mut args = vec![ arg(flags::SESSION, &spec.session_id), @@ -1405,6 +1483,18 @@ pub(crate) fn agent_config(spec: &AgentLaunch, worker_threads: usize) -> AgentCo } } +pub(crate) fn legacy_agent_config(spec: &LegacyAgentLaunch, worker_threads: usize) -> LegacyAgentConfig { + LegacyAgentConfig { + session_id: spec.session_id.clone(), + agent_id: spec.agent_id.clone(), + incarnation_id: spec.incarnation_id.clone(), + worker_threads, + dataset_dir: spec.dataset_dir.clone(), + profile: spec.profile, + macro_channels: spec.macro_channels.clone(), + } +} + pub(crate) fn environment_config(spec: &EnvironmentLaunch) -> EnvironmentConfig { EnvironmentConfig { session_id: spec.session_id.clone(), @@ -1441,6 +1531,11 @@ pub(crate) async fn serve_one( service, FakeAgentWorker::new(agent_config(spec, worker_threads)), ), + Started::LegacyAgent(spec) => serve( + client, + service, + LegacyAgentWorker::new(legacy_agent_config(spec, worker_threads)), + ), Started::Environment(spec) => { serve(client, service, CounterEnvironment::new(environment_config(spec))) } @@ -1528,6 +1623,21 @@ mod flag_tests { } } + fn legacy_agent_launch() -> LegacyAgentLaunch { + LegacyAgentLaunch { + session_id: id("demo"), + agent_id: id("fly-a"), + port_id: id("p1"), + incarnation_id: id("fly-a-inc-1"), + worker_threads: 1, + dataset_dir: PathBuf::from("/nonexistent/legacy-toy"), + profile: LegacyProfileKind::Toy, + macro_channels: vec!["macro_talk".to_owned()], + client_id: "worker-fly-a".to_owned(), + service: "agent.fly-a".to_owned(), + } + } + /// Both halves of the command line name the same constants, and this proves it for every /// argument a launch can produce: a flag the launcher writes that the parser does not /// accept would be a silently ignored option, which is what the parser now refuses. @@ -1539,6 +1649,10 @@ mod flag_tests { [flags::COMMON, flags::ENVIRONMENT_ONLY], ), (Started::Agent(agent_launch()), [flags::COMMON, flags::AGENT_ONLY]), + ( + Started::LegacyAgent(legacy_agent_launch()), + [flags::COMMON, flags::LEGACY_AGENT_ONLY], + ), ] { let arguments = started.arguments(); assert!(!arguments.is_empty()); diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs new file mode 100644 index 0000000..a846993 --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -0,0 +1,1796 @@ +//! AGENT-01: the legacy agent worker, `gameboy-legacy-fafb-v783-v1` over the existing neural core. +//! +//! [`LegacyAgentWorker`] is a [`WorkerEndpoint`] with the agent role. It is a small adapter over +//! `flybrain-core`'s [`NeuralAgent`] primitives -- the LIF network, its plasticity, the retina and +//! the fixed Game Boy readout -- and it does **not** go through `NeuralAgent::tick`, because that +//! wrapper runs a whole legacy frame in one call and the session splits it in two: +//! +//! | Legacy `Sim::step_frame` | Here | +//! | --- | --- | +//! | drain commands: `stimulate(sugar)` | `Agent.Prepare`: `preStepStimulations`, in order | +//! | `network.step(ticks)`, 548625/32768 ms per frame | `Agent.Prepare`: the rational accumulator of `step-v1` section 5, whose ticks and remainders are the legacy f64 ones exactly (`legacy-gameboy-v1` section 3) | +//! | blocked rule, `decode_bound(rates, ms, boot, blocked, bound)` | `Agent.Prepare`, with `gameboy-readout-context-v1` | +//! | `set_visual_frame(frame)` | `Agent.Commit` step 1 | +//! | `stimulate(event.stimulation_ms)` per event | `Agent.Commit` step 2, `taskStimulations` in order | +//! | `reinforce(sum, ms)` if plasticity is enabled | `Agent.Commit` step 3, once | +//! | `location != last` restarts the blocked window | `Agent.Commit`, from `nextDecisionContext.location` | +//! | `recover_game`'s neural half | `Agent.Rollback` (`legacy-ratchet-rollback-v1`) | +//! | FLYSIM01 load, then a fresh process's transients | `State.StageRestore` + `ActivateRestore` (`legacy-transient-reset`) | +//! +//! The readout transient -- the held channel, the start of the blocked window and the last +//! location -- is private agent state (`legacy-gameboy-v1` section 5) and is never captured. +//! A fresh start and a restore both begin it exactly as a fresh legacy process does: no held +//! channel, no location, the window starting at brain time **0 ms**. So the first decode after a +//! restore passes the restored winner as `blocked` (section 14 and the port-contracts review, N1). +//! +//! Rate roles are published under `legacy-rate-role-id-v1` ([`gameboy::rate_role_id`]): the +//! identity on the `Id` grammar, which every legacy role name already satisfies. + +use std::collections::BTreeSet; +use std::path::PathBuf; +use std::sync::Arc; + +use fly_session_types::extensions::{ + AgentRollbackParams, AgentRollbackResult, METHOD_AGENT_ROLLBACK, ROLLBACK_CAPABILITY, +}; +use fly_session_types::gameboy::{self, ChannelsDecision, Location, ReadoutContext}; +use flybrain_core::agent::{AgentConfig as CoreAgentConfig, AgentState, NeuralAgent}; +use flybrain_core::dataset::{BrainDataset, MACRO_ROLE_PREFIX, load_brain_dataset_from_dir}; +use flybrain_core::decoder::gameboy::{gameboy_decoder_config_with_macros, to_button_mask}; +use flybrain_core::decoder::{DecoderConfig, ExclusiveGroup}; +use flybrain_core::envelope::{ + agent_from_chunks, agent_to_chunks, decode_envelope, encode_envelope, +}; +use flybrain_core::json::JsonValue; +use flybrain_core::lif::{LifConfig, SweepPlan, kernel_version}; +use serde_json::{Value, json}; + +use crate::clock::TickAccumulator; +// `crate::types` is this crate's facade over the shared `fly-session-types` crate. +use crate::types::*; +use crate::worker::{BoxFuture, HandlerCtx, HandlerReply, StatusCell, WorkerEndpoint}; + +// ------------------------------------------------------------------------------------------- +// Profiles + +/// The toy profile's id. A fixture profile for the committed toy connectome: every field is the +/// legacy profile's except the id, the dataset id and the fingerprint, and a profile never +/// reuses the legacy profile's id (`legacy-gameboy-v1` section 17). It is test identity, not a +/// production profile. +pub const TOY_PROFILE_ID: &str = "gameboy-legacy-toy-v1"; +/// The toy connectome's dataset id. +pub const TOY_DATASET_ID: &str = "legacy-toy"; +/// The schema-1 fingerprint of `fixtures/legacy-toy`, which the loader recomputes and the toy +/// golden test pins. +pub const TOY_FINGERPRINT: &str = "4014d84930520778281dba0000f97e07e36f200c045f9464f1fc860cb0d8efe6:\ +6a95a07f1598277333397b551c9b3a3d88b0c75a507123486810b83bc5deb88e:\ +6af524099ade9a45f6426eb2dc297306e8ecb2aa19fde7c5764fe8dda722d979:\ +f767d48ff556fceae996e2ac73c0d0871df71101db0af414a0ffcd0bfb678489:\ +525b5fe3910fd219ad7c989f977489fa98fe815a3eef95301626391a9ab126e6:\ +319fbbb4acc79b1711ce1dc9431df2b3c0be49ca04fdd703f1afa204bd3f6e5d:\ +49c2699978666f863cee2baf914167f00fa9a215ef4756536f8d6e64449ceb38"; + +/// The magic of the agent's capture payload: a `flybrain-core` checkpoint envelope whose +/// manifest and chunks are exactly `agent_to_chunks`, plus one `session` manifest member. +pub const PAYLOAD_MAGIC: &str = "FLYAGT01"; +/// The layout version of the `session` member. +pub const PAYLOAD_VERSION: u64 = 1; +/// The attachment a Commit reply carries the transition's spike bitset under. +pub const SPIKES_ATTACHMENT: &str = "telemetry.spikes"; +/// Bit `i` is neuron `i` in dataset order, little-endian within a byte, `ceil(neurons/8)` bytes: +/// the legacy feed's `spike_bitset` layout. +pub const SPIKES_CONTENT_TYPE: &str = "application/x-fly-spike-bitset"; +/// The one stimulus kind the profile supports. +pub const REWARD_PULSE: &str = gameboy::STIMULUS_REWARD_PULSE; + +/// Which profile document a worker is configured for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LegacyProfileKind { + /// `gameboy-legacy-fafb-v783-v1`, over `data/fafb-v783`. + Production, + /// [`TOY_PROFILE_ID`], over the committed toy connectome. + Toy, +} + +impl LegacyProfileKind { + pub fn label(&self) -> &'static str { + match self { + LegacyProfileKind::Production => "production", + LegacyProfileKind::Toy => "toy", + } + } + + pub fn parse(text: &str) -> Result { + match text { + "production" => Ok(LegacyProfileKind::Production), + "toy" => Ok(LegacyProfileKind::Toy), + other => Err(format!( + "unknown legacy profile {other:?}; production or toy" + )), + } + } + + pub fn profile(&self) -> LegacyAgentProfile { + match self { + LegacyProfileKind::Production => LegacyAgentProfile::production(), + LegacyProfileKind::Toy => LegacyAgentProfile::toy(), + } + } +} + +/// A profile document, its `AssetRef` and the dataset fingerprint it embeds. +#[derive(Clone, Debug)] +pub struct LegacyAgentProfile { + pub kind: LegacyProfileKind, + pub document: Value, + pub asset: AssetRef, + pub dataset_fingerprint: String, +} + +impl LegacyAgentProfile { + /// The one legacy profile of `legacy-gameboy-v1` section 2. + pub fn production() -> LegacyAgentProfile { + let document = DomainType::to_json(&gameboy::legacy_profile()); + LegacyAgentProfile { + kind: LegacyProfileKind::Production, + document, + asset: gameboy::profile_asset_ref(), + dataset_fingerprint: gameboy::FAFB_V783_FINGERPRINT.to_owned(), + } + } + + /// The toy fixture profile: the legacy document with the toy id, dataset and fingerprint. + pub fn toy() -> LegacyAgentProfile { + let mut document = DomainType::to_json(&gameboy::legacy_profile()); + document["profileId"] = Value::from(TOY_PROFILE_ID); + document["datasetId"] = Value::from(TOY_DATASET_ID); + document["datasetFingerprint"] = Value::from(TOY_FINGERPRINT); + let canonical = canonicalize(&document).expect("a profile document canonicalizes"); + LegacyAgentProfile { + kind: LegacyProfileKind::Toy, + asset: AssetRef { + id: TOY_PROFILE_ID.to_owned(), + digest: digest_of_bytes(canonical.as_bytes()), + byte_length: canonical.len() as u64, + format: gameboy::PROFILE_FORMAT.to_owned(), + }, + document, + dataset_fingerprint: TOY_FINGERPRINT.to_owned(), + } + } +} + +// ------------------------------------------------------------------------------------------- +// The decoder configuration digest + +fn group_form(group: Option<&ExclusiveGroup>) -> Value { + match group { + None => Value::Null, + Some(g) => json!({ + "channels": g.channels.iter() + .map(|(channel, role)| json!({"channel": channel, "role": role})) + .collect::>(), + "decisionMs": g.decision_ms, + "holdMs": g.hold_ms, + "hysteresis": g.hysteresis, + "fatigueGain": g.fatigue_gain, + "fatigueDecay": g.fatigue_decay, + "blockedFatigue": g.blocked_fatigue, + "blockedMs": g.blocked_ms, + }), + } +} + +/// The canonical form `gameboy-decoder-config-v1` of `legacy-gameboy-v1` section 12. +/// +/// `flysim`'s `legacy_profile_identity` test builds the same form and writes the shared vectors +/// in `fly-session-types/fixtures/gameboy-decoder-config.json`; this crate's tests hold this +/// function to those vectors, so the agent reports the digest its own decoder has. +pub fn decoder_config_form(config: &DecoderConfig) -> Value { + json!({ + "form": "gameboy-decoder-config-v1", + "exclusive": group_form(config.exclusive.as_ref()), + "macros": group_form(config.macros.as_ref()), + "pulses": config.pulses.iter().map(|p| json!({ + "channel": p.channel, + "role": p.role, + "holdMs": p.hold_ms, + "cooldownMs": p.cooldown_ms, + "threshold": p.threshold, + "boot": p.boot.map_or(Value::Null, |b| json!({"cooldownMs": b.cooldown_ms, "threshold": b.threshold})), + "throttleGroup": p.throttle_group.clone().map_or(Value::Null, Value::String), + })).collect::>(), + "clearLockoutMs": config.clear_lockout_ms, + }) +} + +/// `decoderConfigDigest`: the SHA-256 of the canonical form. +pub fn decoder_config_digest(config: &DecoderConfig) -> Digest { + digest_of(&decoder_config_form(config)).expect("a decoder form canonicalizes") +} + +// ------------------------------------------------------------------------------------------- +// Clock conversions + +/// The legacy f64 frame remainder (ms) as the exact `RationalNs` remainder. +/// +/// Every legacy remainder is a multiple of 2^-15 ms below one tick (`legacy-gameboy-v1` +/// section 3), so the conversion is exact; anything else is refused rather than rounded. +pub fn legacy_remainder_to_rational(ms: f64) -> Result { + let scaled = ms * 32_768.0; + if !scaled.is_finite() || scaled < 0.0 || scaled.fract() != 0.0 || scaled >= 32_768.0 { + return Err(format!( + "legacy remainder {ms} is not k/32768 ms below one tick" + )); + } + RationalNs::reduced(scaled as u128 * 1_000_000, 32_768).map_err(|e| e.0) +} + +/// The exact `RationalNs` remainder as the legacy f64 millisecond remainder. +pub fn rational_remainder_to_legacy(remainder: &RationalNs) -> Result { + let numerator = u128::from(remainder.numerator) * 32_768; + let denominator = u128::from(remainder.denominator) * 1_000_000; + if !numerator.is_multiple_of(denominator) { + return Err(format!( + "remainder {}/{} ns is not a multiple of 2^-15 ms", + remainder.numerator, remainder.denominator + )); + } + let k = numerator / denominator; + if k >= 32_768 { + return Err("a remainder must stay below one model tick".to_owned()); + } + Ok(k as f64 / 32_768.0) +} + +// ------------------------------------------------------------------------------------------- +// The readout transient + +/// The readout's private transient: the channel the direction group holds, the brain time at +/// which the blocked window last restarted, and the last location the task reported. +/// +/// `legacy-gameboy-v1` sections 5 and 14: never captured, and reset on Initialize and on every +/// restore to exactly what a fresh legacy process holds. +#[derive(Clone, Debug, PartialEq)] +pub struct ReadoutTransient { + pub held_channel: Option, + pub blocked_since_ms: f64, + pub location: Option, +} + +impl ReadoutTransient { + /// A fresh legacy process: no held channel, no location, the window starting at 0 ms. + pub fn legacy_reset() -> ReadoutTransient { + ReadoutTransient { + held_channel: None, + blocked_since_ms: 0.0, + location: None, + } + } +} + +/// The spike bitset of the legacy feed: neuron `i` fired at or after `since_ms`. +pub fn spike_bitset(last_spike_ms: &[f64], since_ms: f64, now_ms: f64) -> Vec { + let mut bytes = vec![0u8; last_spike_ms.len().div_ceil(8)]; + if now_ms <= since_ms { + return bytes; + } + for (index, last) in last_spike_ms.iter().enumerate() { + if *last >= since_ms { + bytes[index >> 3] |= 1 << (index & 7); + } + } + bytes +} + +// ------------------------------------------------------------------------------------------- +// Configuration + +/// One legacy agent worker's configuration. +#[derive(Clone, Debug)] +pub struct LegacyAgentConfig { + pub session_id: Id, + pub agent_id: Id, + pub incarnation_id: Id, + /// The launcher's thread allocation. `workerThreads > 1` parallelises the neuron sweep, + /// which `flybrain-core` guarantees does not change a result. + pub worker_threads: usize, + /// The dataset directory: `data/fafb-v783` for the production profile. + pub dataset_dir: PathBuf, + pub profile: LegacyProfileKind, + /// The composition's `executor.macroChannels`, in composition order; empty in raw mode. + pub macro_channels: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum AgentPhase { + Uninitialized, + Ready(u64), + Prepared(u64), + Failed, +} + +/// The decision context this worker holds for its next Prepare. +#[derive(Clone, Debug)] +struct HeldContext { + typed: TypedValue, + readout: ReadoutContext, + digest: Digest, +} + +/// A validated replacement state, invisible to the live session until it is activated. +struct StagedAgent { + token: Id, + checkpoint_id: Id, + scope: Scope, + agent: NeuralAgent, + dataset: Arc, + graph: AgentGraph, + accumulator: TickAccumulator, + context: HeldContext, + seed: i32, + reinforcements: u64, + committed_step: u64, +} + +/// The legacy agent worker endpoint. +pub struct LegacyAgentWorker { + config: LegacyAgentConfig, + profile: LegacyAgentProfile, + status: StatusCell, + phase: AgentPhase, + epoch: Option, + dataset: Option>, + graph: Option, + seed: i32, + agent: Option, + accumulator: Option, + transient: ReadoutTransient, + context: Option, + prepared: Option<(DomainRequestId, PreparedDecision)>, + /// The brain time before the in-flight transition's ticks: the spike window's start. + transition_start_ms: f64, + staged: Option, + activated: BTreeSet, + /// Every mutation this worker applied, reported as its progress counter. + mutations: u64, + /// Reinforcement calls applied since the fly's fresh start; captured. + reinforcements: u64, +} + +fn incompatible(message: impl std::fmt::Display) -> DomainError { + DomainError::before(ErrorCode::IncompatibleState, message) +} + +fn applied(code: ErrorCode, message: impl std::fmt::Display) -> DomainError { + DomainError::new(code, message, MutationCertainty::Applied) +} + +fn check_supported(stimulus: &Stimulus) -> DomainResult<()> { + stimulus.validate().map_err(DomainError::invalid)?; + if stimulus.kind_id != REWARD_PULSE { + return Err(DomainError::before( + ErrorCode::Unsupported, + format!( + "stimulus kind {} is not one this profile resolves; it supports {REWARD_PULSE}", + stimulus.kind_id + ), + )); + } + Ok(()) +} + +/// The dataset digest an `AgentGraph` attests: SHA-256 of the schema-1 fingerprint string. +pub fn dataset_digest(fingerprint: &str) -> Digest { + digest_of_bytes(fingerprint.as_bytes()) +} + +/// The index digest: the fingerprint (which covers the neuron order and every anatomical role) +/// plus the `macro_*` populations it deliberately does not cover, the profile's declared +/// `macro-roles-outside-fingerprint` exception. Two datasets that relabel the macro +/// populations differently have the same fingerprint and different index digests. +pub fn index_digest(dataset: &BrainDataset, fingerprint: &str) -> Digest { + let mut text = format!( + "fly-session/legacy-agent-index-v1\nfingerprint={fingerprint}\nneurons={}\n", + dataset.meta.neurons + ); + for (name, neurons) in &dataset.meta.roles { + if name.starts_with(MACRO_ROLE_PREFIX) { + let list: Vec = neurons.iter().map(u32::to_string).collect(); + text.push_str(&format!("role={name}:{}\n", list.join(","))); + } + } + digest_of_bytes(text.as_bytes()) +} + +/// The capture compatibility digest (`workers-v1` section 2) of a legacy agent. +pub fn compatibility_digest( + agent_id: &Id, + profile: &AssetRef, + graph: &AgentGraph, + seed: i32, +) -> Digest { + crate::agent::agent_compatibility_digest( + agent_id, + &profile.digest, + &graph.dataset_digest, + gameboy::KERNEL_VERSION, + gameboy::PLASTICITY_VERSION, + seed, + &graph.index_digest, + ) +} + +/// The telemetry of an agent at its current state. +/// +/// `learning` maps the legacy counters onto the contract's, which requires +/// `changed <= updates`: `updates` is the reinforcement calls this agent applied (one per +/// commit while the rule is enabled, zero sums included), and `changed` is the legacy +/// `plasticity.updates`, the reinforcements that moved at least one gain. The legacy +/// per-synapse count (`LearningStats.changed`, gains off 1.0) is not a counter of updates and +/// is not carried; it stays readable from the captured state. +pub fn telemetry_of(agent: &NeuralAgent, brain_ticks: u64, reinforcements: u64) -> AgentTelemetry { + let network = &agent.network; + let plasticity = &network.plasticity; + AgentTelemetry { + brain_ticks, + population_rate_hz: network.population_rate, + rates: network + .rates + .iter() + .map(|(name, hz)| RateSample { + role_id: name.clone(), + hz, + }) + .collect(), + learning: LearningTelemetry { + enabled: plasticity.enabled, + updates: reinforcements, + changed: plasticity.updates() as u64, + signal: plasticity.signal(), + }, + stimulus_remaining_ms: Some(network.reward_remaining()), + } +} + +/// `gameboy-channels-v1` from a decode's active set: the button mask in `GAMEBOY_BUTTONS` +/// order, and the first bound channel the decode holds, which is exactly the channel the legacy +/// macro layer's `asked` would start. +pub fn channels_decision(active: &[String], bound: &[String]) -> ChannelsDecision { + let mask = to_button_mask(active); + let mut buttons = [false; 8]; + for (bit, down) in buttons.iter_mut().enumerate() { + *down = mask & (1 << bit) != 0; + } + let macro_channel = bound + .iter() + .find(|channel| active.contains(channel)) + .cloned(); + ChannelsDecision { + buttons, + macro_channel, + } +} + +impl LegacyAgentWorker { + pub fn new(config: LegacyAgentConfig) -> LegacyAgentWorker { + LegacyAgentWorker { + profile: config.profile.profile(), + config, + status: StatusCell::new(), + phase: AgentPhase::Uninitialized, + epoch: None, + dataset: None, + graph: None, + seed: 0, + agent: None, + accumulator: None, + transient: ReadoutTransient::legacy_reset(), + context: None, + prepared: None, + transition_start_ms: 0.0, + staged: None, + activated: BTreeSet::new(), + mutations: 0, + reinforcements: 0, + } + } + + pub fn status(&self) -> StatusCell { + self.status.clone() + } + + /// The readout transient, for an in-process test. + pub fn transient(&self) -> &ReadoutTransient { + &self.transient + } + + /// The neural agent, for an in-process test. + pub fn agent(&self) -> Option<&NeuralAgent> { + self.agent.as_ref() + } + + fn bump(&mut self) { + self.mutations += 1; + self.status.advance_to(self.mutations); + } + + fn check_epoch(&self, scope: &Scope) -> DomainResult<()> { + if scope.session_id != self.config.session_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "this worker belongs to another session", + )); + } + match &self.epoch { + Some(epoch) if *epoch == scope.epoch => Ok(()), + Some(_) => Err(DomainError::before( + ErrorCode::StaleEpoch, + "this scope names an epoch this worker has left", + )), + None => Err(DomainError::before( + ErrorCode::InvalidPhase, + "this worker is uninitialized", + )), + } + } + + /// Reads and validates a decision context against the composition's macro channels. + fn read_context(&self, typed: &TypedValue) -> DomainResult { + typed.validate().map_err(DomainError::invalid)?; + let readout = ReadoutContext::from_typed(typed).map_err(|e| { + DomainError::before( + ErrorCode::IdentityMismatch, + format!( + "the decision context is not gameboy-readout-context-v1: {}", + e.0 + ), + ) + })?; + readout + .validate_against(&self.config.macro_channels) + .map_err(DomainError::invalid)?; + Ok(HeldContext { + typed: typed.clone(), + readout, + digest: typed.digest(), + }) + } + + /// Reads the one `lcd` view of a sensory input: 160 x 144 RGBA8, produced at the observed + /// boundary, from a live owned attachment. A missing view is an error, never zero input. + async fn read_lcd(&self, ctx: &HandlerCtx<'_>, input: &SensoryInput) -> DomainResult> { + input + .validate_for_profile(false) + .map_err(DomainError::invalid)?; + let [view] = input.views.as_slice() else { + return Err(DomainError::invalid(format!( + "this profile consumes exactly one view, {}; the input has {}", + gameboy::VIEW_ID, + input.views.len() + ))); + }; + if view.view_id != gameboy::VIEW_ID { + return Err(DomainError::invalid(format!( + "this profile consumes the view {}, not {}", + gameboy::VIEW_ID, + view.view_id + ))); + } + if view.produced_step != input.boundary { + return Err(DomainError::invalid( + "the lcd view has no render delay: it must be produced at the observed boundary", + )); + } + let expected = gameboy::VIEW_WIDTH * gameboy::VIEW_HEIGHT * 4; + let name = crate::media::view_attachment(&view.view_id); + let artifact = ctx.artifact(&name)?; + if artifact.reference() != &view.pixels { + return Err(DomainError::before( + ErrorCode::BufferInvalid, + format!("attachment {name} is not the artifact the payload names"), + )); + } + let bytes = artifact.read_all().await.map_err(|e| { + DomainError::before( + ErrorCode::BufferInvalid, + format!("view {} could not be read: {}", view.view_id, e.message), + ) + })?; + if bytes.len() as u64 != expected || view.pixels.byte_length != expected { + return Err(DomainError::before( + ErrorCode::BufferInvalid, + format!( + "the lcd view must be {expected} RGBA bytes, found {}", + bytes.len() + ), + )); + } + Ok(bytes) + } + + /// Loads the dataset once and checks it is the one the profile embeds. + fn dataset(&mut self) -> DomainResult> { + if let Some(dataset) = &self.dataset { + return Ok(dataset.clone()); + } + let dir = &self.config.dataset_dir; + let dataset = load_brain_dataset_from_dir(dir).map_err(|e| { + DomainError::before( + ErrorCode::IncompatibleState, + format!("the dataset at {} does not load: {e}", dir.display()), + ) + })?; + match dataset.fingerprint.as_deref() { + Some(fingerprint) if fingerprint == self.profile.dataset_fingerprint => {} + found => { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + format!( + "the dataset at {} is not the one {} embeds: fingerprint {} (expected {})", + dir.display(), + self.profile.asset.id, + found.unwrap_or("none"), + self.profile.dataset_fingerprint + ), + )); + } + } + let dataset = Arc::new(dataset); + self.dataset = Some(dataset.clone()); + Ok(dataset) + } + + /// Builds a network and readout over `dataset`, before any state is installed, and checks + /// every identity the profile pins: kernel and plasticity versions, frame size, rate roles. + fn build_agent( + &self, + dataset: Arc, + seed: i32, + ) -> DomainResult<(NeuralAgent, AgentGraph)> { + let lif = LifConfig { + seed, + ..LifConfig::default() + }; + let kernel = kernel_version(&lif); + if kernel != gameboy::KERNEL_VERSION { + return Err(incompatible(format!( + "seed {seed} is not this profile's: its kernel version would be {kernel}, and the \ + profile pins {} (the default seed, 22222)", + gameboy::KERNEL_VERSION + ))); + } + let channels: Vec<&str> = self + .config + .macro_channels + .iter() + .map(String::as_str) + .collect(); + let mut config = + CoreAgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels)); + config.lif = lif; + config.warmup_ms = gameboy::WARMUP_MS; + let mut agent = NeuralAgent::new(dataset.clone(), config) + .map_err(|e| incompatible(format!("the agent does not build: {e}")))?; + if agent.network.version != gameboy::KERNEL_VERSION + || agent.network.plasticity.version != gameboy::PLASTICITY_VERSION + { + return Err(incompatible(format!( + "the built network is {} / {}, not the profile's {} / {}", + agent.network.version, + agent.network.plasticity.version, + gameboy::KERNEL_VERSION, + gameboy::PLASTICITY_VERSION + ))); + } + if (u64::from(agent.frame.width), u64::from(agent.frame.height)) + != (gameboy::VIEW_WIDTH, gameboy::VIEW_HEIGHT) + { + return Err(incompatible( + "the retina is not the profile's 160 x 144 lcd", + )); + } + let names: Vec<&str> = agent.network.rates.keys().map(String::as_str).collect(); + let rate_roles = gameboy::rate_role_ids(names.iter().copied()).map_err(|e| { + incompatible(format!( + "the dataset's rate roles cannot be published: {}", + e.0 + )) + })?; + for channel in &self.config.macro_channels { + if !names.contains(&channel.as_str()) { + return Err(incompatible(format!( + "macro channel {channel} reads a rate role this dataset does not track" + ))); + } + } + if self.config.worker_threads > 1 { + let plan = SweepPlan::with_threads(self.config.worker_threads) + .map_err(|e| DomainError::invalid(format!("sweep plan: {e}")))?; + agent.set_sweep_plan(plan); + } + let fingerprint = self.profile.dataset_fingerprint.clone(); + let graph = AgentGraph { + dataset_digest: dataset_digest(&fingerprint), + index_digest: index_digest(&dataset, &fingerprint), + neuron_count: dataset.meta.neurons as u64, + rate_roles, + supported_stimuli: vec![REWARD_PULSE.to_owned()], + }; + Ok((agent, graph)) + } + + fn telemetry(&self) -> AgentTelemetry { + let agent = self.agent.as_ref().expect("initialized"); + let accumulator = self.accumulator.as_ref().expect("initialized"); + telemetry_of(agent, accumulator.brain_ticks(), self.reinforcements) + } + + // --------------------------------------------------------------------------------------- + // Agent.Initialize + + async fn initialize(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + if self.phase != AgentPhase::Uninitialized { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "Agent.Initialize is only allowed on an uninitialized agent; restore uses the \ + state interface", + )); + } + if scope.step != 0 { + return Err(DomainError::before( + ErrorCode::FutureStep, + "Agent.Initialize uses the new epoch at step 0", + )); + } + if scope.session_id != self.config.session_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "this worker belongs to another session", + )); + } + let params: AgentInitializeParams = ctx.params()?; + if params.agent_id != self.config.agent_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "Agent.Initialize names another agent", + )); + } + if params.worker_threads == 0 { + return Err(DomainError::invalid("workerThreads must be >= 1")); + } + if params.worker_threads > self.config.worker_threads as u64 { + return Err(DomainError::before( + ErrorCode::Busy, + format!( + "Agent.Initialize asks for {} worker threads; the launcher allocated {}", + params.worker_threads, self.config.worker_threads + ), + )); + } + // The profile identity: the document this worker is configured for, byte for byte. + if params.profile != self.profile.asset { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + format!( + "Agent.Initialize names profile {} ({}); this worker serves {} ({})", + params.profile.id, + params.profile.digest, + self.profile.asset.id, + self.profile.asset.digest + ), + )); + } + if params.initial_input.boundary != 0 { + return Err(DomainError::invalid( + "the initial input must observe boundary 0", + )); + } + let context = self.read_context(¶ms.initial_decision_context)?; + let frame = self.read_lcd(ctx, ¶ms.initial_input).await?; + // Everything above is validated; now the dataset and the model. The dataset is checked + // against the fingerprint the profile embeds before a network is built over it. + let dataset = self.dataset()?; + let (mut agent, graph) = self.build_agent(dataset, params.seed)?; + + // Warm-up with learning disabled, calibration on the settled rates, then the first + // frame -- `NeuralAgent::warmup`, which is what the legacy fresh start calls. + let mut accumulator = TickAccumulator::new(gameboy::tick_duration()) + .map_err(|e| applied(ErrorCode::Internal, e))?; + agent + .warmup(Some(&frame)) + .map_err(|e| applied(ErrorCode::BackendFailure, format!("warm-up: {e}")))?; + accumulator + .warm_up(gameboy::WARMUP_MS) + .map_err(|e| applied(ErrorCode::Internal, e))?; + if agent.network.ms != accumulator.brain_ticks() as f64 { + return Err(applied( + ErrorCode::Internal, + "the brain clock after warm-up is not the accumulator's tick count", + )); + } + + self.seed = params.seed; + self.agent = Some(agent); + self.graph = Some(graph.clone()); + self.accumulator = Some(accumulator); + // A fresh legacy process: the context's location is not adopted as the last location. + // The legacy loop only takes a location at the end of a frame, so frame one's commit + // is where the window first restarts on it. + self.transient = ReadoutTransient::legacy_reset(); + self.transition_start_ms = gameboy::WARMUP_MS as f64; + let digest = context.digest.clone(); + self.context = Some(context); + self.epoch = Some(scope.epoch.clone()); + self.phase = AgentPhase::Ready(0); + self.bump(); + self.status.set_state(WorkerState::Ready); + self.status.set_scope(Some(scope.clone())); + + let result = AgentInitializeResult { + agent_id: self.config.agent_id.clone(), + profile_digest: self.profile.asset.digest.clone(), + tick_duration: gameboy::tick_duration(), + warmup_ticks: gameboy::WARMUP_MS, + committed_step: 0, + decision_context_digest: digest, + telemetry: self.telemetry(), + graph, + }; + result + .validate() + .map_err(|e| applied(ErrorCode::Internal, e.0))?; + Ok(HandlerReply::from(&result)) + } + + // --------------------------------------------------------------------------------------- + // Agent.Prepare + + async fn prepare(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + self.check_epoch(&scope)?; + let AgentPhase::Ready(k) = self.phase.clone() else { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + format!( + "Agent.Prepare needs Ready(k); this worker is {:?}", + self.phase + ), + )); + }; + if scope.step != k { + return Err(DomainError::before( + if scope.step < k { + ErrorCode::StaleStep + } else { + ErrorCode::FutureStep + }, + "Agent.Prepare names a step other than this worker's committed boundary", + )); + } + let params: PrepareParams = ctx.params()?; + if params.agent_id != self.config.agent_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "Agent.Prepare names another agent", + )); + } + if params.profile_digest != self.profile.asset.digest { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "Agent.Prepare names another profile", + )); + } + let context = self.context.clone().expect("initialized"); + if params.decision_context_digest != context.digest { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "the cached decision context digest does not match", + )); + } + if params.interval != gameboy::step_duration() { + return Err(DomainError::invalid( + "this profile's interval is one Game Boy frame, 8572265625/512 ns", + )); + } + if params.pre_step_stimulations.len() > MAX_STIMULI { + return Err(DomainError::invalid("at most 64 pre-step stimulations")); + } + for stimulus in ¶ms.pre_step_stimulations { + check_supported(stimulus)?; + } + + self.status.set_state(WorkerState::Preparing); + // 1. Admitted pre-step stimulation (sugar), in command order: the legacy drain. + let agent = self.agent.as_mut().expect("initialized"); + for stimulus in ¶ms.pre_step_stimulations { + agent.network.stimulate(stimulus.duration_ms); + } + // 2. The frame's whole ticks. + let accumulator = self.accumulator.as_mut().expect("initialized"); + let ticks = accumulator + .advance(¶ms.interval) + .map_err(|e| applied(ErrorCode::Internal, e))?; + let brain_ticks = accumulator.brain_ticks(); + let remainder = accumulator.remainder(); + self.transition_start_ms = agent.network.ms; + agent.network.step(ticks); + if agent.network.ms != brain_ticks as f64 { + return Err(applied( + ErrorCode::Internal, + "the brain clock is not the accumulator's tick count", + )); + } + // 3. The fixed readout with the declared context, and the blocked-direction rule on + // the agent's own held channel, clock and location history (`docs/readout.md`). + let ms = agent.network.ms; + let rates = agent.network.rates.clone(); + let blocked_ms = agent.decoder.blocked_ms(); + let blocked = (blocked_ms > 0.0 && ms - self.transient.blocked_since_ms >= blocked_ms) + .then(|| agent.decoder.current()) + .flatten() + .map(str::to_string); + let bound = context.readout.bound.clone(); + // Raw mode has no macro group, and the legacy loop passes `None` there. + let mask_bound = (!self.config.macro_channels.is_empty()).then_some(bound.as_slice()); + let active = agent.decoder.decode_bound( + &rates, + ms, + context.readout.boot, + blocked.as_deref(), + mask_bound, + ); + // A new winner starts its own window. + let held = agent.decoder.current().map(str::to_string); + if held != self.transient.held_channel { + self.transient.held_channel = held; + self.transient.blocked_since_ms = ms; + } + let decision = channels_decision(&active, &bound); + decision + .validate_against(&context.readout) + .map_err(|e| applied(ErrorCode::Internal, e.0))?; + let prepared = PreparedDecision { + agent_id: self.config.agent_id.clone(), + ticks_advanced: ticks, + brain_ticks, + remainder, + decision: decision.to_typed(), + }; + self.prepared = Some((ctx.request.request_id.clone(), prepared.clone())); + self.phase = AgentPhase::Prepared(k); + self.bump(); + self.status.set_state(WorkerState::Prepared); + Ok(HandlerReply::from(&prepared)) + } + + // --------------------------------------------------------------------------------------- + // Agent.Commit + + async fn commit(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + self.check_epoch(&scope)?; + let AgentPhase::Prepared(k) = self.phase.clone() else { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + format!( + "Agent.Commit needs Prepared(k); this worker is {:?}", + self.phase + ), + )); + }; + if scope.step != k { + return Err(DomainError::before( + if scope.step < k { + ErrorCode::StaleStep + } else { + ErrorCode::FutureStep + }, + "Agent.Commit must carry the step of its transition, not the new boundary", + )); + } + let params: CommitParams = ctx.params()?; + params + .validate_against_scope(&scope) + .map_err(DomainError::invalid)?; + if params.agent_id != self.config.agent_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "Agent.Commit names another agent", + )); + } + let (prepared_request, _) = self.prepared.as_ref().expect("prepared"); + if params.prepared_request_id != *prepared_request { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "Agent.Commit does not match this worker's Prepare request", + )); + } + if params.rewards.len() > MAX_REWARDS || params.task_stimulations.len() > MAX_STIMULI { + return Err(DomainError::invalid( + "at most 64 rewards and 64 stimulations", + )); + } + for reward in ¶ms.rewards { + reward.validate().map_err(DomainError::invalid)?; + } + for stimulus in ¶ms.task_stimulations { + check_supported(stimulus)?; + } + let context = self.read_context(¶ms.next_decision_context)?; + // The complete request and its owned artifact are validated before anything applies. + let frame = self.read_lcd(ctx, ¶ms.next_input).await?; + + self.status.set_state(WorkerState::Committing); + let agent = self.agent.as_mut().expect("initialized"); + // 1. Install the next input: the frame the environment just produced. + let (width, height) = (agent.frame.width, agent.frame.height); + agent.network.set_visual_frame(&frame, width, height); + // 2. Task stimulation, in event order. + for stimulus in ¶ms.task_stimulations { + agent.network.stimulate(stimulus.duration_ms); + } + // 3. One reinforcement with the sum, in event order, at the current brain time. The + // legacy loop gates it on the rule being enabled and never skips a zero sum. + let ms = agent.network.ms; + let mut total = 0.0f64; + for reward in ¶ms.rewards { + total += reward.value; + } + if agent.network.plasticity.enabled { + agent.network.plasticity.reinforce(total, ms); + self.reinforcements += 1; + } + // The blocked window's other reset: the player moved. `None` is no information. + if let Some(location) = context.readout.location + && Some(location) != self.transient.location + { + self.transient.location = Some(location); + self.transient.blocked_since_ms = ms; + } + let spikes = spike_bitset(&agent.network.last_spike_ms, self.transition_start_ms, ms); + // 4. Retain the next context and acknowledge k+1. + let digest = context.digest.clone(); + self.context = Some(context); + self.prepared = None; + self.phase = AgentPhase::Ready(k + 1); + self.bump(); + let result = AgentCommitResult { + agent_id: self.config.agent_id.clone(), + committed_step: k + 1, + decision_context_digest: digest, + telemetry: self.telemetry(), + }; + let artifact = crate::media::seal_copy(ctx.client, SPIKES_CONTENT_TYPE.to_owned(), &spikes) + .await + .map_err(|e| applied(e.code, e.message))?; + self.status.set_state(WorkerState::Ready); + self.status + .set_scope(Some(scope_at(&scope.session_id, &scope.epoch, k + 1))); + Ok(HandlerReply::with_artifacts( + object(result.to_json()), + vec![(SPIKES_ATTACHMENT.to_owned(), artifact)], + )) + } + + // --------------------------------------------------------------------------------------- + // Agent.Rollback: legacy-ratchet-rollback-v1 + + async fn rollback(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + if scope.session_id != self.config.session_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "this worker belongs to another session", + )); + } + let params: AgentRollbackParams = ctx.params()?; + params + .validate_against_scope(&scope) + .map_err(DomainError::invalid)?; + if params.agent_id != self.config.agent_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "Agent.Rollback names another agent", + )); + } + match &self.epoch { + None => { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "this worker is uninitialized", + )); + } + Some(epoch) if *epoch == scope.epoch => { + return Err(DomainError::before( + ErrorCode::StaleEpoch, + "Agent.Rollback moves to a new epoch; this worker is already in it", + )); + } + Some(epoch) if *epoch != params.prior_epoch => { + return Err(DomainError::before( + ErrorCode::StaleEpoch, + format!( + "Agent.Rollback names prior epoch {}; this worker is in {epoch}", + params.prior_epoch + ), + )); + } + Some(_) => {} + } + let AgentPhase::Ready(k) = self.phase.clone() else { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + format!( + "Agent.Rollback needs Ready(k); this worker is {:?}", + self.phase + ), + )); + }; + if scope.step != k { + return Err(DomainError::before( + if scope.step < k { + ErrorCode::StaleStep + } else { + ErrorCode::FutureStep + }, + "Agent.Rollback is applied at this worker's committed boundary", + )); + } + let context = self.read_context(¶ms.decision_context)?; + let frame = self.read_lcd(ctx, ¶ms.input).await?; + + self.status.set_state(WorkerState::Restoring); + let agent = self.agent.as_mut().expect("initialized"); + let ms = agent.network.ms; + // The neural half of `recover_game`, in its order: decoder holds, eligibility, frame. + agent.decoder.clear_holds(ms); + agent.network.plasticity.clear_eligibility(ms); + let (width, height) = (agent.frame.width, agent.frame.height); + agent.network.set_visual_frame(&frame, width, height); + // `Sim::recover`: the location from the restored world, no held channel, the window + // restarting now. + self.transient = ReadoutTransient { + held_channel: None, + blocked_since_ms: ms, + location: context.readout.location, + }; + self.transition_start_ms = ms; + let digest = context.digest.clone(); + self.context = Some(context); + self.epoch = Some(scope.epoch.clone()); + self.prepared = None; + self.phase = AgentPhase::Ready(k); + self.bump(); + let result = AgentRollbackResult { + agent_id: self.config.agent_id.clone(), + committed_step: k, + decision_context_digest: digest, + telemetry: self.telemetry(), + }; + result + .validate_against_scope(&scope) + .map_err(|e| applied(ErrorCode::Internal, e.0))?; + self.status.set_state(WorkerState::Ready); + self.status.set_scope(Some(scope.clone())); + Ok(HandlerReply::new(object(result.to_json()))) + } + + // --------------------------------------------------------------------------------------- + // State.Capture / StageRestore / ActivateRestore + + /// The capture payload: `agent_to_chunks` in a checkpoint envelope, plus a `session` + /// manifest member with the accumulator, the context and the identities. The readout + /// transient is not in it (`legacy-transient-reset`). + fn payload(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult> { + let agent = self.agent.as_ref().expect("initialized"); + let accumulator = self.accumulator.as_ref().expect("initialized"); + let context = self.context.as_ref().expect("initialized"); + let mut state = agent.export_state(); + // The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`). + state.remainder = rational_remainder_to_legacy(&accumulator.remainder()) + .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?; + let chunks = agent_to_chunks(&state); + let channels: Vec<&str> = self + .config + .macro_channels + .iter() + .map(String::as_str) + .collect(); + let session = json!({ + "payloadVersion": PAYLOAD_VERSION, + "kind": "legacy-agent", + "agentId": self.config.agent_id, + "checkpointId": checkpoint_id, + "sourceScope": scope.to_json(), + "committedStep": k.to_string(), + "profile": self.profile.asset.to_json(), + "seed": self.seed, + "reinforcements": self.reinforcements.to_string(), + "kernelVersion": gameboy::KERNEL_VERSION, + "plasticityVersion": gameboy::PLASTICITY_VERSION, + "macroChannels": self.config.macro_channels, + "decoderConfigDigest": decoder_config_digest(&gameboy_decoder_config_with_macros(&channels)), + "accumulator": { + "tickDuration": accumulator.tick_duration().to_json(), + "remainder": accumulator.remainder().to_json(), + "executedTicks": accumulator.executed_ticks().to_string(), + "warmupOffset": accumulator.warmup_offset().to_string(), + }, + "context": context.typed.to_json(), + }); + let mut manifest = chunks.manifest; + let session = JsonValue::parse(&session.to_string()).map_err(|e| { + DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None) + })?; + manifest.set("session", session); + encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| { + DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None) + }) + } + + async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + self.check_epoch(&scope)?; + let AgentPhase::Ready(k) = self.phase.clone() else { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + format!( + "State.Capture needs a quiescent Ready(k); this worker is {:?}", + self.phase + ), + )); + }; + if scope.step != k { + return Err(DomainError::before( + if scope.step < k { + ErrorCode::StaleStep + } else { + ErrorCode::FutureStep + }, + "State.Capture names a boundary this worker is not at", + )); + } + let params: CaptureParams = ctx.params()?; + let previous = self.status.state(); + self.status.set_state(WorkerState::Capturing); + let bytes = self.payload(¶ms.checkpoint_id, &scope, k); + let bytes = match bytes { + Ok(bytes) => bytes, + Err(e) => { + self.status.set_state(previous); + return Err(e); + } + }; + let digest = digest_of_bytes(&bytes); + let artifact = crate::state::seal_payload(ctx.client, &bytes, &digest).await; + self.status.set_state(previous); + let artifact = artifact?; + let graph = self.graph.as_ref().expect("initialized"); + let result = CaptureResult { + checkpoint_id: params.checkpoint_id, + boundary: k, + compatibility_digest: compatibility_digest( + &self.config.agent_id, + &self.profile.asset, + graph, + self.seed, + ), + payload: artifact.reference().clone(), + }; + Ok(HandlerReply::with_artifacts( + object(result.to_json()), + vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)], + )) + } + + async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let scope = ctx.scope()?.clone(); + if scope.session_id != self.config.session_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "this worker belongs to another session", + )); + } + match &self.phase { + AgentPhase::Uninitialized | AgentPhase::Ready(_) => {} + other => { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + format!( + "State.StageRestore needs an uninitialized replacement or a quiescent \ + worker; this worker is {other:?}" + ), + )); + } + } + if let Some(epoch) = &self.epoch + && *epoch == scope.epoch + { + return Err(DomainError::before( + ErrorCode::StaleEpoch, + "State.StageRestore proposes the epoch this worker is already running", + )); + } + let params: StageRestoreParams = ctx.params()?; + if params.source_scope.step != scope.step { + return Err(DomainError::invalid( + "State.StageRestore's scope step must be the source boundary", + )); + } + let artifact = ctx.artifact(crate::state::PAYLOAD_ATTACHMENT)?; + if artifact.reference() != ¶ms.payload { + return Err(DomainError::before( + ErrorCode::BufferInvalid, + "the staged payload attachment is not the artifact the request names", + )); + } + let bytes = artifact.read_all().await.map_err(|e| { + DomainError::before( + ErrorCode::BufferInvalid, + format!("the staged payload could not be read: {}", e.message), + ) + })?; + let declared = params + .payload + .digest + .clone() + .ok_or_else(|| incompatible("a checkpoint payload must carry a content digest"))?; + let actual = digest_of_bytes(&bytes); + if actual != declared || bytes.len() as u64 != params.payload.byte_length { + return Err(incompatible( + "the staged payload is not the content the request declares", + )); + } + let parts = decode_envelope(&bytes, PAYLOAD_MAGIC).map_err(|e| { + incompatible(format!( + "the staged payload is not a {PAYLOAD_MAGIC} envelope: {e}" + )) + })?; + let session = parts + .manifest + .get("session") + .ok_or_else(|| incompatible("the agent payload has no session member"))?; + let session: Value = serde_json::from_str(&session.stringify()) + .map_err(|e| incompatible(format!("the session member is not JSON: {e}")))?; + let text = |key: &str| -> DomainResult { + session + .get(key) + .and_then(Value::as_str) + .map(str::to_owned) + .ok_or_else(|| incompatible(format!("the agent payload has no {key}"))) + }; + if session.get("payloadVersion").and_then(Value::as_u64) != Some(PAYLOAD_VERSION) { + return Err(incompatible("the agent payload is another payload version")); + } + if text("kind")? != "legacy-agent" { + return Err(incompatible("this payload is not a legacy agent's state")); + } + if text("agentId")? != self.config.agent_id { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "the staged payload belongs to another agent", + )); + } + if text("checkpointId")? != params.checkpoint_id { + return Err(incompatible( + "the staged payload belongs to another checkpoint", + )); + } + if text("kernelVersion")? != gameboy::KERNEL_VERSION + || text("plasticityVersion")? != gameboy::PLASTICITY_VERSION + { + return Err(incompatible( + "the staged payload was captured under another numerical model", + )); + } + let source_scope = Scope::from_json( + session + .get("sourceScope") + .ok_or_else(|| incompatible("the agent payload has no sourceScope"))?, + ) + .map_err(|e| incompatible(format!("the agent payload's sourceScope: {}", e.0)))?; + if source_scope != params.source_scope { + return Err(incompatible( + "the staged payload was captured at another source scope", + )); + } + let committed_step: u64 = text("committedStep")? + .parse() + .map_err(|_| incompatible("the agent payload's committedStep is not a U64"))?; + if committed_step != params.source_scope.step { + return Err(incompatible( + "the staged payload's committed step is not the source boundary", + )); + } + let profile = AssetRef::from_json( + session + .get("profile") + .ok_or_else(|| incompatible("the agent payload has no profile"))?, + ) + .map_err(|e| incompatible(format!("the agent payload's profile: {}", e.0)))?; + if profile != self.profile.asset { + return Err(incompatible(format!( + "the staged payload is profile {}; this worker serves {}", + profile.id, self.profile.asset.id + ))); + } + let seed = session + .get("seed") + .and_then(Value::as_i64) + .and_then(|v| i32::try_from(v).ok()) + .ok_or_else(|| incompatible("the agent payload has no seed"))?; + let reinforcements: u64 = text("reinforcements")? + .parse() + .map_err(|_| incompatible("the agent payload's reinforcements is not a U64"))?; + let accumulator_value = session + .get("accumulator") + .ok_or_else(|| incompatible("the agent payload has no accumulator"))?; + let rational = |key: &str| -> DomainResult { + RationalNs::from_json( + accumulator_value + .get(key) + .ok_or_else(|| incompatible(format!("the accumulator has no {key}")))?, + ) + .map_err(|e| incompatible(format!("the accumulator's {key}: {}", e.0))) + }; + let counter = |key: &str| -> DomainResult { + accumulator_value + .get(key) + .and_then(Value::as_str) + .ok_or_else(|| incompatible(format!("the accumulator has no {key}")))? + .parse::() + .map_err(|_| incompatible(format!("the accumulator's {key} is not a U64"))) + }; + let tick_duration = rational("tickDuration")?; + if tick_duration != gameboy::tick_duration() { + return Err(incompatible( + "the staged state was captured at another model tick", + )); + } + let accumulator = TickAccumulator::restored( + tick_duration, + rational("remainder")?, + counter("executedTicks")?, + counter("warmupOffset")?, + ) + .map_err(incompatible)?; + let context = self.read_context( + &TypedValue::from_json( + session + .get("context") + .ok_or_else(|| incompatible("the agent payload has no context"))?, + ) + .map_err(|e| incompatible(format!("the agent payload's context: {}", e.0)))?, + )?; + let state: AgentState = agent_from_chunks(&parts.manifest, &parts) + .map_err(|e| incompatible(format!("the agent state does not read: {e}")))?; + // The accumulator and the agent state describe one clock. + let legacy_remainder = + rational_remainder_to_legacy(&accumulator.remainder()).map_err(incompatible)?; + if state.remainder != legacy_remainder + || state.network.ms != accumulator.brain_ticks() as f64 + { + return Err(incompatible( + "the agent state's clock and the session accumulator disagree", + )); + } + if !state.warmed_up { + return Err(incompatible("the staged agent state was never warmed up")); + } + // A replacement fly: the dataset is loaded and checked here, not trusted. + let dataset = self.dataset()?; + let (mut agent, graph) = self.build_agent(dataset.clone(), seed)?; + let computed = + compatibility_digest(&self.config.agent_id, &self.profile.asset, &graph, seed); + if computed != params.compatibility_digest { + return Err(incompatible(format!( + "the staged state's compatibility {} is not the {computed} this worker is", + params.compatibility_digest + ))); + } + agent + .import_state(&state) + .map_err(|e| incompatible(format!("the agent state does not import: {e}")))?; + if let Some(staged) = &self.staged { + return Err(DomainError::before( + ErrorCode::Conflict, + format!( + "this worker already holds the staged restore {} for checkpoint {}", + staged.token, staged.checkpoint_id + ), + )); + } + let token = crate::agent::restore_token( + ¶ms.checkpoint_id, + &scope, + &actual, + &self.config.incarnation_id, + ); + if self.activated.contains(&token) { + return Err(DomainError::before( + ErrorCode::Conflict, + "this exact restore was already activated on this worker", + )); + } + self.staged = Some(StagedAgent { + token: token.clone(), + checkpoint_id: params.checkpoint_id.clone(), + scope: scope.clone(), + agent, + dataset, + graph, + accumulator, + context, + seed, + reinforcements, + committed_step, + }); + self.status.set_state(WorkerState::StagedRestore); + Ok(HandlerReply::from(&StageRestoreResult { + checkpoint_id: params.checkpoint_id, + restore_token: token, + })) + } + + async fn state_activate_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { + let params: ActivateRestoreParams = ctx.params()?; + if self.activated.contains(¶ms.restore_token) { + return Err(DomainError::before( + ErrorCode::Conflict, + "this restore token has already been activated", + )); + } + let Some(staged) = self.staged.take() else { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "this worker holds no staged restore", + )); + }; + if staged.token != params.restore_token { + let token = staged.token.clone(); + self.staged = Some(staged); + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + format!( + "this worker's staged restore is {token}, not {}", + params.restore_token + ), + )); + } + self.status.set_state(WorkerState::Restoring); + let StagedAgent { + token, + checkpoint_id, + scope, + agent, + dataset, + graph, + accumulator, + context, + seed, + reinforcements, + committed_step, + } = staged; + self.transition_start_ms = agent.network.ms; + self.agent = Some(agent); + self.dataset = Some(dataset); + self.graph = Some(graph); + self.accumulator = Some(accumulator); + self.context = Some(context); + self.seed = seed; + self.reinforcements = reinforcements; + // legacy-transient-reset: the readout transient starts as a fresh legacy process has + // it, while the decoder state (holds, winners, fatigue) was restored with the agent. + self.transient = ReadoutTransient::legacy_reset(); + self.epoch = Some(scope.epoch.clone()); + self.prepared = None; + self.phase = AgentPhase::Ready(committed_step); + self.activated.insert(token); + self.bump(); + self.status.set_state(WorkerState::Ready); + self.status.set_scope(Some(scope_at( + &scope.session_id, + &scope.epoch, + committed_step, + ))); + let result = ActivateRestoreResult { + committed_step, + checkpoint_id, + observation: None, + }; + result + .validate_for_role(Role::Agent) + .map_err(|e| DomainError::invalid(e.0))?; + Ok(HandlerReply::from(&result)) + } + + fn fail_on_applied( + &mut self, + outcome: DomainResult, + ) -> DomainResult { + if let Err(e) = &outcome + && e.mutation != MutationCertainty::None + { + self.phase = AgentPhase::Failed; + } + outcome + } +} + +impl WorkerEndpoint for LegacyAgentWorker { + fn worker_id(&self) -> Id { + self.config.agent_id.clone() + } + + fn incarnation_id(&self) -> Id { + self.config.incarnation_id.clone() + } + + fn session_id(&self) -> Id { + self.config.session_id.clone() + } + + fn role(&self) -> Role { + Role::Agent + } + + fn capabilities(&self) -> Vec { + vec![ + id("agent-step-v1"), + id("pixel-observation-v1"), + id(crate::state::CHECKPOINT_CAPABILITY), + id(ROLLBACK_CAPABILITY), + ] + } + + fn status_cell(&self) -> StatusCell { + self.status.clone() + } + + fn worker_threads(&self) -> u64 { + self.config.worker_threads as u64 + } + + fn methods(&self) -> Vec<&'static str> { + vec![ + "Agent.Initialize", + "Agent.Prepare", + "Agent.Commit", + METHOD_AGENT_ROLLBACK, + "State.Capture", + "State.StageRestore", + "State.ActivateRestore", + ] + } + + fn handle<'a>(&'a mut self, ctx: HandlerCtx<'a>) -> BoxFuture<'a, DomainResult> { + Box::pin(async move { + let outcome = match ctx.method { + "Agent.Initialize" => self.initialize(&ctx).await, + "Agent.Prepare" => self.prepare(&ctx).await, + "Agent.Commit" => self.commit(&ctx).await, + METHOD_AGENT_ROLLBACK => self.rollback(&ctx).await, + "State.Capture" => self.state_capture(&ctx).await, + "State.StageRestore" => self.state_stage_restore(&ctx).await, + "State.ActivateRestore" => self.state_activate_restore(&ctx).await, + other => Err(DomainError::before( + ErrorCode::Unsupported, + format!("{other} is not an agent method"), + )), + }; + self.fail_on_applied(outcome) + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_legacy_remainder_converts_exactly_both_ways() { + let mut legacy = 0.0f64; + for _ in 0..100_000 { + legacy += flybrain_core::agent::GAMEBOY_MS_PER_FRAME; + legacy -= legacy.floor(); + let rational = legacy_remainder_to_rational(legacy).expect("exact"); + assert_eq!( + rational_remainder_to_legacy(&rational).expect("exact"), + legacy + ); + } + assert!( + legacy_remainder_to_rational(0.1).is_err(), + "0.1 ms is not k/32768" + ); + assert!( + legacy_remainder_to_rational(1.0).is_err(), + "a remainder is below one tick" + ); + } + + #[test] + fn the_spike_bitset_is_the_legacy_feed_layout() { + let last = [5.0, 9.0, 10.0, -1.0, 12.0, 0.0, 0.0, 0.0, 11.0]; + assert_eq!( + spike_bitset(&last, 10.0, 12.0), + vec![0b0001_0100, 0b0000_0001] + ); + assert_eq!( + spike_bitset(&last, 12.0, 12.0), + vec![0, 0], + "an empty window is empty" + ); + } + + #[test] + fn the_macro_in_a_decision_is_the_first_bound_channel_held() { + let active = vec![ + "up".to_owned(), + "macro_talk".to_owned(), + "macro_go_out".to_owned(), + ]; + let bound = vec!["macro_go_out".to_owned(), "macro_talk".to_owned()]; + let decision = channels_decision(&active, &bound); + assert_eq!(decision.macro_channel.as_deref(), Some("macro_go_out")); + assert_eq!(decision.mask(), 1); + assert_eq!(channels_decision(&active, &[]).macro_channel, None); + } + + #[test] + fn the_decoder_digest_reproduces_the_shared_vectors() { + let file = + fly_session_types::fixtures::load("gameboy-decoder-config.json").expect("vectors"); + for case in file["cases"].as_array().expect("cases") { + let channels: Vec<&str> = case["macroChannels"] + .as_array() + .expect("channels") + .iter() + .map(|c| c.as_str().expect("a channel")) + .collect(); + let config = gameboy_decoder_config_with_macros(&channels); + assert_eq!( + decoder_config_form(&config), + case["form"], + "{}", + case["name"] + ); + assert_eq!( + decoder_config_digest(&config), + case["digest"].as_str().expect("digest"), + "{}", + case["name"] + ); + } + } + + #[test] + fn the_production_profile_is_the_contract_constant_and_the_toy_one_is_not() { + let production = LegacyAgentProfile::production(); + assert_eq!(production.asset, gameboy::profile_asset_ref()); + let toy = LegacyAgentProfile::toy(); + assert_eq!(toy.asset.id, TOY_PROFILE_ID); + assert_ne!(toy.asset.digest, production.asset.digest); + assert_eq!( + digest_of(&toy.document).expect("digest"), + toy.asset.digest, + "the toy AssetRef is the digest of its own document" + ); + // Every pinned field other than the three it names is the legacy profile's. + for key in [ + "kernelVersion", + "plasticityVersion", + "tickDuration", + "warmupMs", + "view", + "supportedStimuli", + "readoutContextSchema", + "decisionSchema", + "legacyExceptions", + ] { + assert_eq!(toy.document[key], production.document[key], "{key}"); + } + } +} diff --git a/services/flysim/crates/fly-session/src/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs new file mode 100644 index 0000000..785b7b7 --- /dev/null +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -0,0 +1,1990 @@ +//! AGENT-01's parity harness: recorded inputs, a reference that drives [`NeuralAgent`] directly +//! in the legacy frame order, the same inputs driven through a launched [`LegacyAgentWorker`] +//! over the bus, and a record-by-record comparison. +//! +//! ```text +//! LegacyScript ──> DirectReference (NeuralAgent in Sim::step_frame order) ──> Vec +//! ──> AgentDriver (Agent.* RPCs to a launched worker) ──> Vec +//! └─ compare() ─┘ +//! ``` +//! +//! A [`ParityRecord`] carries only what both sides can observe of the agent: the ticks, the +//! brain clock and its exact remainder, the decision, the whole telemetry, the digest of the +//! transition's spike bitset and, at declared checkpoints, the digest of the full agent state +//! (`agent_to_chunks`). A state digest is exact equality of every membrane, trace, gain, rate, +//! RNG and decoder field. +//! +//! FND-01's `FLY_TRACE` (`flysim::trace`, `flysim-legacy-frame-trace-v1`) is the running loop's +//! own record. It carries digests and behaviour fields rather than full telemetry, and neither the +//! frames nor the `{boot, bound, location}` context, so it cannot drive a worker by itself: it +//! checks one. [`read_frame_trace`] reads it and [`check_against_trace`] holds a run's records to +//! it. `flysim/tests/agent_trace_parity.rs` is the host that runs `LegacyFrame` with the trace on, +//! records the missing inputs as a [`LegacyScript`], and checks both the worker and +//! [`DirectReference`] against the trace -- so the transcription is itself checked against the +//! service. [`ReferenceSource`] stays the seam for sources of full records. +//! +//! [`toy`] is the committed toy connectome the goldens run on; the real dataset is optional. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use fly_session_types::extensions::{ + AgentRollbackParams, AgentRollbackResult, METHOD_AGENT_ROLLBACK, ROLLBACK_POLICY, +}; +use fly_session_types::gameboy::{self, ChannelsDecision, Location, ReadoutContext}; +use flybrain_core::agent::{AgentConfig as CoreAgentConfig, NeuralAgent}; +use flybrain_core::dataset::BrainDataset; +use flybrain_core::decoder::gameboy::{gameboy_decoder_config_with_macros, to_button_mask}; +use flybrain_core::envelope::{agent_from_chunks, agent_to_chunks, decode_envelope}; +use flybrain_core::rng::Xorshift32; +use flybus::{Client, Grants, Pattern, Policy, Router, RouterConfig}; +use serde_json::{Value, json}; + +use crate::launcher::{ + ExecutionMode, Launcher, LegacyAgentLaunch, SUPERVISOR_CLIENT, ThreadBudget, Via, +}; +use crate::legacy_agent::{ + LegacyAgentProfile, LegacyProfileKind, PAYLOAD_MAGIC, SPIKES_ATTACHMENT, channels_decision, + legacy_remainder_to_rational, spike_bitset, telemetry_of, +}; +use crate::rpc::{Serials, WorkerRef, call}; +use crate::types::*; + +/// The frame size: 160 x 144 RGBA8. +pub const FRAME_BYTES: usize = (gameboy::VIEW_WIDTH * gameboy::VIEW_HEIGHT * 4) as usize; +/// The legacy default seed. The profile's kernel version pins it (`lif-1ms-f64-v2` hashes the +/// seed into any other value), so it is the only seed this profile accepts. +pub const LEGACY_SEED: i32 = 22_222; + +// ------------------------------------------------------------------------------------------- +// The toy connectome + +pub mod toy { + //! The committed toy connectome, `fixtures/legacy-toy`: 4,096 neurons, sized as the + //! oracle's synthetic connectome is (`packages/brain/tools/golden.ts`) so that 300 noise + //! kicks leave the network sub-threshold and the connectome drives it, with the roles the + //! legacy readout and plasticity read -- `command_0..7`, `kenyon`, `mbon`, `reward_pam` -- + //! and four `macro_*` populations merged after the fingerprint, as FAFB's are. + + use std::io::Write as _; + use std::path::{Path, PathBuf}; + + use flate2::Compression; + use flate2::write::GzEncoder; + use flybrain_core::rng::Xorshift32; + use serde_json::{Map, Value, json}; + + /// The macro channels of the toy composition, in composition order. + pub const MACRO_CHANNELS: [&str; 4] = + ["macro_go_out", "macro_talk", "macro_menu", "macro_next"]; + pub const NEURONS: u32 = 4_096; + const EDGES_PER_NEURON: u32 = 10; + const SEED: i32 = 20_260_923; + + /// `services/flysim/crates/fly-session/fixtures/legacy-toy`. + pub fn dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/legacy-toy") + } + + fn range(from: u32, to: u32) -> Vec { + (from..to).collect() + } + + fn gz(bytes: &[u8]) -> Vec { + // flate2's default header has no name and a zero mtime, so the bytes are reproducible. + let mut encoder = GzEncoder::new(Vec::new(), Compression::best()); + encoder.write_all(bytes).expect("in memory"); + encoder.finish().expect("in memory") + } + + /// Every file of the toy dataset, by name, as it is committed. + pub fn files() -> Vec<(String, Vec)> { + let mut random = Xorshift32::new(SEED); + let kenyon = (0u32, 1_024u32); + let mbon = (1_024u32, 1_280u32); + let visual = range(1_600, 2_400); + + let mut roles = Map::new(); + for command in 0..8u32 { + roles.insert( + format!("command_{command}"), + json!(range(1_344 + command * 32, 1_376 + command * 32)), + ); + } + roles.insert("reward_pam".to_owned(), json!(range(1_280, 1_344))); + roles.insert("steer_left".to_owned(), json!(range(2_400, 2_432))); + roles.insert("steer_right".to_owned(), json!(range(2_432, 2_464))); + roles.insert("visual_l1".to_owned(), json!(visual)); + + let mut indptr = Vec::with_capacity(NEURONS as usize + 1); + let mut targets: Vec = Vec::new(); + let mut weights: Vec = Vec::new(); + for source in 0..NEURONS { + indptr.push(targets.len() as u32); + let is_kenyon = source >= kenyon.0 && source < kenyon.1; + for edge in 0..EDGES_PER_NEURON { + let forced = is_kenyon && edge < 4; + let target = if forced { + mbon.0 + (random.next_f64() * f64::from(mbon.1 - mbon.0)).floor() as u32 + } else { + (random.next_f64() * f64::from(NEURONS)).floor() as u32 + }; + let magnitude = 1 + (random.next_f64() * 40.0).floor() as i16; + targets.push(target); + weights.push(if !forced && random.next_f64() < 0.2 { + -magnitude + } else { + magnitude + }); + } + } + indptr.push(targets.len() as u32); + + let mut visual_xy = Vec::with_capacity(visual.len() * 2); + for column in 0..visual.len() { + visual_xy.push((column % 40) as f32 * 7.5); + visual_xy.push((column / 40) as f32 * 5.25); + } + let hemisphere: Vec = (0..visual.len()).map(|c| (c % 2) as u8).collect(); + + let meta = json!({ + "schemaVersion": 1, + "dataset": "legacy-toy", + "neurons": NEURONS, + "edges": targets.len(), + "roles": Value::Object(roles), + "visual": {"population": "toy-retina", "count": visual.len()}, + }); + let circuits = json!({ + "neurons": NEURONS, + "roles": { + "kenyon": range(kenyon.0, kenyon.1), + "mbon": range(mbon.0, mbon.1), + // Relabelled MBONs, outside the fingerprint, as the FAFB macro populations are. + "macro_go_out": range(1_100, 1_116), + "macro_talk": range(1_116, 1_132), + "macro_menu": range(1_132, 1_148), + "macro_next": range(1_148, 1_164), + }, + }); + let le32 = |values: &[u32]| { + values + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>() + }; + let text = |value: &Value| { + let mut s = serde_json::to_string(value).expect("json"); + s.push('\n'); + s.into_bytes() + }; + vec![ + ("meta.json".to_owned(), text(&meta)), + ("circuit-roles.json".to_owned(), text(&circuits)), + ("indptr.binz".to_owned(), gz(&le32(&indptr))), + ("targets.binz".to_owned(), gz(&le32(&targets))), + ( + "weights.binz".to_owned(), + gz(&weights + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>()), + ), + ("visual-indices.binz".to_owned(), gz(&le32(&visual))), + ("visual-hemisphere.binz".to_owned(), gz(&hemisphere)), + ( + "visual-xy.binz".to_owned(), + gz(&visual_xy + .iter() + .flat_map(|v| v.to_le_bytes()) + .collect::>()), + ), + ] + } + + /// Writes the dataset into `dir`. + pub fn write(dir: &Path) -> std::io::Result<()> { + std::fs::create_dir_all(dir)?; + for (name, bytes) in files() { + std::fs::write(dir.join(name), bytes)?; + } + Ok(()) + } +} + +/// `/data/fafb-v783`, or `None` where the dataset is not checked out. +pub fn fafb_dir() -> Option { + let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../../data/fafb-v783"); + dir.join("meta.json").is_file().then_some(dir) +} + +// ------------------------------------------------------------------------------------------- +// Recorded inputs + +/// One reward event of the legacy adapter: a value for `reinforce` and a pulse for +/// `stimulate`. The task turns it into one `Reward` and one `reward-pulse` `Stimulus`. +#[derive(Clone, Debug, PartialEq)] +pub struct RewardEvent { + pub value: f64, + pub stimulation_ms: f64, +} + +/// One step of a recorded run. +#[derive(Clone, Debug, PartialEq)] +pub enum ScriptStep { + /// One transition: sugar admitted before it, the frame the environment produced, the + /// adapter's reward events, and the next decision context. + Frame { + sugar: Vec, + frame: usize, + rewards: Vec, + next_context: ReadoutContext, + }, + /// `legacy-ratchet-rollback-v1` at the boundary just reached: the slot's archived frame and + /// the context the executor's observation of the restored world produced. + Rollback { + frame: usize, + context: ReadoutContext, + }, + /// A group restore at the boundary just reached into a fresh agent + /// (`legacy-transient-reset`): a FLYSIM01-style load into a new process. + Restore, +} + +/// A recorded run: the macro channels, the frame pool, the first frame and context, and the +/// steps. The frames are the environment's output, so they are inputs here. +#[derive(Clone, Debug)] +pub struct LegacyScript { + pub name: String, + pub macro_channels: Vec, + pub frames: Arc>>, + pub initial_frame: usize, + pub initial_context: ReadoutContext, + pub steps: Vec, + /// Step indices after which the full agent state is compared. + pub checkpoints: BTreeSet, +} + +/// A deterministic pool of frames with distinct overall brightness, so the retina drive differs +/// from frame to frame and the connectome has something to respond to. +pub fn frame_pool(count: usize, seed: i32) -> Vec> { + let mut random = Xorshift32::new(seed); + (0..count) + .map(|index| { + let scale = (index + 1) as f64 / count as f64; + (0..FRAME_BYTES) + .map(|byte| { + if byte % 4 == 3 { + 255 + } else { + (random.next_f64() * 256.0 * scale).floor() as u8 + } + }) + .collect() + }) + .collect() +} + +fn context(boot: bool, bound: &[&str], location: Option<(u32, u32, u32)>) -> ReadoutContext { + ReadoutContext { + boot, + bound: bound.iter().map(|b| (*b).to_owned()).collect(), + location: location.map(|(area, x, y)| Location { area, x, y }), + } +} + +/// The macros-mode toy scenario: boot and play, a still location long enough for the blocked +/// rule, a battle (no location), sugar overlapping a pulse, reward events on a schedule with a +/// zero-value one, a rollback into a world that then stands still past a blocked window, a +/// restore into a fresh worker and play after both. +pub fn toy_macros_script(frames: usize) -> LegacyScript { + let channels: Vec = toy::MACRO_CHANNELS + .iter() + .map(|c| (*c).to_owned()) + .collect(); + let bound_at = |k: usize| -> Vec<&'static str> { + match k { + 0..60 => vec![], + 60..130 => vec!["macro_go_out", "macro_talk"], + 130..200 => vec!["macro_talk", "macro_menu", "macro_next"], + _ => vec!["macro_go_out", "macro_menu"], + } + }; + let location_at = |k: usize| -> Option<(u32, u32, u32)> { + match k { + 0..20 => None, + 20..90 => Some((1, 5, 5)), + 90..96 => None, + // The rollback's restored world, standing still past one blocked window. + 121..185 => Some((2, 3, 4)), + _ => Some((1, 5 + (k / 30) as u32, 5)), + } + }; + let mut steps = Vec::new(); + for k in 1..=frames { + let sugar = match k { + 25 => vec![300.0], + 26 => vec![100.0], + 170 => vec![500.0, 40.0], + _ => vec![], + }; + let mut rewards = Vec::new(); + if k % 17 == 0 { + rewards.push(RewardEvent { + value: 0.4, + stimulation_ms: 120.0, + }); + } + if k == 50 { + rewards.push(RewardEvent { + value: 0.25, + stimulation_ms: 80.0, + }); + rewards.push(RewardEvent { + value: 0.5, + stimulation_ms: 200.0, + }); + } + if k == 77 { + rewards.push(RewardEvent { + value: 0.0, + stimulation_ms: 60.0, + }); + } + steps.push(ScriptStep::Frame { + sugar, + frame: (k * 3) % 8, + rewards, + next_context: context(k < 40, &bound_at(k), location_at(k)), + }); + if k == 120 { + steps.push(ScriptStep::Rollback { + frame: 5, + context: context(false, &bound_at(k), Some((2, 3, 4))), + }); + } + if k == 190 { + steps.push(ScriptStep::Restore); + } + } + let checkpoints: BTreeSet = steps + .iter() + .enumerate() + .filter(|(i, _)| i % 40 == 39) + .map(|(i, _)| i) + .chain([steps.len() - 1]) + .collect(); + LegacyScript { + name: "toy-macros".to_owned(), + macro_channels: channels, + frames: Arc::new(frame_pool(8, 4_242)), + initial_frame: 0, + initial_context: context(true, &[], None), + steps, + checkpoints, + } +} + +/// The raw-mode toy scenario: no macro group, a still location, rewards, a rollback. +pub fn toy_raw_script(frames: usize) -> LegacyScript { + let mut steps = Vec::new(); + for k in 1..=frames { + steps.push(ScriptStep::Frame { + sugar: if k == 10 { vec![250.0] } else { vec![] }, + frame: (k * 5) % 8, + rewards: if k % 13 == 0 { + vec![RewardEvent { + value: 0.3, + stimulation_ms: 120.0, + }] + } else { + vec![] + }, + next_context: context(k < 30, &[], if k > 5 { Some((7, 1, 1)) } else { None }), + }); + if k == 60 { + steps.push(ScriptStep::Rollback { + frame: 2, + context: context(false, &[], None), + }); + } + } + let last = steps.len() - 1; + LegacyScript { + name: "toy-raw".to_owned(), + macro_channels: Vec::new(), + frames: Arc::new(frame_pool(8, 99)), + initial_frame: 1, + initial_context: context(true, &[], None), + steps, + checkpoints: [29, last].into_iter().collect(), + } +} + +// ------------------------------------------------------------------------------------------- +// Records + +/// What both sides can observe of one step. +#[derive(Clone, Debug, PartialEq)] +pub struct ParityRecord { + /// 0 is Initialize; step `i` of the script is record `i + 1`. + pub index: usize, + pub kind: &'static str, + /// The committed boundary after the step. + pub boundary: u64, + pub ticks: u64, + pub brain_ticks: u64, + pub remainder: RationalNs, + pub decision: Option, + pub telemetry: Option, + /// SHA-256 of the transition's spike bitset. + pub spikes: Option, + /// SHA-256 of the full agent state, at a checkpoint. + pub state: Option, +} + +impl ParityRecord { + pub fn to_json(&self) -> Value { + json!({ + "index": self.index, + "kind": self.kind, + "boundary": self.boundary.to_string(), + "ticks": self.ticks.to_string(), + "brainTicks": self.brain_ticks.to_string(), + "remainder": self.remainder.to_json(), + "decision": self.decision.as_ref().map_or(Value::Null, DomainType::to_json), + "telemetry": self.telemetry.as_ref().map_or(Value::Null, |t| t.to_json()), + "spikes": self.spikes, + "state": self.state, + }) + } + + pub fn digest(&self) -> Digest { + digest_of(&self.to_json()).expect("a record canonicalizes") + } + + /// One readable line for a golden file: the fields a reviewer reads, then the digest of + /// the whole record. + pub fn row(&self) -> String { + let (mask, macro_channel) = match &self.decision { + Some(d) => ( + format!("{:02x}", d.mask()), + d.macro_channel.clone().unwrap_or_else(|| "-".to_owned()), + ), + None => ("--".to_owned(), "-".to_owned()), + }; + let pulse = self + .telemetry + .as_ref() + .and_then(|t| t.stimulus_remaining_ms) + .map_or("-".to_owned(), |ms| format!("{ms}")); + format!( + "{} {} b{} t{} bt{} m{} {} p{} {}{}", + self.index, + self.kind, + self.boundary, + self.ticks, + self.brain_ticks, + mask, + macro_channel, + pulse, + &self.digest()[..16], + if self.state.is_some() { " state" } else { "" } + ) + } +} + +/// The digest of a full agent state: every chunk and the manifest `agent_to_chunks` writes. +pub fn state_digest(state: &flybrain_core::agent::AgentState) -> Digest { + let chunks = agent_to_chunks(state); + let mut bytes = chunks.manifest.stringify().into_bytes(); + for (name, chunk) in &chunks.chunks { + bytes.extend_from_slice(name.as_bytes()); + bytes.extend_from_slice(&(chunk.len() as u64).to_le_bytes()); + bytes.extend_from_slice(chunk); + } + digest_of_bytes(&bytes) +} + +/// The state digest of a worker's capture payload. +pub fn payload_state_digest(payload: &[u8]) -> Result { + let parts = decode_envelope(payload, PAYLOAD_MAGIC).map_err(|e| e.to_string())?; + let state = agent_from_chunks(&parts.manifest, &parts).map_err(|e| e.to_string())?; + Ok(state_digest(&state)) +} + +/// The first record at which two runs differ, described. +pub fn compare(left: &[ParityRecord], right: &[ParityRecord]) -> Result<(), String> { + for (a, b) in left.iter().zip(right) { + if a != b { + let mut fields = Vec::new(); + let (ja, jb) = (a.to_json(), b.to_json()); + for key in [ + "kind", + "boundary", + "ticks", + "brainTicks", + "remainder", + "decision", + "telemetry", + "spikes", + "state", + ] { + if ja[key] != jb[key] { + fields.push(format!("{key}: {} != {}", ja[key], jb[key])); + } + } + return Err(format!( + "record {} ({}) differs: {}", + a.index, + a.kind, + fields.join("; ") + )); + } + } + if left.len() != right.len() { + return Err(format!("{} records against {}", left.len(), right.len())); + } + Ok(()) +} + +/// A source of reference records for a script. +/// +/// [`DirectSource`] and [`RestoredSource`] are the two. FND-01's `FLY_TRACE` records digests +/// rather than full records, so it is a check ([`check_against_trace`]) rather than a source. +pub trait ReferenceSource { + fn records(&mut self, script: &LegacyScript) -> Result, String>; +} + +// ------------------------------------------------------------------------------------------- +// The direct reference: NeuralAgent in `Sim::step_frame` order + +/// `NeuralAgent` driven the way `flysim::simloop::Sim` drives it, transcribed line by line from +/// `fresh_start`, `step_frame`, `recover` and `try_restore` (since FND-01, one type: +/// `flysim::frame::LegacyFrame`'s `initialize`, `transition`, `rollback` and `restore`, whose two +/// reorderings touch disjoint state), with the emulator, adapter and macro layer replaced by the +/// script's recorded outputs. +pub struct DirectReference { + dataset: Arc, + agent: NeuralAgent, + macro_channels: Vec, + // `Sim`'s own fields. + remainder: f64, + location: Option, + held_channel: Option, + blocked_since_ms: f64, + frame_buffer: Vec, + /// What the adapter and the macro layer would report after the last frame. + boot: bool, + bound: Vec, + /// Reinforcement calls, for `learning.updates`. + reinforcements: u64, +} + +impl DirectReference { + fn build(dataset: Arc, macro_channels: &[String]) -> Result { + let channels: Vec<&str> = macro_channels.iter().map(String::as_str).collect(); + let mut config = + CoreAgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels)); + config.warmup_ms = gameboy::WARMUP_MS; + NeuralAgent::new(dataset, config).map_err(|e| e.to_string()) + } + + /// `Sim::boot` with no checkpoint: `fresh_start` warms up on the setup frame. + pub fn fresh( + dataset: Arc, + script: &LegacyScript, + ) -> Result<(DirectReference, ParityRecord), String> { + let mut agent = DirectReference::build(dataset.clone(), &script.macro_channels)?; + let frame = script.frames[script.initial_frame].clone(); + agent.warmup(Some(&frame)).map_err(|e| e.to_string())?; + let reference = DirectReference { + dataset, + agent, + macro_channels: script.macro_channels.clone(), + remainder: 0.0, + location: None, + held_channel: None, + blocked_since_ms: 0.0, + frame_buffer: frame, + boot: script.initial_context.boot, + bound: script.initial_context.bound.clone(), + reinforcements: 0, + }; + let record = reference.record(0, "initialize", 0, gameboy::WARMUP_MS, None, None); + Ok((reference, record)) + } + + fn record( + &self, + index: usize, + kind: &'static str, + boundary: u64, + ticks: u64, + decision: Option, + spikes: Option, + ) -> ParityRecord { + ParityRecord { + index, + kind, + boundary, + ticks, + brain_ticks: self.agent.network.ms as u64, + remainder: legacy_remainder_to_rational(self.remainder).expect("a legacy remainder"), + decision, + telemetry: Some(telemetry_of( + &self.agent, + self.agent.network.ms as u64, + self.reinforcements, + )), + spikes, + state: None, + } + } + + /// The full state as `Sim::checkpoint` exports it: the loop owns the remainder. + pub fn state_digest(&self) -> Digest { + let mut state = self.agent.export_state(); + state.remainder = self.remainder; + state_digest(&state) + } + + /// `drain_commands` (sugar) and then `Sim::step_frame`'s agent half. + fn frame( + &mut self, + sugar: &[f64], + frame: &[u8], + rewards: &[RewardEvent], + next: &ReadoutContext, + ) -> (u64, ChannelsDecision, Digest) { + // Commands: `self.agent.network.stimulate(duration)`. + for duration in sugar { + self.agent.network.stimulate(*duration); + } + // 2. Step the brain. + self.remainder += self.agent.ms_per_frame; + let steps = self.remainder.floor(); + self.remainder -= steps; + let since = self.agent.network.ms; + self.agent.network.step(steps as u64); + // 3. Decode. + let boot = self.boot; + let ms = self.agent.network.ms; + let rates = self.agent.network.rates.clone(); + let blocked_ms = self.agent.decoder.blocked_ms(); + let blocked = (blocked_ms > 0.0 && ms - self.blocked_since_ms >= blocked_ms) + .then(|| self.agent.decoder.current()) + .flatten() + .map(str::to_string); + let bound = (!self.macro_channels.is_empty()).then(|| self.bound.clone()); + let active = + self.agent + .decoder + .decode_bound(&rates, ms, boot, blocked.as_deref(), bound.as_deref()); + let held = self.agent.decoder.current().map(str::to_string); + if held != self.held_channel { + self.held_channel = held; + self.blocked_since_ms = ms; + } + let mask = to_button_mask(&active); + let decision = channels_decision(&active, &self.bound); + debug_assert_eq!(u32::from(decision.mask()), mask); + // 5. Run a frame (recorded), 6. set the visual frame from it. + self.frame_buffer.copy_from_slice(frame); + let (width, height) = (self.agent.frame.width, self.agent.frame.height); + self.agent + .network + .set_visual_frame(&self.frame_buffer, width, height); + // 7. Sample rewards (recorded), 8. stimulate once per event, 9. reinforce with the sum. + let ms = self.agent.network.ms; + let mut total = 0.0; + for event in rewards { + self.agent.network.stimulate(event.stimulation_ms); + total += event.value; + } + if self.agent.network.plasticity.enabled { + self.agent.network.plasticity.reinforce(total, ms); + self.reinforcements += 1; + } + // `observe` (recorded as the next context's bound) and the cooldown's other reset. + self.boot = next.boot; + self.bound = next.bound.clone(); + let location = next.location; + if location.is_some() && location != self.location { + self.location = location; + self.blocked_since_ms = ms; + } + let spikes = digest_of_bytes(&spike_bitset(&self.agent.network.last_spike_ms, since, ms)); + (steps as u64, decision, spikes) + } + + /// `Sim::recover`: `recover_game`'s neural half, then the loop's own transients. + fn rollback(&mut self, frame: &[u8], context: &ReadoutContext) { + let ms = self.agent.network.ms; + self.agent.decoder.clear_holds(ms); + let ms = self.agent.network.ms; + self.agent.network.plasticity.clear_eligibility(ms); + let (width, height) = (self.agent.frame.width, self.agent.frame.height); + self.agent.network.set_visual_frame(frame, width, height); + self.frame_buffer.copy_from_slice(frame); + self.location = context.location; + self.held_channel = None; + self.blocked_since_ms = self.agent.network.ms; + self.boot = context.boot; + self.bound = context.bound.clone(); + } + + /// A service restart onto the last checkpoint: `Sim::boot`'s fresh fields, then + /// `try_restore`'s agent half. The executor observes the restored world before the first + /// frame, which is the context this reference already holds. + fn restore(&mut self) -> Result<(), String> { + let mut state = self.agent.export_state(); + state.remainder = self.remainder; + let mut agent = DirectReference::build(self.dataset.clone(), &self.macro_channels)?; + agent.import_state(&state).map_err(|e| e.to_string())?; + self.agent = agent; + self.remainder = state.remainder; + let (width, height) = (self.agent.frame.width, self.agent.frame.height); + self.agent + .network + .set_visual_frame(&self.frame_buffer, width, height); + self.location = None; + self.held_channel = None; + self.blocked_since_ms = 0.0; + Ok(()) + } +} + +/// [`ReferenceSource`] over a dataset directory. +pub struct DirectSource { + pub dataset: Arc, +} + +impl ReferenceSource for DirectSource { + fn records(&mut self, script: &LegacyScript) -> Result, String> { + let (reference, first) = DirectReference::fresh(self.dataset.clone(), script)?; + reference.run(first, script) + } +} + +/// [`ReferenceSource`] from a legacy agent state (a `FLYSIM01` checkpoint's), the way the +/// stream restores after a restart: `LegacyFrame::restore` into a fresh process's transient. +pub struct RestoredSource { + pub dataset: Arc, + pub state: flybrain_core::agent::AgentState, +} + +impl ReferenceSource for RestoredSource { + fn records(&mut self, script: &LegacyScript) -> Result, String> { + let mut agent = DirectReference::build(self.dataset.clone(), &script.macro_channels)?; + agent.import_state(&self.state).map_err(|e| e.to_string())?; + let frame = script.frames[script.initial_frame].clone(); + let (width, height) = (agent.frame.width, agent.frame.height); + agent.network.set_visual_frame(&frame, width, height); + let reference = DirectReference { + dataset: self.dataset.clone(), + agent, + macro_channels: script.macro_channels.clone(), + remainder: self.state.remainder, + location: None, + held_channel: None, + blocked_since_ms: 0.0, + frame_buffer: frame, + boot: script.initial_context.boot, + bound: script.initial_context.bound.clone(), + reinforcements: legacy_reinforcements(&self.state), + }; + let mut first = reference.record(0, "restore", 0, 0, None, None); + first.telemetry = None; + first.state = Some(reference.state_digest()); + reference.run(first, script) + } +} + +impl DirectReference { + fn run( + mut self, + first: ParityRecord, + script: &LegacyScript, + ) -> Result, String> { + let reference = &mut self; + let mut records = vec![first]; + let mut boundary = 0u64; + for (index, step) in script.steps.iter().enumerate() { + let mut record = match step { + ScriptStep::Frame { + sugar, + frame, + rewards, + next_context, + } => { + let (ticks, decision, spikes) = + reference.frame(sugar, &script.frames[*frame], rewards, next_context); + boundary += 1; + reference.record( + index + 1, + "frame", + boundary, + ticks, + Some(decision), + Some(spikes), + ) + } + ScriptStep::Rollback { frame, context } => { + reference.rollback(&script.frames[*frame], context); + reference.record(index + 1, "rollback", boundary, 0, None, None) + } + ScriptStep::Restore => { + reference.restore()?; + let mut record = + reference.record(index + 1, "restore", boundary, 0, None, None); + // An ActivateRestore reply carries no telemetry; the record says so. + record.telemetry = None; + record.state = Some(reference.state_digest()); + record + } + }; + if script.checkpoints.contains(&index) { + record.state = Some(reference.state_digest()); + } + records.push(record); + } + Ok(records) + } +} + +// ------------------------------------------------------------------------------------------- +// The worker side: a launched LegacyAgentWorker driven over the bus + +const DRIVER_CLIENT: &str = "coordinator"; +const MAX_GENERATIONS: u32 = 8; + +fn agent_service(agent_id: &Id) -> String { + format!("agent.{agent_id}") +} + +fn agent_client(agent_id: &Id, generation: u32) -> String { + if generation <= 1 { + format!("worker-{agent_id}") + } else { + format!("worker-{agent_id}-r{generation}") + } +} + +fn grants(f: impl FnOnce(&mut Grants)) -> Grants { + let mut g = Grants::default(); + f(&mut g); + g +} + +/// One legacy agent the rig launches. +#[derive(Clone, Debug)] +pub struct RigAgent { + pub agent_id: Id, + pub port_id: Id, + pub dataset_dir: PathBuf, + pub profile: LegacyProfileKind, + pub macro_channels: Vec, + pub worker_threads: usize, +} + +/// A router, a launcher in one execution mode and the legacy agents it started: the smallest +/// composition that runs `LegacyAgentWorker` under `fly-session`'s own supervisor. The +/// coordinator's part is played by [`AgentDriver`]s on one bus client. +pub struct LegacyRig { + pub launcher: Launcher, + pub client: Client, + pub session_id: Id, + pub mode: ExecutionMode, + agents: BTreeMap, +} + +impl LegacyRig { + pub async fn start( + root: &Path, + mode: ExecutionMode, + agents: &[RigAgent], + ) -> Result { + let session_id = id("legacy"); + let store_root = root.join("store"); + let sockets = root.join("sockets"); + std::fs::create_dir_all(&sockets).map_err(|e| format!("sockets: {e}"))?; + let mut policy = Policy::closed() + .client( + DRIVER_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("agent.")]), + ) + .client( + SUPERVISOR_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("agent.")]), + ); + for agent in agents { + let service = agent_service(&agent.agent_id); + for generation in 1..=MAX_GENERATIONS { + policy = policy.client( + &agent_client(&agent.agent_id, generation), + grants(|g| g.register = vec![Pattern::exact(&service)]), + ); + } + } + let mut config = RouterConfig::new(&store_root); + config.policy = policy; + let router = Router::new(config).map_err(|e| format!("router: {e}"))?; + let total = 1 + agents.iter().map(|a| a.worker_threads).sum::(); + let budget = ThreadBudget::new(total, 1).map_err(|e| e.message)?; + let launcher = Launcher::start(router, mode, Via::Unix, &store_root, &sockets, budget) + .await + .map_err(|e| format!("launcher: {}", e.message))?; + let client = launcher + .connect(DRIVER_CLIENT) + .await + .map_err(|e| format!("connect: {}", e.message))?; + let mut rig = LegacyRig { + launcher, + client, + session_id, + mode, + agents: BTreeMap::new(), + }; + for agent in agents { + rig.agents + .insert(agent.agent_id.clone(), (agent.clone(), 0)); + rig.launch(&agent.agent_id).await?; + } + Ok(rig) + } + + async fn launch(&mut self, agent_id: &Id) -> Result { + let (agent, generation) = self.agents.get_mut(agent_id).ok_or("unknown agent")?; + *generation += 1; + let spec = LegacyAgentLaunch { + session_id: self.session_id.clone(), + agent_id: agent.agent_id.clone(), + port_id: agent.port_id.clone(), + incarnation_id: parse_id(&format!("{}-inc-{generation}", agent.agent_id))?, + worker_threads: agent.worker_threads, + dataset_dir: agent.dataset_dir.clone(), + profile: agent.profile, + macro_channels: agent.macro_channels.clone(), + client_id: agent_client(&agent.agent_id, *generation), + service: agent_service(&agent.agent_id), + }; + self.launcher + .launch_legacy_agent(spec) + .await + .map_err(|e| e.message)?; + Ok(self.worker_ref(agent_id)) + } + + pub fn worker_ref(&self, agent_id: &Id) -> WorkerRef { + self.launcher + .worker(agent_id) + .expect("launched") + .worker_ref() + } + + /// Stops an agent's worker and starts its replacement: a new process in process mode, with + /// a new incarnation and a new client identity, uninitialized. + pub async fn replace(&mut self, agent_id: &Id) -> Result { + self.launcher.reap(agent_id, &id("replaced")).await; + self.launch(agent_id).await + } + + pub async fn stop(mut self) { + self.launcher.reap_all(&id("done")).await; + } + + /// A driver for one agent, playing the coordinator's part. + pub fn driver(&self, agent_id: &Id, script: &LegacyScript) -> AgentDriver { + let (agent, _) = &self.agents[agent_id]; + AgentDriver { + client: self.client.clone(), + target: self.worker_ref(agent_id), + session_id: self.session_id.clone(), + agent_id: agent_id.clone(), + profile: agent.profile.profile(), + epoch_serial: 1, + boundary: 0, + serials: Serials::default(), + context: script.initial_context.to_typed(), + frames: script.frames.clone(), + captures: 0, + remainder: RationalNs::ZERO, + } + } +} + +fn domain(e: DomainError) -> String { + format!("{:?}: {}", e.code, e.message) +} + +/// The coordinator's side of one agent: scopes, request serials, frame artifacts and the +/// context it last sent. +pub struct AgentDriver { + client: Client, + target: WorkerRef, + session_id: Id, + agent_id: Id, + profile: LegacyAgentProfile, + epoch_serial: u32, + boundary: u64, + serials: Serials, + context: TypedValue, + frames: Arc>>, + captures: u64, + /// The remainder the last Prepare reported: a rollback keeps it. + remainder: RationalNs, +} + +/// A captured payload, held for a restore. +pub struct Captured { + pub result: CaptureResult, + pub artifact: flybus::Artifact, + pub bytes: Vec, + pub scope: Scope, +} + +impl AgentDriver { + fn epoch(&self) -> Id { + id(&format!("e{}", self.epoch_serial)) + } + + fn scope(&self) -> Scope { + scope_at(&self.session_id, &self.epoch(), self.boundary) + } + + async fn frame_input( + &self, + frame: usize, + boundary: u64, + ) -> Result<(SensoryInput, flybus::Artifact), String> { + let artifact = crate::media::seal_copy( + &self.client, + crate::media::FRAME_CONTENT_TYPE.to_owned(), + &self.frames[frame], + ) + .await + .map_err(domain)?; + let input = SensoryInput { + boundary, + views: vec![ViewRef { + view_id: gameboy::VIEW_ID.to_owned(), + produced_step: boundary, + pixels: artifact.reference().clone(), + }], + structured: None, + }; + Ok((input, artifact)) + } + + async fn call( + &mut self, + method: &str, + scope: Option, + params: Value, + attachments: &[(&str, &flybus::Artifact)], + want: &[&str], + ) -> Result { + let request_id = self.serials.next(&self.target.service); + let want: Vec = want.iter().map(|w| (*w).to_owned()).collect(); + let reply = call( + &self.client, + &self.target, + method, + scope, + object(params), + attachments, + request_id, + &want, + ) + .await + .map_err(|e| format!("{method}: {}", domain(e)))?; + reply + .result() + .map_err(|e| format!("{method}: {}", domain(e)))?; + Ok(reply) + } + + /// One call with any params, its domain outcome returned as it stands: for tests that + /// need the worker to refuse something. + pub async fn call_raw( + &mut self, + method: &str, + scope: Option, + params: Value, + attachments: &[(&str, &flybus::Artifact)], + ) -> Result { + let request_id = self.serials.next(&self.target.service); + call( + &self.client, + &self.target, + method, + scope, + object(params), + attachments, + request_id, + &[], + ) + .await + } + + /// The same request again, same id and body: a domain retry. + pub async fn retry_raw( + &mut self, + request_id: DomainRequestId, + method: &str, + scope: Option, + params: Value, + ) -> Result { + call( + &self.client, + &self.target, + method, + scope, + object(params), + &[], + request_id, + &[], + ) + .await + } + + /// A sealed frame from the script's pool, as a sensory input observing `boundary`. + pub async fn input( + &self, + frame: usize, + boundary: u64, + ) -> Result<(SensoryInput, flybus::Artifact), String> { + self.frame_input(frame, boundary).await + } + + /// The scope of the committed boundary this driver is at. + pub fn current_scope(&self) -> Scope { + self.scope() + } + + /// Moves the driver to the next epoch without telling the worker, to address it wrongly. + pub fn bump_epoch(&mut self) { + self.epoch_serial += 1; + } + + pub fn context(&self) -> &TypedValue { + &self.context + } + + pub fn profile(&self) -> &AssetRef { + &self.profile.asset + } + + async fn acknowledge(&mut self, request_id: DomainRequestId) -> Result<(), String> { + let params = AcknowledgeParams { + request_ids: vec![request_id], + }; + self.call("Worker.Acknowledge", None, params.to_json(), &[], &[]) + .await + .map(|_| ()) + } + + pub async fn initialize(&mut self, initial_frame: usize) -> Result { + let (input, artifact) = self.frame_input(initial_frame, 0).await?; + let params = AgentInitializeParams { + agent_id: self.agent_id.clone(), + profile: self.profile.asset.clone(), + seed: LEGACY_SEED, + initial_input: input, + initial_decision_context: self.context.clone(), + worker_threads: 1, + }; + let reply = self + .call( + "Agent.Initialize", + Some(self.scope()), + params.to_json(), + &[("view.lcd", &artifact)], + &[], + ) + .await?; + let result: AgentInitializeResult = reply.parse().map_err(domain)?; + if result + .telemetry + .rates + .iter() + .map(|r| r.role_id.as_str()) + .ne(result.graph.rate_roles.iter().map(String::as_str)) + { + return Err("telemetry rates are not in AgentGraph.rateRoles order".to_owned()); + } + self.acknowledge(reply.request_id).await?; + Ok(ParityRecord { + index: 0, + kind: "initialize", + boundary: 0, + ticks: result.warmup_ticks, + brain_ticks: result.telemetry.brain_ticks, + remainder: RationalNs::ZERO, + decision: None, + telemetry: Some(result.telemetry), + spikes: None, + state: None, + }) + } + + /// Prepare then Commit: one transition. + pub async fn frame( + &mut self, + index: usize, + sugar: &[f64], + frame: usize, + rewards: &[RewardEvent], + next_context: &ReadoutContext, + ) -> Result { + let k = self.boundary; + let prepare = PrepareParams { + agent_id: self.agent_id.clone(), + profile_digest: self.profile.asset.digest.clone(), + interval: gameboy::step_duration(), + decision_context_digest: self.context.digest(), + pre_step_stimulations: sugar + .iter() + .enumerate() + .map(|(n, ms)| Stimulus { + id: id(&format!("sugar-{k}-{n}")), + kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(), + duration_ms: *ms, + }) + .collect(), + }; + let reply = self + .call( + "Agent.Prepare", + Some(self.scope()), + prepare.to_json(), + &[], + &[], + ) + .await?; + let prepared: PreparedDecision = reply.parse().map_err(domain)?; + let decision = ChannelsDecision::from_typed(&prepared.decision).map_err(|e| e.0)?; + + let (input, artifact) = self.frame_input(frame, k + 1).await?; + let next = next_context.to_typed(); + let commit = CommitParams { + agent_id: self.agent_id.clone(), + prepared_request_id: reply.request_id.clone(), + next_input: input, + next_decision_context: next.clone(), + rewards: rewards + .iter() + .enumerate() + .map(|(n, e)| Reward { + event_id: id(&format!("ev-{k}-{n}")), + rule_id: id("toy"), + value: e.value, + }) + .collect(), + task_stimulations: rewards + .iter() + .enumerate() + .map(|(n, e)| Stimulus { + id: id(&format!("ev-{k}-{n}")), + kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(), + duration_ms: e.stimulation_ms, + }) + .collect(), + }; + let reply = self + .call( + "Agent.Commit", + Some(self.scope()), + commit.to_json(), + &[("view.lcd", &artifact)], + &[SPIKES_ATTACHMENT], + ) + .await?; + let result: AgentCommitResult = reply.parse().map_err(domain)?; + if result.committed_step != k + 1 || result.decision_context_digest != next.digest() { + return Err(format!( + "Agent.Commit acknowledged {} with another context", + result.committed_step + )); + } + let spikes = match reply.artifacts.get(SPIKES_ATTACHMENT) { + Some(artifact) => digest_of_bytes(&artifact.read_all().await.map_err(|e| e.message)?), + None => return Err("Agent.Commit carried no spike bitset".to_owned()), + }; + self.context = next; + self.boundary = k + 1; + self.remainder = prepared.remainder; + Ok(ParityRecord { + index, + kind: "frame", + boundary: k + 1, + ticks: prepared.ticks_advanced, + brain_ticks: prepared.brain_ticks, + remainder: prepared.remainder, + decision: Some(decision), + telemetry: Some(result.telemetry), + spikes: Some(spikes), + state: None, + }) + } + + /// `legacy-ratchet-rollback-v1`'s agent half, under a new epoch at the same boundary. + pub async fn rollback( + &mut self, + index: usize, + frame: usize, + context: &ReadoutContext, + ) -> Result { + let prior = self.epoch(); + self.epoch_serial += 1; + let (input, artifact) = self.frame_input(frame, self.boundary).await?; + let typed = context.to_typed(); + let params = AgentRollbackParams { + agent_id: self.agent_id.clone(), + prior_epoch: prior, + policy: ROLLBACK_POLICY.to_owned(), + input, + decision_context: typed.clone(), + }; + let reply = self + .call( + METHOD_AGENT_ROLLBACK, + Some(self.scope()), + params.to_json(), + &[("view.lcd", &artifact)], + &[], + ) + .await?; + let result: AgentRollbackResult = reply.parse().map_err(domain)?; + result + .validate_against_scope(&self.scope()) + .map_err(|e| e.0)?; + self.context = typed; + Ok(ParityRecord { + index, + kind: "rollback", + boundary: self.boundary, + ticks: 0, + brain_ticks: result.telemetry.brain_ticks, + remainder: self.remainder, + decision: None, + telemetry: Some(result.telemetry), + spikes: None, + state: None, + }) + } + + /// `State.Capture` at the committed boundary. + pub async fn capture(&mut self) -> Result { + self.captures += 1; + let scope = self.scope(); + let params = CaptureParams { + checkpoint_id: id(&format!("cp-{}", self.captures)), + }; + let reply = self + .call( + "State.Capture", + Some(scope.clone()), + params.to_json(), + &[], + &[crate::state::PAYLOAD_ATTACHMENT], + ) + .await?; + let result: CaptureResult = reply.parse().map_err(domain)?; + let artifact = reply + .artifacts + .get(crate::state::PAYLOAD_ATTACHMENT) + .cloned() + .ok_or("State.Capture carried no payload")?; + let bytes = artifact.read_all().await.map_err(|e| e.message)?; + self.acknowledge(reply.request_id).await?; + Ok(Captured { + result, + artifact, + bytes, + scope, + }) + } + + /// A group restore into `target`, a fresh replacement worker, under a new epoch. + pub async fn restore_into( + &mut self, + target: WorkerRef, + captured: &Captured, + ) -> Result<(), String> { + self.target = target; + self.epoch_serial += 1; + let params = StageRestoreParams { + checkpoint_id: captured.result.checkpoint_id.clone(), + source_scope: captured.scope.clone(), + compatibility_digest: captured.result.compatibility_digest.clone(), + payload: captured.artifact.reference().clone(), + }; + let reply = self + .call( + "State.StageRestore", + Some(self.scope()), + params.to_json(), + &[(crate::state::PAYLOAD_ATTACHMENT, &captured.artifact)], + &[], + ) + .await?; + let staged: StageRestoreResult = reply.parse().map_err(domain)?; + self.acknowledge(reply.request_id).await?; + let params = ActivateRestoreParams { + restore_token: staged.restore_token, + }; + let reply = self + .call("State.ActivateRestore", None, params.to_json(), &[], &[]) + .await?; + let activated: ActivateRestoreResult = reply.parse().map_err(domain)?; + if activated.committed_step != self.boundary { + return Err("State.ActivateRestore landed on another boundary".to_owned()); + } + self.acknowledge(reply.request_id).await + } + + /// Starts the agent from a legacy agent state -- a `FLYSIM01` checkpoint's `agent`, with + /// the loop's frame remainder in it -- instead of from a warm-up, the way the stream restores + /// after a restart (`legacy-transient-reset`). + /// + /// This is the test side of an import nothing ships yet: the worker is initialized, its own + /// capture is taken as the template for the session member, the agent chunks and the clock + /// are replaced with `state`'s, and the result is restored into a replacement worker through + /// the ordinary `State.StageRestore` / `ActivateRestore`, which validates it like any other + /// payload. `learning.updates` starts at [`legacy_reinforcements`], because `FLYSIM01` does + /// not record every reinforcement call. + pub async fn seed_from_legacy_state( + &mut self, + rig: &mut LegacyRig, + agent_id: &Id, + initial_frame: usize, + state: &flybrain_core::agent::AgentState, + ) -> Result { + self.initialize(initial_frame).await?; + let template = self.capture().await?; + let bytes = legacy_state_payload(&template.bytes, state, &self.context)?; + let digest = digest_of_bytes(&bytes); + let artifact = crate::state::seal_payload(&self.client, &bytes, &digest) + .await + .map_err(domain)?; + let seeded = Captured { + result: CaptureResult { + payload: artifact.reference().clone(), + ..template.result + }, + artifact, + bytes, + scope: template.scope, + }; + let target = rig.replace(agent_id).await?; + self.restore_into(target, &seeded).await?; + let after = self.capture().await?; + let restored = payload_state_digest(&after.bytes)?; + if restored != state_digest(state) { + return Err("the seeded worker's state is not the legacy state".to_owned()); + } + self.remainder = legacy_remainder_to_rational(state.remainder)?; + Ok(ParityRecord { + index: 0, + kind: "restore", + boundary: self.boundary, + ticks: 0, + brain_ticks: state.network.ms as u64, + remainder: self.remainder, + decision: None, + telemetry: None, + spikes: None, + state: Some(restored), + }) + } +} + +/// The reinforcement calls to start a legacy agent state's `learning.updates` at. +/// +/// `FLYSIM01` records `plasticity.updates`, the reinforcements that moved a gain, but not every +/// call, and the contract requires `learning.changed <= learning.updates`. An import that starts +/// the call count at zero makes the first telemetry unreadable (found on the row-58 stream +/// checkpoint: `changed` is in the thousands), so it starts at the recorded count, a lower bound +/// on the calls actually made. +pub fn legacy_reinforcements(state: &flybrain_core::agent::AgentState) -> u64 { + state.network.plasticity.updates as u64 +} + +/// A worker capture with its agent chunks and clock replaced by a legacy agent state, and its +/// context by `context`: see [`AgentDriver::seed_from_legacy_state`]. +pub fn legacy_state_payload( + template: &[u8], + state: &flybrain_core::agent::AgentState, + context: &TypedValue, +) -> Result, String> { + let mut session = captured_session(template)?; + let remainder = legacy_remainder_to_rational(state.remainder)?; + session["accumulator"]["remainder"] = remainder.to_json(); + session["accumulator"]["executedTicks"] = json!((state.network.ms as u64).to_string()); + session["reinforcements"] = json!(legacy_reinforcements(state).to_string()); + session["context"] = context.to_json(); + let chunks = agent_to_chunks(state); + let mut manifest = chunks.manifest; + manifest.set( + "session", + flybrain_core::json::JsonValue::parse(&session.to_string()).map_err(|e| e.to_string())?, + ); + flybrain_core::envelope::encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks) + .map_err(|e| e.to_string()) +} + +/// Runs a script against the rig's agent, recording what the coordinator observes. +pub async fn run_on_worker( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, +) -> Result, String> { + run_on_worker_from(rig, agent_id, script, None).await +} + +/// [`run_on_worker`], from a warm-up or, with `start`, from a legacy agent state +/// ([`AgentDriver::seed_from_legacy_state`]). +pub async fn run_on_worker_from( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, + start: Option<&flybrain_core::agent::AgentState>, +) -> Result, String> { + let mut driver = rig.driver(agent_id, script); + let first = match start { + None => driver.initialize(script.initial_frame).await?, + Some(state) => { + driver + .seed_from_legacy_state(rig, agent_id, script.initial_frame, state) + .await? + } + }; + let mut records = vec![first]; + for (index, step) in script.steps.iter().enumerate() { + let mut record = match step { + ScriptStep::Frame { + sugar, + frame, + rewards, + next_context, + } => { + driver + .frame(index + 1, sugar, *frame, rewards, next_context) + .await? + } + ScriptStep::Rollback { frame, context } => { + driver.rollback(index + 1, *frame, context).await? + } + ScriptStep::Restore => { + let captured = driver.capture().await?; + let target = rig.replace(agent_id).await?; + driver.restore_into(target, &captured).await?; + // The replacement's own capture: a restore is exact for everything captured. + let after = driver.capture().await?; + ParityRecord { + index: index + 1, + kind: "restore", + boundary: driver.boundary, + ticks: 0, + brain_ticks: captured_brain_ticks(&after.bytes)?, + remainder: captured_remainder(&after.bytes)?, + decision: None, + telemetry: None, + spikes: None, + state: Some(payload_state_digest(&after.bytes)?), + } + } + }; + if script.checkpoints.contains(&index) { + let captured = driver.capture().await?; + record.state = Some(payload_state_digest(&captured.bytes)?); + } + records.push(record); + } + Ok(records) +} + +fn captured_session(payload: &[u8]) -> Result { + let parts = decode_envelope(payload, PAYLOAD_MAGIC).map_err(|e| e.to_string())?; + let session = parts.manifest.get("session").ok_or("no session member")?; + serde_json::from_str(&session.stringify()).map_err(|e| e.to_string()) +} + +fn captured_brain_ticks(payload: &[u8]) -> Result { + captured_session(payload)?["accumulator"]["executedTicks"] + .as_str() + .and_then(|s| s.parse().ok()) + .ok_or_else(|| "no executedTicks".to_owned()) +} + +fn captured_remainder(payload: &[u8]) -> Result { + RationalNs::from_json(&captured_session(payload)?["accumulator"]["remainder"]).map_err(|e| e.0) +} + +/// The rows and the overall digest of a record sequence, as a golden file holds them. +pub fn golden_json(script: &LegacyScript, records: &[ParityRecord]) -> Value { + let all: Vec = records.iter().map(ParityRecord::to_json).collect(); + json!({ + "scenario": script.name, + "macroChannels": script.macro_channels, + "records": records.len(), + "digest": digest_of(&Value::Array(all)).expect("records canonicalize"), + "rows": records.iter().map(ParityRecord::row).collect::>(), + }) +} + +// ------------------------------------------------------------------------------------------- +// FND-01's FLY_TRACE: the running legacy loop as a reference + +/// The format name on the first line of a `FLY_TRACE` file (`flysim::trace::FORMAT`). +pub const FRAME_TRACE_FORMAT: &str = "flysim-legacy-frame-trace-v1"; + +/// One sugar or operator pulse admitted at the top of a legacy frame, before its ticks. +#[derive(Clone, Debug, PartialEq)] +pub enum TraceAdmission { + Sugar { + duration_ms: f64, + }, + /// `POST /reward`: `plasticity.reinforce(value)` at admission. It has no session-framework + /// counterpart, so a script cannot carry it and [`check_against_trace`] refuses a trace + /// that has one. + RewardPulse { + value: f64, + }, +} + +/// The agent-observable half of one `FLY_TRACE` transition line, `behaviour` only. +#[derive(Clone, Debug, PartialEq)] +pub struct TraceTransition { + pub step: u64, + pub admissions: Vec, + pub ticks: u64, + pub brain_ticks: u64, + pub remainder: RationalNs, + pub rates_digest: String, + pub spikes_digest: String, + pub spike_count: u64, + /// The decode's active set, as the executor was given it. + pub decision: Vec, + /// The mask the emulator was given: the executor's, not the decision's. + pub mask: u32, + pub framebuffer_digest: String, + /// `(value, stimulationMs)` in adapter order. + pub rewards: Vec, + /// The boundary actions, `save-slot` and `rollback`, in order. + pub boundary_actions: Vec, +} + +/// Reads a `FLY_TRACE` file: the header, an optional start-boundary line, then one line per +/// transition. +pub fn read_frame_trace(text: &str) -> Result, String> { + let mut lines = text.lines().filter(|l| !l.trim().is_empty()); + let header: Value = serde_json::from_str(lines.next().ok_or("an empty trace")?) + .map_err(|e| format!("the trace header: {e}"))?; + if header["format"] != FRAME_TRACE_FORMAT { + return Err(format!( + "the trace is {}, not {FRAME_TRACE_FORMAT}", + header["format"] + )); + } + let text_u64 = |v: &Value, key: &str| -> Result { + v[key] + .as_str() + .and_then(|s| s.parse().ok()) + .ok_or_else(|| format!("{key} is not a U64 string")) + }; + let string = |v: &Value, key: &str| -> Result { + v[key] + .as_str() + .map(str::to_owned) + .ok_or_else(|| format!("{key} is not a string")) + }; + let mut out = Vec::new(); + for (n, line) in lines.enumerate() { + let value: Value = + serde_json::from_str(line).map_err(|e| format!("trace line {}: {e}", n + 2))?; + let Some(b) = value.get("behaviour") else { + // The start boundary's captures: operational only. + continue; + }; + let admissions = b["admissions"] + .as_array() + .ok_or("admissions is not a list")? + .iter() + .map(|a| match a["kind"].as_str() { + Some("sugar") => a["durationMs"] + .as_f64() + .map(|duration_ms| TraceAdmission::Sugar { duration_ms }) + .ok_or_else(|| "a sugar admission without durationMs".to_owned()), + Some("reward") => a["value"] + .as_f64() + .map(|value| TraceAdmission::RewardPulse { value }) + .ok_or_else(|| "a reward admission without value".to_owned()), + other => Err(format!("an admission of kind {other:?}")), + }) + .collect::, _>>()?; + let rewards = b["rewards"] + .as_array() + .ok_or("rewards is not a list")? + .iter() + .map(|r| { + Ok(RewardEvent { + value: r["value"].as_f64().ok_or("a reward without value")?, + stimulation_ms: r["stimulationMs"] + .as_f64() + .ok_or("a reward without stimulationMs")?, + }) + }) + .collect::, String>>()?; + let decision = b["decision"] + .as_array() + .ok_or("decision is not a list")? + .iter() + .map(|c| c.as_str().map(str::to_owned).ok_or("a decision channel")) + .collect::, _>>()?; + let boundary_actions = b["boundaryActions"] + .as_array() + .ok_or("boundaryActions is not a list")? + .iter() + .map(|a| { + a["kind"] + .as_str() + .map(str::to_owned) + .ok_or("an action kind") + }) + .collect::, _>>()?; + out.push(TraceTransition { + step: text_u64(b, "step")?, + admissions, + ticks: text_u64(b, "ticksAdvanced")?, + brain_ticks: text_u64(b, "brainTicks")?, + remainder: RationalNs::from_json(&b["remainder"]) + .map_err(|e| format!("remainder: {}", e.0))?, + rates_digest: string(b, "ratesDigest")?, + spikes_digest: string(b, "spikesDigest")?, + spike_count: b["spikeCount"].as_u64().ok_or("spikeCount")?, + decision, + mask: b["mask"] + .as_u64() + .and_then(|m| u32::try_from(m).ok()) + .ok_or("mask")?, + framebuffer_digest: string(b, "framebufferDigest")?, + rewards, + boundary_actions, + }); + } + Ok(out) +} + +/// `FLY_TRACE`'s `ratesDigest` of a telemetry's rates: per tracked role in the network's +/// order, the name's length (u32 LE), the name, and the rate's f64 bits (LE). The role id is +/// the role name (`legacy-rate-role-id-v1`). +pub fn trace_rates_digest(telemetry: &AgentTelemetry) -> Result { + let mut bytes = Vec::new(); + for sample in &telemetry.rates { + let name = gameboy::rate_role_name(&sample.role_id).map_err(|e| e.0)?; + bytes.extend_from_slice(&(name.len() as u32).to_le_bytes()); + bytes.extend_from_slice(name.as_bytes()); + bytes.extend_from_slice(&sample.hz.to_bits().to_le_bytes()); + } + Ok(digest_of_bytes(&bytes)) +} + +/// What a trace check covered. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TraceCheck { + pub transitions: usize, + pub sugar: usize, + pub rewards: usize, + pub rollbacks: usize, + pub macro_decisions: usize, + pub pressed: usize, + pub spikes: u64, +} + +/// Checks the records of a run of `script` -- the worker's, or [`DirectReference`]'s -- +/// against the `FLY_TRACE` of the legacy loop that produced the script. +/// +/// The trace carries digests and the behaviour fields, not the full telemetry, so this is a +/// check rather than a [`ReferenceSource`]. It holds the script to the trace first (the same +/// sugar, frames and reward events, a rollback exactly where the loop rolled back), then each +/// frame record to its transition: ticks, brain clock, exact remainder, the rates digest, the +/// spike-set digest, and the decision as `gameboy-channels-v1` of the decode's active set under +/// the context the step was decided in. +pub fn check_against_trace( + script: &LegacyScript, + records: &[ParityRecord], + trace: &[TraceTransition], +) -> Result { + if records.len() != script.steps.len() + 1 { + return Err(format!( + "{} records for {} steps", + records.len(), + script.steps.len() + )); + } + let mut check = TraceCheck::default(); + let mut transitions = trace.iter(); + let mut last: Option<&TraceTransition> = None; + let mut bound = script.initial_context.bound.clone(); + let mut previous_ticks = records[0].brain_ticks; + for (index, step) in script.steps.iter().enumerate() { + let record = &records[index + 1]; + let at = |what: String| format!("step {index} (record {}): {what}", index + 1); + match step { + ScriptStep::Frame { + sugar, + frame, + rewards, + next_context, + } => { + let t = transitions + .next() + .ok_or_else(|| at("the trace ended".to_owned()))?; + let admitted: Vec = sugar + .iter() + .map(|d| TraceAdmission::Sugar { duration_ms: *d }) + .collect(); + if t.admissions != admitted { + return Err(at(format!( + "the trace admitted {:?}, the script {admitted:?}", + t.admissions + ))); + } + if digest_of_bytes(&script.frames[*frame]) != t.framebuffer_digest { + return Err(at("the script's frame is not the loop's".to_owned())); + } + if &t.rewards != rewards { + return Err(at(format!( + "the trace rewarded {:?}, the script {rewards:?}", + t.rewards + ))); + } + if t.boundary_actions.iter().any(|a| a == "rollback") + != matches!( + script.steps.get(index + 1), + Some(ScriptStep::Rollback { .. }) + ) + { + return Err(at("the script's rollback is not where the loop's is".into())); + } + if record.kind != "frame" { + return Err(at(format!("a {} record for a frame", record.kind))); + } + let mut differ = Vec::new(); + if record.ticks != t.ticks { + differ.push(format!("ticks {} != {}", record.ticks, t.ticks)); + } + if record.brain_ticks != t.brain_ticks { + differ.push(format!( + "brainTicks {} != {}", + record.brain_ticks, t.brain_ticks + )); + } + if record.remainder != t.remainder { + differ.push(format!( + "remainder {:?} != {:?}", + record.remainder, t.remainder + )); + } + let telemetry = record + .telemetry + .as_ref() + .ok_or_else(|| at("a frame record without telemetry".to_owned()))?; + if trace_rates_digest(telemetry)? != t.rates_digest { + differ.push("ratesDigest".to_owned()); + } + if record.spikes.as_deref() != Some(t.spikes_digest.as_str()) { + differ.push("spikesDigest".to_owned()); + } + let want = channels_decision(&t.decision, &bound); + if record.decision.as_ref() != Some(&want) { + differ.push(format!( + "decision {:?} != {:?} (active {:?})", + record.decision, want, t.decision + )); + } + if !differ.is_empty() { + return Err(at(format!( + "differs from trace step {}: {}", + t.step, + differ.join("; ") + ))); + } + check.transitions += 1; + check.sugar += sugar.len(); + check.rewards += rewards.len(); + check.spikes += t.spike_count; + check.macro_decisions += usize::from(want.macro_channel.is_some()); + check.pressed += usize::from(want.mask() != 0); + bound = next_context.bound.clone(); + previous_ticks = record.brain_ticks; + last = Some(t); + } + ScriptStep::Rollback { frame, context } => { + let t = last.ok_or_else(|| at("a rollback before any frame".to_owned()))?; + if !t.boundary_actions.iter().any(|a| a == "rollback") { + return Err(at("the loop did not roll back here".to_owned())); + } + if record.kind != "rollback" || record.ticks != 0 { + return Err(at(format!("a {} record with ticks", record.kind))); + } + if record.brain_ticks != previous_ticks { + return Err(at("a rollback moved the brain clock".to_owned())); + } + // The slot's frame is the rolled-back world's, which the trace does not digest; + // the next transition's ticks and spikes are what it drives. + let _ = frame; + check.rollbacks += 1; + bound = context.bound.clone(); + } + ScriptStep::Restore => { + return Err(at( + "a restore splits a trace in two; check each process's trace".to_owned(), + )); + } + } + } + if let Some(t) = transitions.next() { + return Err(format!("the trace goes on at step {}", t.step)); + } + Ok(check) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_frame_pool_and_scripts_are_deterministic() { + assert_eq!(frame_pool(3, 7), frame_pool(3, 7)); + assert_ne!(frame_pool(3, 7)[0], frame_pool(3, 7)[1]); + let script = toy_macros_script(260); + assert_eq!( + script + .steps + .iter() + .filter(|s| matches!(s, ScriptStep::Rollback { .. })) + .count(), + 1 + ); + assert_eq!( + script + .steps + .iter() + .filter(|s| matches!(s, ScriptStep::Restore)) + .count(), + 1 + ); + for step in &script.steps { + if let ScriptStep::Frame { next_context, .. } = step { + next_context + .validate_against(&script.macro_channels) + .expect("a valid context"); + } + } + } +} diff --git a/services/flysim/crates/fly-session/src/lib.rs b/services/flysim/crates/fly-session/src/lib.rs index 6849001..fcb005e 100644 --- a/services/flysim/crates/fly-session/src/lib.rs +++ b/services/flysim/crates/fly-session/src/lib.rs @@ -29,6 +29,8 @@ pub mod dedup; pub mod environment; pub mod harness; pub mod launcher; +pub mod legacy_agent; +pub mod legacy_parity; pub mod measure; pub mod media; pub mod metrics; diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index e361af3..4451900 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -606,6 +606,13 @@ async fn execute( fn classify_default(method: &str) -> Option { match method { "Agent.Prepare" | "Agent.Commit" | "Environment.Advance" => Some(OpClass::StepMutation), + // The extension methods of `workers-v1` section 7 are mutations under the step operation + // key (`legacy-gameboy-v1` section 11): `SaveSlot` at `(e, k)`, `RestoreSlot` and + // `Agent.Rollback` at the new epoch `(e', k)`. A lost reply replays from the same cache + // rather than rolling back twice. + "Agent.Rollback" | "Environment.SaveSlot" | "Environment.RestoreSlot" => { + Some(OpClass::StepMutation) + } // `ipc-v1` section 5 retains lifecycle *and capture* replies until // `Worker.Acknowledge`. The restore methods join them: their replies carry a // once-only token and, for an environment, the restored observation's artifact, and a diff --git a/services/flysim/crates/fly-session/tests/legacy_agent.rs b/services/flysim/crates/fly-session/tests/legacy_agent.rs new file mode 100644 index 0000000..36c91a0 --- /dev/null +++ b/services/flysim/crates/fly-session/tests/legacy_agent.rs @@ -0,0 +1,885 @@ +//! AGENT-01: the legacy agent worker against the neural core driven directly, on the committed +//! toy connectome, under the launcher in every execution mode. +//! +//! `FLY_UPDATE_FIXTURES=1` rewrites the toy dataset and the goldens; otherwise the committed +//! files must be exactly what this build computes. + +use std::sync::Arc; + +use fly_session::ExecutionMode; +use fly_session::legacy_agent::{LegacyProfileKind, TOY_FINGERPRINT}; +use fly_session::legacy_parity::{ + self, DirectSource, LegacyRig, LegacyScript, ParityRecord, ReferenceSource, RigAgent, toy, +}; +use fly_session::types::id; +use flybrain_core::dataset::load_brain_dataset_from_dir; +use serde_json::Value; + +fn updating() -> bool { + std::env::var_os("FLY_UPDATE_FIXTURES").is_some() +} + +fn toy_agent(agent_id: &str, script: &LegacyScript) -> RigAgent { + RigAgent { + agent_id: id(agent_id), + port_id: id("p1"), + dataset_dir: toy::dir(), + profile: LegacyProfileKind::Toy, + macro_channels: script.macro_channels.clone(), + worker_threads: 1, + } +} + +fn reference(script: &LegacyScript) -> Vec { + let dataset = Arc::new(load_brain_dataset_from_dir(toy::dir()).expect("the toy dataset loads")); + DirectSource { dataset } + .records(script) + .expect("the reference runs") +} + +async fn on_worker(mode: ExecutionMode, script: &LegacyScript) -> Vec { + let root = tempfile::tempdir().expect("a temporary directory"); + let mut rig = LegacyRig::start(root.path(), mode, &[toy_agent("fly-a", script)]) + .await + .expect("the rig starts"); + let records = legacy_parity::run_on_worker(&mut rig, &id("fly-a"), script) + .await + .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + rig.stop().await; + records +} + +fn golden(script: &LegacyScript, records: &[ParityRecord]) { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("fixtures") + .join(format!("{}.golden.json", script.name)); + let mut text = + serde_json::to_string_pretty(&legacy_parity::golden_json(script, records)).expect("json"); + text.push('\n'); + if updating() { + std::fs::write(&path, &text).expect("write the golden"); + } + let found = std::fs::read_to_string(&path).expect("the committed golden"); + if found != text { + let want: Value = serde_json::from_str(&found).expect("golden json"); + let got: Value = serde_json::from_str(&text).expect("json"); + let rows = |v: &Value| -> Vec { + v["rows"] + .as_array() + .map(|a| { + a.iter() + .map(|r| r.as_str().unwrap_or("").to_owned()) + .collect() + }) + .unwrap_or_default() + }; + let first = rows(&want) + .into_iter() + .zip(rows(&got)) + .find(|(a, b)| a != b); + panic!( + "{} is stale (first differing row: {first:?}); rerun with FLY_UPDATE_FIXTURES=1", + path.display() + ); + } +} + +#[test] +fn the_committed_toy_dataset_is_what_the_generator_writes() { + let dir = toy::dir(); + if updating() { + toy::write(&dir).expect("write the toy dataset"); + } + for (name, bytes) in toy::files() { + let found = std::fs::read(dir.join(&name)).unwrap_or_else(|e| panic!("{name}: {e}")); + assert_eq!( + found, bytes, + "{name} is stale; rerun with FLY_UPDATE_FIXTURES=1" + ); + } + let dataset = load_brain_dataset_from_dir(&dir).expect("the toy dataset loads"); + assert_eq!( + dataset.fingerprint.as_deref(), + Some(TOY_FINGERPRINT), + "the toy profile embeds it" + ); +} + +/// The macros-mode scenario, in all three execution modes, against the direct reference and +/// the committed golden. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_macros_scenario_matches_the_reference_in_every_mode() { + let script = legacy_parity::toy_macros_script(260); + let want = reference(&script); + golden(&script, &want); + for mode in ExecutionMode::all() { + let got = on_worker(mode, &script).await; + legacy_parity::compare(&want, &got).unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + } +} + +/// Raw mode: no macro group, `bound` never masks, the decision never names a macro. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_raw_scenario_matches_the_reference_in_every_mode() { + let script = legacy_parity::toy_raw_script(80); + let want = reference(&script); + golden(&script, &want); + assert!(want.iter().all(|r| { + r.decision + .as_ref() + .is_none_or(|d| d.macro_channel.is_none()) + })); + for mode in ExecutionMode::all() { + let got = on_worker(mode, &script).await; + legacy_parity::compare(&want, &got).unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + } +} + +/// A second fly's script: the same shape, other frames and no rewards, so any gain, trace, RNG +/// or hold shared between the two would show in one of them. +fn quiet_twin(script: &LegacyScript) -> LegacyScript { + let mut twin = script.clone(); + twin.name = format!("{}-twin", script.name); + for step in &mut twin.steps { + if let legacy_parity::ScriptStep::Frame { + frame, + rewards, + sugar, + .. + } = step + { + *frame = (*frame + 3) % 8; + rewards.clear(); + sugar.clear(); + } + } + twin +} + +async fn step_one( + driver: &mut legacy_parity::AgentDriver, + index: usize, + step: &legacy_parity::ScriptStep, +) -> ParityRecord { + match step { + legacy_parity::ScriptStep::Frame { + sugar, + frame, + rewards, + next_context, + } => driver + .frame(index + 1, sugar, *frame, rewards, next_context) + .await + .expect("a frame"), + legacy_parity::ScriptStep::Rollback { frame, context } => driver + .rollback(index + 1, *frame, context) + .await + .expect("a rollback"), + legacy_parity::ScriptStep::Restore => unreachable!("the pair scripts do not restore"), + } +} + +/// Two flies in one composition, dispatched concurrently and then in reversed order, one of +/// them sweeping on two threads: each is exactly its own solo reference. No gains, RNG, holds +/// or pulse cross between agents, and neither dispatch order nor worker count moves a result. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn two_agents_share_nothing_whatever_the_dispatch_order_or_thread_count() { + let a_script = legacy_parity::toy_raw_script(60); + let b_script = quiet_twin(&a_script); + let a_want = reference(&a_script); + let b_want = reference(&b_script); + assert_ne!(a_want, b_want); + for (mode, reversed) in [ + (ExecutionMode::Thread, false), + (ExecutionMode::Process, true), + ] { + let root = tempfile::tempdir().expect("a temporary directory"); + let mut a_agent = toy_agent("fly-a", &a_script); + a_agent.worker_threads = 2; + let mut b_agent = toy_agent("fly-b", &b_script); + b_agent.port_id = id("p2"); + let rig = LegacyRig::start(root.path(), mode, &[a_agent, b_agent]) + .await + .expect("the rig starts"); + let mut a = rig.driver(&id("fly-a"), &a_script); + let mut b = rig.driver(&id("fly-b"), &b_script); + let mut a_got = vec![a.initialize(a_script.initial_frame).await.expect("a")]; + let mut b_got = vec![b.initialize(b_script.initial_frame).await.expect("b")]; + for index in 0..a_script.steps.len() { + let (ra, rb) = if reversed { + let rb = step_one(&mut b, index, &b_script.steps[index]).await; + let ra = step_one(&mut a, index, &a_script.steps[index]).await; + (ra, rb) + } else { + tokio::join!( + step_one(&mut a, index, &a_script.steps[index]), + step_one(&mut b, index, &b_script.steps[index]) + ) + }; + a_got.push(ra); + b_got.push(rb); + } + // Checkpoints are compared on the solo runs; here the per-step records are. + let strip = |records: &[ParityRecord]| -> Vec { + records + .iter() + .cloned() + .map(|mut r| { + r.state = None; + r + }) + .collect() + }; + legacy_parity::compare(&strip(&a_want), &a_got) + .unwrap_or_else(|e| panic!("{} fly-a: {e}", mode.label())); + legacy_parity::compare(&strip(&b_want), &b_got) + .unwrap_or_else(|e| panic!("{} fly-b: {e}", mode.label())); + rig.stop().await; + } +} + +mod refusals { + use super::*; + use fly_session::legacy_agent::LegacyAgentProfile; + use fly_session::types::*; + use fly_session_types::extensions::{ + AgentRollbackParams, ROLLBACK_CAPABILITY, ROLLBACK_POLICY, + }; + + fn code(reply: Result) -> ErrorCode { + match reply { + Err(e) => e.code, + Ok(reply) => match reply.result() { + Err(e) => e.code, + Ok(v) => panic!("expected a refusal, got {v}"), + }, + } + } + + async fn rig_with(root: &std::path::Path, agent: RigAgent) -> LegacyRig { + LegacyRig::start(root, ExecutionMode::InProcess, &[agent]) + .await + .expect("the rig starts") + } + + fn init_params( + driver: &legacy_parity::AgentDriver, + input: SensoryInput, + profile: AssetRef, + seed: i32, + ) -> serde_json::Value { + AgentInitializeParams { + agent_id: id("fly-a"), + profile, + seed, + initial_input: input, + initial_decision_context: driver.context().clone(), + worker_threads: 1, + } + .to_json() + } + + /// Initialize refuses another profile, a dataset that is not the profile's, a seed the + /// kernel version does not allow, and a context naming a channel the composition lacks. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn initialize_checks_the_profile_the_dataset_the_seed_and_the_context() { + let script = legacy_parity::toy_macros_script(4); + let root = tempfile::tempdir().expect("tmp"); + let rig = rig_with(root.path(), toy_agent("fly-a", &script)).await; + let mut driver = rig.driver(&id("fly-a"), &script); + let scope = driver.current_scope(); + let (input, frame) = driver.input(0, 0).await.expect("a frame"); + let production = LegacyAgentProfile::production().asset; + let params = init_params( + &driver, + input.clone(), + production, + legacy_parity::LEGACY_SEED, + ); + assert_eq!( + code( + driver + .call_raw( + "Agent.Initialize", + Some(scope.clone()), + params, + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::IdentityMismatch, + "another profile" + ); + let toy_profile = driver.profile().clone(); + let params = init_params(&driver, input.clone(), toy_profile.clone(), 7); + assert_eq!( + code( + driver + .call_raw( + "Agent.Initialize", + Some(scope.clone()), + params, + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::IncompatibleState, + "seed 7 would be another kernel version" + ); + let mut params = init_params( + &driver, + input.clone(), + toy_profile.clone(), + legacy_parity::LEGACY_SEED, + ); + let bad = fly_session_types::gameboy::ReadoutContext { + boot: true, + bound: vec!["macro_heal".to_owned()], + location: None, + }; + params["initialDecisionContext"] = bad.to_typed().to_json(); + assert_eq!( + code( + driver + .call_raw( + "Agent.Initialize", + Some(scope.clone()), + params, + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::InvalidArgument, + "a bound channel outside the composition" + ); + // Every refusal above was made before a model existed: the worker still initializes. + driver + .initialize(0) + .await + .expect("the worker is still uninitialized and accepts a good request"); + rig.stop().await; + + // A worker configured for the production profile, pointed at the toy connectome. + let root = tempfile::tempdir().expect("tmp"); + let mut agent = toy_agent("fly-a", &script); + agent.profile = LegacyProfileKind::Production; + let rig = rig_with(root.path(), agent).await; + let mut driver = rig.driver(&id("fly-a"), &script); + let (input, frame) = driver.input(0, 0).await.expect("a frame"); + let params = init_params( + &driver, + input, + LegacyAgentProfile::production().asset, + legacy_parity::LEGACY_SEED, + ); + let scope = driver.current_scope(); + assert_eq!( + code( + driver + .call_raw( + "Agent.Initialize", + Some(scope), + params, + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::IdentityMismatch, + "the toy connectome is not the dataset the production profile embeds" + ); + rig.stop().await; + } + + /// Prepare refuses another cadence and an undeclared stimulus kind; a retried Prepare + /// replays its decision without ticking again; Rollback refuses the wrong epochs and a + /// prepared agent; StageRestore refuses another fly's compatibility. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn step_rollback_and_restore_refuse_what_they_must() { + let script = legacy_parity::toy_macros_script(4); + let root = tempfile::tempdir().expect("tmp"); + let rig = rig_with(root.path(), toy_agent("fly-a", &script)).await; + let mut driver = rig.driver(&id("fly-a"), &script); + let hello = HelloParams { + session_id: id("legacy"), + expected_worker_id: id("fly-a"), + role: Role::Agent, + supported_majors: vec![1], + }; + let hello: HelloResult = driver + .call_raw("Worker.Hello", None, hello.to_json(), &[]) + .await + .expect("hello") + .parse() + .expect("a hello result"); + assert!( + hello.capabilities.iter().any(|c| c == ROLLBACK_CAPABILITY), + "{:?}", + hello.capabilities + ); + driver.initialize(0).await.expect("initialize"); + let scope = driver.current_scope(); + let prepare = |interval: RationalNs, kind: &str| PrepareParams { + agent_id: id("fly-a"), + profile_digest: driver.profile().digest.clone(), + interval, + decision_context_digest: driver.context().digest(), + pre_step_stimulations: vec![Stimulus { + id: id("s1"), + kind_id: kind.to_owned(), + duration_ms: 50.0, + }], + }; + let sixty = hz(60).expect("60 Hz"); + let frame_interval = fly_session_types::gameboy::step_duration(); + let bad_cadence = prepare(sixty, "reward-pulse").to_json(); + let bad_kind = prepare(frame_interval, "arena.milestone").to_json(); + let good = prepare(frame_interval, "reward-pulse").to_json(); + assert_eq!( + code( + driver + .call_raw("Agent.Prepare", Some(scope.clone()), bad_cadence, &[]) + .await + ), + ErrorCode::InvalidArgument + ); + assert_eq!( + code( + driver + .call_raw("Agent.Prepare", Some(scope.clone()), bad_kind, &[]) + .await + ), + ErrorCode::Unsupported + ); + let first = driver + .call_raw("Agent.Prepare", Some(scope.clone()), good.clone(), &[]) + .await + .expect("prepare"); + let prepared: PreparedDecision = first.parse().expect("a decision"); + let again = driver + .retry_raw( + first.request_id.clone(), + "Agent.Prepare", + Some(scope.clone()), + good, + ) + .await + .expect("a replay"); + let replayed: PreparedDecision = again.parse().expect("the same decision"); + assert_eq!( + prepared, replayed, + "a duplicate Prepare returns the same decision" + ); + + // Rollback while Prepared. + let (input, frame) = driver.input(2, 0).await.expect("a frame"); + let rollback = |prior: &str| AgentRollbackParams { + agent_id: id("fly-a"), + prior_epoch: id(prior), + policy: ROLLBACK_POLICY.to_owned(), + input: input.clone(), + decision_context: driver.context().clone(), + }; + let next_epoch = scope_at("legacy", "e2", 0); + assert_eq!( + code( + driver + .call_raw( + "Agent.Rollback", + Some(next_epoch.clone()), + rollback("e1").to_json(), + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::InvalidPhase, + "a prepared agent is mid-transition" + ); + rig.stop().await; + + let root = tempfile::tempdir().expect("tmp"); + let mut rig = rig_with(root.path(), toy_agent("fly-a", &script)).await; + let mut driver = rig.driver(&id("fly-a"), &script); + driver.initialize(0).await.expect("initialize"); + let (input, frame) = driver.input(2, 0).await.expect("a frame"); + let context = driver.context().clone(); + let params = |prior: &str| { + AgentRollbackParams { + agent_id: id("fly-a"), + prior_epoch: id(prior), + policy: ROLLBACK_POLICY.to_owned(), + input: input.clone(), + decision_context: context.clone(), + } + .to_json() + }; + assert_eq!( + code( + driver + .call_raw( + "Agent.Rollback", + Some(scope_at("legacy", "e3", 0)), + params("e2"), + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::StaleEpoch, + "the prior epoch is not the one this worker is in" + ); + assert_eq!( + code( + driver + .call_raw( + "Agent.Rollback", + Some(scope_at("legacy", "e1", 0)), + params("e0"), + &[("view.lcd", &frame)] + ) + .await + ), + ErrorCode::StaleEpoch, + "a rollback moves to a new epoch" + ); + let first = driver + .call_raw( + "Agent.Rollback", + Some(scope_at("legacy", "e2", 0)), + params("e1"), + &[("view.lcd", &frame)], + ) + .await + .expect("a rollback"); + first.result().expect("applied"); + let replay = driver + .retry_raw( + first.request_id.clone(), + "Agent.Rollback", + Some(scope_at("legacy", "e2", 0)), + params("e1"), + ) + .await + .expect("a replay of the same rollback"); + assert_eq!( + replay.result().expect("replayed"), + first.result().expect("applied"), + "a lost reply replays, it does not roll back twice" + ); + + // A capture restored with someone else's compatibility is refused before staging. + driver.bump_epoch(); + let captured = driver.capture().await.expect("capture"); + let target = rig.replace(&id("fly-a")).await.expect("a replacement"); + let mut forged = captured.result.clone(); + forged.compatibility_digest = digest_of_bytes(b"another fly"); + let forged = legacy_parity::Captured { + result: forged, + artifact: captured.artifact.clone(), + bytes: captured.bytes.clone(), + scope: captured.scope.clone(), + }; + let refused = driver + .restore_into(target, &forged) + .await + .expect_err("another fly's compatibility"); + assert!(refused.contains("IncompatibleState"), "{refused}"); + rig.stop().await; + } +} + +/// The real dataset, an explicit job: `FLY_AGENT01_FAFB=1` with `data/fafb-v783` checked out. +/// Release mode is the sensible way to run it. +mod fafb { + use super::*; + use fly_session::legacy_parity::{RewardEvent, ScriptStep, fafb_dir, frame_pool}; + use fly_session_types::gameboy::{Location, ReadoutContext}; + + fn enabled() -> Option { + if std::env::var_os("FLY_AGENT01_FAFB").is_none() { + eprintln!("skipping: FLY_AGENT01_FAFB is not set"); + return None; + } + let dir = fafb_dir(); + if dir.is_none() { + eprintln!("skipping: data/fafb-v783 is not present in this checkout"); + } + dir + } + + fn pokered_channels() -> Vec { + let file = + fly_session_types::fixtures::load("gameboy-decoder-config.json").expect("vectors"); + file["cases"][1]["macroChannels"] + .as_array() + .expect("the Pokemon Red macro group") + .iter() + .map(|c| c.as_str().expect("a channel").to_owned()) + .collect() + } + + /// The live macros-mode composition's shape on the real connectome, with recorded inputs. + fn script(frames: usize) -> LegacyScript { + let channels = pokered_channels(); + let bound = |k: usize| -> Vec { + let take: &[usize] = match k { + 0..20 => &[], + 20..50 => &[0, 1, 9], + _ => &[1, 4, 5, 6], + }; + take.iter().map(|i| channels[*i].clone()).collect() + }; + let mut steps = Vec::new(); + for k in 1..=frames { + steps.push(ScriptStep::Frame { + sugar: if k == 12 { vec![400.0] } else { vec![] }, + frame: k % 6, + rewards: if k % 11 == 0 { + vec![RewardEvent { + value: 0.5, + stimulation_ms: 120.0, + }] + } else { + vec![] + }, + next_context: ReadoutContext { + boot: k < 10, + bound: bound(k), + location: (k > 5).then_some(Location { + area: 12, + x: 3 + (k / 40) as u32, + y: 7, + }), + }, + }); + if k == 60 { + steps.push(ScriptStep::Rollback { + frame: 2, + context: ReadoutContext { + boot: false, + bound: bound(k), + location: None, + }, + }); + } + if k == 75 { + steps.push(ScriptStep::Restore); + } + } + let last = steps.len() - 1; + LegacyScript { + name: "fafb-macros".to_owned(), + macro_channels: channels, + frames: Arc::new(frame_pool(6, 783)), + initial_frame: 0, + initial_context: ReadoutContext { + boot: true, + bound: vec![], + location: None, + }, + steps, + checkpoints: [30, last].into_iter().collect(), + } + } + + /// The tracked rate roles on the committed dataset are the fixture's list, and each is + /// published as itself (`legacy-rate-role-id-v1`). + #[test] + fn the_fafb_rate_roles_are_the_fixture_list() { + let Some(dir) = enabled() else { return }; + let dataset = Arc::new(load_brain_dataset_from_dir(&dir).expect("the dataset loads")); + let config = flybrain_core::agent::AgentConfig::with_decoder( + flybrain_core::decoder::gameboy::gameboy_decoder_config(), + ); + let agent = flybrain_core::agent::NeuralAgent::new(dataset, config).expect("the agent"); + let tracked: Vec = agent.network.rates.keys().cloned().collect(); + let file = fly_session_types::fixtures::load("gameboy-rate-roles.json").expect("fixture"); + let want: Vec = file["fafbTrackedRoles"] + .as_array() + .expect("list") + .iter() + .map(|v| v.as_str().expect("a name").to_owned()) + .collect(); + assert_eq!(tracked, want); + } + + /// Recorded inputs through the worker (in-process and as a process) against `NeuralAgent` + /// driven directly, on `gameboy-legacy-fafb-v783-v1` itself. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn the_fafb_scenario_matches_the_direct_reference() { + let Some(dir) = enabled() else { return }; + let script = script(90); + let started = std::time::Instant::now(); + let dataset = Arc::new(load_brain_dataset_from_dir(&dir).expect("the dataset loads")); + let want = DirectSource { dataset } + .records(&script) + .expect("the reference runs"); + eprintln!( + "reference: {} records in {:?}", + want.len(), + started.elapsed() + ); + let summary = legacy_parity::golden_json(&script, &want); + eprintln!("reference digest {}", summary["digest"]); + for mode in [ExecutionMode::InProcess, ExecutionMode::Process] { + let started = std::time::Instant::now(); + let root = tempfile::tempdir().expect("tmp"); + let agent = RigAgent { + agent_id: id("fly-a"), + port_id: id("p1"), + dataset_dir: dir.clone(), + profile: LegacyProfileKind::Production, + macro_channels: script.macro_channels.clone(), + worker_threads: 1, + }; + let mut rig = LegacyRig::start(root.path(), mode, &[agent]) + .await + .expect("the rig"); + let got = legacy_parity::run_on_worker(&mut rig, &id("fly-a"), &script) + .await + .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + rig.stop().await; + legacy_parity::compare(&want, &got).unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + eprintln!( + "{}: {} records identical in {:?}", + mode.label(), + got.len(), + started.elapsed() + ); + } + for row in summary["rows"].as_array().expect("rows").iter().step_by(10) { + eprintln!(" {}", row.as_str().expect("a row")); + } + } +} + +/// FND-01's `FLY_TRACE` reader and check, without a ROM: a trace written in flysim's line shape +/// from the reference's own records is accepted, and each kind of disagreement is refused. The +/// real traces are `flysim/tests/agent_trace_parity.rs`. +mod frame_trace { + use super::*; + use fly_session::legacy_parity::{ + ScriptStep, check_against_trace, read_frame_trace, toy_raw_script, trace_rates_digest, + }; + use fly_session::types::{DomainType, digest_of_bytes}; + use flybrain_core::decoder::gameboy::GAMEBOY_BUTTONS; + use serde_json::json; + + /// `flysim::trace` lines for a script and its records. + fn trace_of(script: &LegacyScript, records: &[ParityRecord]) -> Vec { + let mut lines: Vec = Vec::new(); + for (index, step) in script.steps.iter().enumerate() { + let record = &records[index + 1]; + match step { + ScriptStep::Frame { + sugar, + frame, + rewards, + .. + } => { + let decision = record.decision.as_ref().expect("a decision"); + let mut active: Vec<&str> = GAMEBOY_BUTTONS + .iter() + .enumerate() + .filter(|(bit, _)| decision.buttons[*bit]) + .map(|(_, name)| *name) + .collect(); + if let Some(channel) = &decision.macro_channel { + active.push(channel); + } + lines.push(json!({ + "behaviour": { + "step": (lines.len() as u64).to_string(), + "admissions": sugar.iter().map(|d| json!({"kind": "sugar", "durationMs": d})).collect::>(), + "ticksAdvanced": record.ticks.to_string(), + "brainTicks": record.brain_ticks.to_string(), + "remainder": record.remainder.to_json(), + "ratesDigest": trace_rates_digest(record.telemetry.as_ref().expect("telemetry")).expect("rates"), + "spikesDigest": record.spikes.clone().expect("spikes"), + "spikeCount": 0, + "decision": active, + "mask": decision.mask(), + "macroEvents": [], + "framebufferDigest": digest_of_bytes(&script.frames[*frame]), + "wramDigest": "", + "rewards": rewards.iter().map(|r| json!({"kind": "toy", "value": r.value, "stimulationMs": r.stimulation_ms})).collect::>(), + "rank": 0, + "acknowledgedBoundary": (lines.len() as u64 + 1).to_string(), + "boundaryActions": [], + }, + "operational": {"captures": []}, + })); + } + ScriptStep::Rollback { .. } => { + let last = lines.last_mut().expect("a frame before the rollback"); + last["behaviour"]["boundaryActions"] + .as_array_mut() + .expect("a list") + .push(json!({"kind": "rollback", "slotId": "best", "stateDigest": null})); + } + ScriptStep::Restore => unreachable!("the raw script has no restore"), + } + } + lines + } + + fn text(lines: &[Value]) -> String { + let mut out = json!({"format": "flysim-legacy-frame-trace-v1"}).to_string(); + out.push('\n'); + out.push_str(&json!({"boundary": "0", "operational": {"captures": [{"checkpointId": "g1", "afterActions": 0}]}}).to_string()); + for line in lines { + out.push('\n'); + out.push_str(&line.to_string()); + } + out + } + + #[test] + fn a_trace_of_the_reference_checks_and_every_disagreement_is_refused() { + let script = toy_raw_script(80); + let records = reference(&script); + let lines = trace_of(&script, &records); + let trace = read_frame_trace(&text(&lines)).expect("the trace reads"); + assert_eq!(trace.len(), 80); + let check = check_against_trace(&script, &records, &trace).expect("the reference checks"); + assert_eq!( + (check.transitions, check.sugar, check.rollbacks), + (80, 1, 1) + ); + + let refused = |edit: &dyn Fn(&mut Vec)| { + let mut lines = lines.clone(); + edit(&mut lines); + let trace = read_frame_trace(&text(&lines)).expect("the trace reads"); + check_against_trace(&script, &records, &trace).expect_err("a disagreement") + }; + let e = refused(&|l| l[30]["behaviour"]["spikesDigest"] = json!("00")); + assert!(e.contains("spikesDigest"), "{e}"); + let e = refused(&|l| l[30]["behaviour"]["brainTicks"] = json!("1")); + assert!(e.contains("brainTicks"), "{e}"); + let e = refused(&|l| { + l[30]["behaviour"]["remainder"] = json!({"numerator": "0", "denominator": "1"}) + }); + assert!(e.contains("remainder"), "{e}"); + let e = refused(&|l| l[30]["behaviour"]["ratesDigest"] = json!("00")); + assert!(e.contains("ratesDigest"), "{e}"); + let e = refused(&|l| l[30]["behaviour"]["decision"] = json!(["select"])); + assert!(e.contains("decision"), "{e}"); + let e = refused(&|l| l[9]["behaviour"]["admissions"] = json!([])); + assert!(e.contains("admitted"), "{e}"); + let e = refused(&|l| { + l[9]["behaviour"]["admissions"] = json!([{"kind": "reward", "value": 1.0}]) + }); + assert!(e.contains("RewardPulse"), "{e}"); + let e = refused(&|l| l[5]["behaviour"]["framebufferDigest"] = json!("00")); + assert!(e.contains("frame"), "{e}"); + let e = refused(&|l| { + for line in l.iter_mut() { + line["behaviour"]["boundaryActions"] = json!([]); + } + }); + assert!(e.contains("rollback"), "{e}"); + let e = refused(&|l| { + l.pop(); + }); + assert!(e.contains("ended"), "{e}"); + } +} diff --git a/services/flysim/crates/flysim/Cargo.toml b/services/flysim/crates/flysim/Cargo.toml index b3184ba..3884630 100644 --- a/services/flysim/crates/flysim/Cargo.toml +++ b/services/flysim/crates/flysim/Cargo.toml @@ -55,6 +55,9 @@ unicode-normalization = "0.1" # The legacy profile's pinned identities (`tests/legacy_profile_identity.rs`): test-only, so the # service itself does not link the session types. fly-session-types = { path = "../fly-session-types" } +# AGENT-01's worker checked against this loop's FLY_TRACE (`tests/agent_trace_parity.rs`): +# test-only as well. fly-session does not depend on flysim, so this is no cycle. +fly-session = { path = "../fly-session" } futures-util = "0.3" # `default-features = false` drops the remote-reference resolver (and with it reqwest and a # TLS stack): `packages/feed/src/schema.json` is self-contained, so nothing has to be fetched. diff --git a/services/flysim/crates/flysim/tests/agent_trace_parity.rs b/services/flysim/crates/flysim/tests/agent_trace_parity.rs new file mode 100644 index 0000000..3f81d47 --- /dev/null +++ b/services/flysim/crates/flysim/tests/agent_trace_parity.rs @@ -0,0 +1,422 @@ +//! AGENT-01 against FND-01: the legacy agent worker, and the direct reference, checked against the +//! `FLY_TRACE` of the legacy frame the stream runs (`flysim::frame::LegacyFrame`). +//! +//! The trace records what the loop did to the brain as digests -- ticks, clock, exact remainder, +//! rates, the spike set, the decision -- but not everything a worker needs to be driven: the +//! frames (only their digests), and the `{boot, bound, location}` context the executor and the +//! adapter produced. So this test is the host: it runs `LegacyFrame` on the real emulator with the +//! trace on, records those inputs beside it as a `LegacyScript`, then drives the same script +//! through `LegacyAgentWorker` in every execution mode and through `DirectReference`, and holds +//! each record to its trace line (`fly_session::legacy_parity::check_against_trace`). The script +//! is checked against the trace as well: the same admissions, frames, reward events and rollback. +//! +//! Two runs, both explicit ROM jobs (`. bin/rom-env.sh`, never a download): +//! +//! - `toy_raw_from_power_on`: `FLY_ROM` only. The committed toy connectome in raw mode from +//! power-on, with two sugar admissions. Cheap enough for every ROM run of the workspace. +//! - `fafb_macros_from_a_checkpoint`: also `FLY_AGENT01_FAFB=1` and `data/fafb-v783`. The live +//! composition -- `gameboy-legacy-fafb-v783-v1`, macros mode -- restored from a stream +//! checkpoint (`FLY_AGENT01_TRACE_CHECKPOINT`, else `FLY_DOOR_CHECKPOINT`), with sugar and one +//! ratchet rollback onto the checkpoint's slot. The worker starts from the checkpoint's agent +//! state (`AgentDriver::seed_from_legacy_state`). +//! +//! `FLY_AGENT01_TRACE_FRAMES` sets the length (default 600 toy, 240 FAFB). The worker program for +//! process mode is the workspace's `fly-session` binary; a build that did not produce it skips +//! that mode and says so. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use fly_session::ExecutionMode; +use fly_session::fly_session_types::gameboy::{Location, ReadoutContext}; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity::{ + self, DirectSource, LegacyRig, LegacyScript, ParityRecord, ReferenceSource, RestoredSource, + RewardEvent, RigAgent, ScriptStep, TraceCheck, TraceTransition, toy, +}; +use fly_session::types::{digest_of_bytes, id}; +use flybrain_core::agent::{AgentConfig, AgentState, NeuralAgent}; +use flybrain_core::dataset::{BrainDataset, load_brain_dataset_from_dir}; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flybrain_gb::adapter::GameAdapter; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flybrain_gb::ratchet::Ratchet; +use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator}; +use flysim::config::Config; +use flysim::frame::{LegacyFrame, Parts}; +use flysim::macros::{MacroLayer, macro_layer}; +use flysim::snapshot::MacroMode; +use flysim::trace::FrameTrace; + +fn rom() -> Option> { + let Some(path) = std::env::var_os("FLY_ROM") else { + eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)"); + return None; + }; + Some(std::fs::read(&path).unwrap_or_else(|e| panic!("FLY_ROM {path:?}: {e}"))) +} + +fn frames(default: usize) -> usize { + std::env::var("FLY_AGENT01_TRACE_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +fn context(adapter: &dyn GameAdapter, macros: Option<&MacroLayer>) -> ReadoutContext { + ReadoutContext { + boot: adapter.boot(), + bound: macros.map(MacroLayer::bound_channels).unwrap_or_default(), + location: adapter + .location() + .map(|(area, x, y)| Location { area, x, y }), + } +} + +/// Frames by content, so a still screen is stored once. +#[derive(Default)] +struct Pool { + frames: Vec>, + index: HashMap, +} + +impl Pool { + fn add(&mut self, frame: &[u8]) -> usize { + let digest = digest_of_bytes(frame); + *self.index.entry(digest).or_insert_with(|| { + self.frames.push(frame.to_vec()); + self.frames.len() - 1 + }) + } +} + +/// How the legacy run starts. +enum Start<'a> { + /// `LegacyFrame::initialize`: one frame with no button, then the warm-up on it. + PowerOn, + /// `LegacyFrame::restore` from a stream checkpoint, as `Sim::try_restore` does. + Checkpoint(&'a flysim::store::Checkpoint), +} + +struct LegacyRun { + script: LegacyScript, + trace: Vec, + /// The agent state the run started from, for a restored start. + start: Option, + rewards: Vec<&'static str>, +} + +/// The stream's frame on the real emulator with `FLY_TRACE` on, recording the script beside it. +/// +/// Sugar is admitted the way `Sim::stimulate` admits it (stimulate, then the trace), at the top of +/// the frame. `rollback_at` forces the ratchet's rollback at that boundary when the ratchet holds a +/// slot and did not roll back itself: `LegacyFrame::rollback` is exactly what `boundary` runs when +/// the ratchet fires, and whether it fires is the task's decision, not the agent's. +#[allow(clippy::too_many_arguments)] +fn run_legacy( + rom: &[u8], + data: &Arc, + start: Start<'_>, + mode: MacroMode, + frames: usize, + sugar: &[(usize, f64)], + rollback_at: Option, + trace_path: &Path, +) -> LegacyRun { + let mut emulator = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .expect("binjgb should accept the cartridge"); + let mut adapter = PokemonRedReward::new(); + let mut ratchet = Ratchet::with_policy(adapter.recovery_policy()); + let mut config = Config::default(); + config.loop_.game = "pokemon-red".to_string(); + config.macros.mode = mode; + let channels = if mode.dealt() { + flybrain_gb::macro_channels("pokemon-red") + } else { + Vec::new() + }; + let preset = gameboy_decoder_config_with_macros(&channels); + let hold_ms = preset + .macros + .as_ref() + .or(preset.exclusive.as_ref()) + .expect("the preset has a group") + .hold_ms; + let mut agent_config = AgentConfig::with_decoder(preset); + agent_config.warmup_ms = config.loop_.warmup_ms; + assert_eq!( + config.loop_.warmup_ms, + fly_session::fly_session_types::gameboy::WARMUP_MS, + "the stream's warm-up is the profile's" + ); + let mut agent = NeuralAgent::new(Arc::clone(data), agent_config).expect("a valid agent"); + let mut frame = + LegacyFrame::new().with_trace(Some(FrameTrace::create(trace_path).expect("a trace file"))); + let start_state = match start { + Start::PowerOn => { + frame + .initialize(&mut emulator, &mut agent) + .expect("the first frame and the warm-up"); + None + } + Start::Checkpoint(checkpoint) => { + frame + .restore( + &mut Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: None, + }, + checkpoint, + ) + .expect("the checkpoint should restore"); + Some(checkpoint.agent.clone()) + } + }; + // `Sim::boot`: the macro layer is built after the restore or warm-up, seeded from the network + // as it then stands, and observes once before the first frame. + let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32); + if let Some(layer) = macros.as_mut() { + let ledger = AdapterLedger(&adapter); + let _ = layer.observe(&mut emulator, &ledger, agent.network.ms); + } + + let mut pool = Pool::default(); + let initial_frame = pool.add(&frame.frame_buffer); + let initial_context = context(&adapter, macros.as_ref()); + let mut steps = Vec::new(); + let mut kinds = Vec::new(); + for k in 1..=frames { + let mut admitted = Vec::new(); + for (_, duration) in sugar.iter().filter(|(at, _)| *at == k) { + agent.network.stimulate(*duration); + if let Some(trace) = frame.trace_mut() { + trace.sugar(*duration); + } + admitted.push(*duration); + } + let mut parts = Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: macros.as_mut(), + }; + let transition = frame.transition(&mut parts, &mut ()).expect("a frame"); + let produced = pool.add(&frame.frame_buffer); + let rewards: Vec = transition + .evaluated + .rewards + .iter() + .map(|event| { + kinds.push(event.kind); + RewardEvent { + value: event.value, + stimulation_ms: f64::from(event.stimulation_ms), + } + }) + .collect(); + // The next context is read after the evaluation and before the ratchet: what the task + // hands `Agent.Commit`. + let next_context = context(&*parts.adapter, parts.macros.as_deref()); + let boundary = frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .expect("the boundary"); + steps.push(ScriptStep::Frame { + sugar: admitted, + frame: produced, + rewards, + next_context, + }); + let mut rolled_back = boundary.rollback.is_some(); + if !rolled_back && rollback_at == Some(k) && parts.ratchet.game().is_some() { + frame.rollback(&mut parts).expect("the forced rollback"); + rolled_back = true; + } + if rolled_back { + let restored = pool.add(&frame.frame_buffer); + steps.push(ScriptStep::Rollback { + frame: restored, + context: context(&*parts.adapter, parts.macros.as_deref()), + }); + } + } + frame.finish_trace(); + drop(frame); + let text = std::fs::read_to_string(trace_path).expect("the trace reads back"); + let trace = legacy_parity::read_frame_trace(&text).expect("a flysim-legacy-frame-trace-v1"); + LegacyRun { + script: LegacyScript { + name: format!("flysim-{}", mode.as_str()), + macro_channels: channels.iter().map(|c| (*c).to_owned()).collect(), + frames: Arc::new(pool.frames), + initial_frame, + initial_context, + steps, + checkpoints: Default::default(), + }, + trace, + start: start_state, + rewards: kinds, + } +} + +fn worker_modes() -> Vec { + let mut modes = vec![ExecutionMode::InProcess, ExecutionMode::Thread]; + let program = fly_session::launcher::default_worker_program(); + if program.is_file() { + modes.push(ExecutionMode::Process); + } else { + eprintln!( + "process mode skipped: no worker program at {} (build the fly-session binary, or set {})", + program.display(), + fly_session::launcher::WORKER_PROGRAM_ENV + ); + } + modes +} + +async fn on_worker( + mode: ExecutionMode, + run: &LegacyRun, + dataset_dir: PathBuf, + profile: LegacyProfileKind, +) -> Vec { + let root = tempfile::tempdir().expect("tmp"); + let agent = RigAgent { + agent_id: id("fly"), + port_id: id("p1"), + dataset_dir, + profile, + macro_channels: run.script.macro_channels.clone(), + worker_threads: 1, + }; + let mut rig = LegacyRig::start(root.path(), mode, &[agent]) + .await + .expect("the rig"); + let records = + legacy_parity::run_on_worker_from(&mut rig, &id("fly"), &run.script, run.start.as_ref()) + .await + .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + rig.stop().await; + records +} + +fn report(what: &str, check: &TraceCheck) { + eprintln!( + "{what}: {} transitions identical to FLY_TRACE ({} sugar, {} reward events, {} rollbacks, \ + {} macro decisions, {} pressed, {} spikes)", + check.transitions, + check.sugar, + check.rewards, + check.rollbacks, + check.macro_decisions, + check.pressed, + check.spikes + ); +} + +async fn check_all( + run: &LegacyRun, + reference: Vec, + dataset_dir: PathBuf, + profile: LegacyProfileKind, +) { + let check = legacy_parity::check_against_trace(&run.script, &reference, &run.trace) + .unwrap_or_else(|e| panic!("the direct reference against FLY_TRACE: {e}")); + report("direct reference", &check); + for mode in worker_modes() { + let started = std::time::Instant::now(); + let got = on_worker(mode, run, dataset_dir.clone(), profile).await; + let worker = legacy_parity::check_against_trace(&run.script, &got, &run.trace) + .unwrap_or_else(|e| panic!("{} against FLY_TRACE: {e}", mode.label())); + assert_eq!(worker, check); + // And record for record, telemetry included, the worker is the reference. + legacy_parity::compare(&reference, &got) + .unwrap_or_else(|e| panic!("{} against the direct reference: {e}", mode.label())); + report( + &format!("worker {} ({:?})", mode.label(), started.elapsed()), + &worker, + ); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn toy_raw_from_power_on() { + let Some(rom) = rom() else { return }; + let data = Arc::new(load_brain_dataset_from_dir(toy::dir()).expect("the toy dataset")); + let dir = tempfile::tempdir().expect("tmp"); + let n = frames(600); + let run = run_legacy( + &rom, + &data, + Start::PowerOn, + MacroMode::Raw, + n, + &[(40, 300.0), (n / 2, 500.0)], + None, + &dir.path().join("trace.jsonl"), + ); + assert_eq!(run.trace.len(), n); + let reference = DirectSource { dataset: data } + .records(&run.script) + .expect("the direct reference runs"); + check_all(&run, reference, toy::dir(), LegacyProfileKind::Toy).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fafb_macros_from_a_checkpoint() { + let Some(rom) = rom() else { return }; + if std::env::var_os("FLY_AGENT01_FAFB").is_none() { + eprintln!("skipping: FLY_AGENT01_FAFB is not set"); + return; + } + let Some(dataset_dir) = legacy_parity::fafb_dir() else { + eprintln!("skipping: data/fafb-v783 is not present in this checkout"); + return; + }; + let Some(path) = std::env::var_os("FLY_AGENT01_TRACE_CHECKPOINT") + .or_else(|| std::env::var_os("FLY_DOOR_CHECKPOINT")) + else { + eprintln!("skipping: neither FLY_AGENT01_TRACE_CHECKPOINT nor FLY_DOOR_CHECKPOINT is set"); + return; + }; + let checkpoint = flysim::store::load(Path::new(&path)).expect("a FLYSIM01 checkpoint"); + let data = Arc::new(load_brain_dataset_from_dir(&dataset_dir).expect("the dataset")); + let dir = tempfile::tempdir().expect("tmp"); + let n = frames(240); + let started = std::time::Instant::now(); + let run = run_legacy( + &rom, + &data, + Start::Checkpoint(&checkpoint), + MacroMode::Macros, + n, + &[(10, 400.0), (n / 2, 250.0)], + Some(n / 3), + &dir.path().join("trace.jsonl"), + ); + eprintln!( + "legacy loop: {n} frames from {} in {:?}; reward events {:?}", + Path::new(&path).display(), + started.elapsed(), + run.rewards + ); + assert!( + run.script + .steps + .iter() + .any(|s| matches!(s, ScriptStep::Rollback { .. })), + "the checkpoint holds no ratchet slot to roll back onto" + ); + let reference = RestoredSource { + dataset: data, + state: run.start.clone().expect("a restored start"), + } + .records(&run.script) + .expect("the direct reference runs"); + check_all(&run, reference, dataset_dir, LegacyProfileKind::Production).await; +}