diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index ffbd75a..f45c012 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -344,6 +344,103 @@ CUT-01 shadow need. the executor over `ImageReader::new(&O[k], &cartridge)` in Phase B and over O[k+1] in Phase C, retaining O[k] until then. The `Cartridge` comes from `Cartridge::verified(rom, contentDigest)`. +### TASK-01 — The `pokered-macros-v1` task and executor (port slice) + +**2026-09-29: built** on `port/task-01` off `port/integration` (main v0.6.5 + AGENT-01 + MEM-01 + +ENV-01) and awaiting review. It changes no live behaviour: `flysim` is only a library dependency of +the new crate, nothing in the service calls it, and the compatibility string is unchanged. With it +the live fly's whole composition -- agent, world, task and executor -- runs on the session +framework, from a fresh start or from a FLYSIM01 checkpoint. + +- **The object** (`fly-legacy-session::task::PokeredTask`). The task and the executor are one + object with two faces, `Task` and `ActionExecutor`, which the coordinator holds where it holds + any task and executor (legacy-gameboy-v1 section 10). Phase B runs flysim's `MacroLayer::decide` + over `ImageReader(O[k], cartridge)` at the agent's brain time. Phase C runs + `PokemonRedReward::sample`, `MacroLayer::observe`, the location, the progress and the ratchet's + decision over `ImageReader(O[k+1])`. A rollback runs `clear_transient`, `cancel` and `observe` + over `ImageReader(O'[k+1])`. These are the legacy engine's own calls in `LegacyFrame`'s order; + there is no port of a rule. The cartridge is `Cartridge::verified(rom, contentDigest)`, and O[k] is + retained until Phase C has read it. +- **The coordinator** (fly-session). A task declares the inspection attachments it reads, and the + coordinator holds them and hands over their bytes (`task::Inspection`). The executor's clock is the + agent's brain time after Prepare. `Evaluation.slot_saves` asks for `Environment.SaveSlot`. A + declared rollback policy now runs itself: `Ready(e, k) -> RollingBack(e', k) -> Ready(e', k)`, with + `RestoreSlot`, then `Task::rollback`, then `Agent.Rollback` on every agent. Composition setters + cover the backend and task config, the media, the decision schema, the world's state format and + per-agent model versions. The admission queue (`AdmissionQueue`) is cut into each Prepare's + `preStepStimulations` and reports every admission applied or aborted. `Coordinator::import` + installs a checkpoint of another format as a session's start. Step details (`StepDetails`) are + kept for a parity run. +- **FLYSIM01 as the start** (`fly-legacy-session::import`, on STATE-02's + `legacy_checkpoint::{halves, agent_payload, world_payload}`). The world, agent and task halves + go into each participant's own capture format, and the ordinary group restore installs them: + stage, validate, activate, `Paused(k)`, resume. The world is replaced by a fresh one first, + because ENV-01 stages only on a replacement. The context the agent resumes with is computed + from the checkpoint's own memory image, and the coordinator holds the task to it after the + install (`Task::restored`). The task ledger is STATE-02's `{reward, ratchet, slotFilled}`. +- **The store and the boot** (`fly-legacy-session::composition`, on STATE-02's + `LegacyCheckpointer`). + - `boot` is `Sim::boot`. It restores from the live hot and durable stores in the legacy + candidate order, holding each candidate to the legacy gate. Any refusal falls to the next + candidate; each attempt runs on a session of its own, because a refused install fences its + session. It is a fresh start when the stores are empty. After either, the startup durable + save is written and the intervals start. + - `advance` keeps the declared boundary order: the slot save (inside the step), the milestone + archive on a rank climb, the rollback (deferred by the coordinator until the host has + captured), a durable save after a rollback, then the interval saves. + - `shutdown_save` is the legacy shutdown's durable save. + - The session runtime writes no sugar journal yet: its admission is the coordinator's, and the + journal's boot header needs the edge. + - `lastEventId` carries the restored file's watermark; the runtime has no feed event log + before EDGE-01. +- **Sugar** (`fly-legacy-session::admission`). flysim's `RateLimiter` and clamp run unchanged, + against the last commit's `stimulusRemainingMs` (one commit stale). An admission waits for the + next cut. +- **The operator reward pulse is refused.** See the legacy-gameboy-v1 section 15 amendment. + +**Parity** (`fly-legacy-session/tests/session_trace.rs`, rom-env). A whole new-runtime session +writes its own `FLY_TRACE` line per transition (`fly-legacy-session::trace`). Each line is built +from what crossed its boundaries: `Agent.Prepare`, `Agent.Commit`'s rates and spike bitset, the +executor's batch, the view, the image and the boundary actions. It is compared field by field with +the legacy loop's. The decision is compared as a set, because `gameboy-channels-v1` carries no list +order. Where the legacy side runs in the test, the ledgers are compared after every boundary as +well: adapter export, ratchet state, and the executor's scene, bound channels, running macro, +counts and "nearer". Results: see the TASK-01 run report and the amendment below. + +**Amendment, 2026-09-29 (TASK-01 review fix round).** The review blocked on B1 and noted +N1 to N5. All are fixed here; the dated amendments to legacy-gameboy-v1 section 10 and 15 cover +B1, N1 and N3. + +- **B1: the task ledger is artifact-backed.** On the live fly the adapter ledger is 42-46 KB, + past the 32 KiB `TypedValue` bound. + - `Task` gains `capture_attachments`, `validate_restore_with` and `install_restore_with`. + - The coordinator files those attachments as `task-ledger-` payloads in captures and + imports. + - A bad ledger is an error, never a panic, so a boot falls to the next candidate. + - Boot parity now covers row 64 (42 KB) and the row 65 yard (46 KB). +- **N1: a sugar admitted before the next commit is an active pulse.** +- **N3: a restore seeds the palette as `Sim::boot` does.** `tests/palette_seed.rs` shows that the + seed is never read. +- **N4: saves are queued to the writer thread.** +- **N5: speed.** The profile is below. Changes: + - The world seals its three artifacts concurrently. + - Cache and caller holds are taken concurrently. + - In-process participants use the in-memory transport. + - A service session publishes every other boundary (the feed's 30 Hz) and keeps a bounded + history. + - `State.Capture` is off the loop. The worker shell lets a handler finish its reply outside + the endpoint's lock, and takes mutations in arrival order. The legacy agent copies its state + under the lock, then encodes, digests and seals it off the lock. The coordinator's + `begin_capture` / `finish_capture` let the session step on while the payload is written. +- **Measured** (`tests/speed.rs`, `tests/speed_ab.rs`): + - The brain is the same: the legacy `ticks` phase and the agent's `ticks` span agree within a + few percent. + - What remains is a fixed per-frame overhead of the process boundary. It is about 3-5 ms on a + quiet 8-core build box: roughly 0.7-1 ms per RPC round trip for Prepare, Advance and Commit, + plus the world's and the agent's artifact seals and reads. + - Against it, the legacy loop spends about 0.7 ms per frame outside the ticks. + - The report `claude-task-01` has the per-phase table and what would close the rest. + ### STATE-01 — Coherent all-participant checkpoint/recovery **Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01. diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index d08f539..281079c 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -288,6 +288,37 @@ signal. The object serves exactly one agent on one port. - **Cancel.** `cancel(ms)` abandons a running macro. It is followed by `observe` on the world the fly now stands in. +**Amendment, 2026-09-29 (TASK-01).** Choices the section above leaves open, fixed as built by +`fly-legacy-session::task`: + +- *The ratchet's slot.* The ratchet ledger stays in the task. Its snapshot lives in the environment + as the slot `best`. The ratchet only asks whether one exists: its budget test is "no snapshot". + So the task holds a marker snapshot in its place, and a task ledger records `slotFilled`. A slot + save is asked for exactly when the legacy capture closure runs: safe, and rank above best. +- *The task ledger is artifact-backed* (amended 2026-09-29, TASK-01 review B1). The adapter's + lifetime ledger grows with play: it is 42-46 KB on the live fly at rungs 12-15, which is past + the 32 KiB `TypedValue` bound. So the typed ledger is `{reward: {digest, byteLength}, ratchet, + slotFilled}`, and the adapter state's JSON travels as the ledger attachment `reward`. A + checkpoint files it as the payload `task-ledger-reward` ([workers-v1](workers-v1.md) section 1's + explicit artifact-backed schema; `Task::capture_attachments`). A missing, altered or unreadable + attachment is `INCOMPATIBLE_STATE`, never a panic, so a boot falls to the next candidate. +- *The palette seed* (amended 2026-09-29, TASK-01 review N3). The legacy loop seeds the palette + from the brain's RNG state after boot. A restore does the same: it seeds with the restored + agent state's RNG, which it holds. A fresh start cannot see the agent's RNG after the warm-up, + so it uses a constant. That is exact because `MacroMachine` never reads its generator: no macro + has a random step. `fly-legacy-session` `tests/palette_seed.rs` holds this on the cartridge: + two seeds, driven by the same decisions, press the same buttons for 3000 frames. A future + macro that draws from the generator fails there. +- *The clock of the first observation.* A fresh start's layer observes O[0] at the end of the + warm-up, `warmupMs` = 2500 ms, which the profile pins. That is the same time the legacy loop's + `Sim::boot` observes at, although the agent is initialized after the task bootstraps. After a + restore the layer observes at the restored brain time. +- *A reward event with `stimulation_ms` = 0* is one `Reward` and no `Stimulus`, because + `Stimulus.durationMs` is positive. The legacy `stimulate(0)` changes nothing. +- *Executor events.* Macro starts and finishes are not `executionEvents`. They are reported as + `FLY_TRACE` `macroEvents` (phases `execute`, `evaluate`, `rollback`). Reward events are the + task's `TaskEvent`s. + ## 11. Episode policy `legacy-ratchet-rollback-v1` The ratchet's game-only rollback is a declared episode policy. When the ratchet fires during @@ -331,6 +362,14 @@ the adapter's persistent state. The first audio chunk after the rollback marks a discontinuity. This is the legacy `recover_game` sequence with the neural half moved into the agent. Each half touches only its own state, so the order between the halves does not matter. +**Amendment, 2026-09-29 (TASK-01).** The coordinator applies the policy itself, as the section +describes. The phase is `RollingBack(k)`. The new epoch is the session's epoch root plus `.rb`, +which is deterministic, so two runs of one session name the same epochs. A composition that +declares the policy refuses to start unless every agent advertises `legacy-ratchet-rollback-v1`. +The task's rollback request carries `{slotId: best, trigger}`. The world must advertise +`gameboy-slots-v1` before anything is saved or restored. Service traces with a ratchet slot save +and a ratchet rollback reproduce as described in the implementation guide's TASK-01 entry. + ## 12. Composition declaration and digest ```ts @@ -500,6 +539,27 @@ Resume tests compare against the legacy restore outcome, not against an uninterr unstick procedure depends on: restarting the service clears the ledger-shaped traps and keeps the rung. +**Amendment, 2026-09-29 (TASK-01): a FLYSIM01 checkpoint as the start.** A new-runtime session +starts from the live fly's own save through the ordinary group restore +(`Coordinator::import`, `fly-legacy-session::import`): + +- The world is ENV-01's `WorldState::from_flysim01` at `k = emulatorFrame - 1`, staged on a + replacement world. +- The agent is the checkpoint's agent state in the worker's own capture format: STATE-02's + `legacy_checkpoint::agent_payload`. It carries the file's reinforcement count and the file's + framebuffer as the next input, and its ids come from the file. +- The task is STATE-02's ledger `{reward, ratchet, slotFilled}`. + +A session boots from the live stores the way `Sim::boot` does: the legacy candidate order, the +legacy gate, the next candidate on any refusal, then a startup durable save. See the +implementation guide's TASK-01 entry. + +This section's resets then apply, and nothing else. The executor is fresh and observes the restored +image once, at the restored brain time. The agent's readout transient is a fresh process's. The +decision context is computed from the checkpoint's memory image before the install, and the +coordinator refuses the install if the task, re-observing the restored world, derives another +context. + ## 15. Sugar admission The coordinator owns admission, with the legacy rules: the per-minute limiter, and "no overlap @@ -523,6 +583,29 @@ applies it never commits, the admission is reported aborted and the edge refunds bridge's fulfil path and refund path both get tests in the slice that wires them ([workers-v1](workers-v1.md) section 5 amendment). +**Amendment, 2026-09-29 (TASK-01).** As built: + +- *Admission.* The coordinator's `AdmissionQueue` is cut at the top of each Prepare. It reports + every admission `applied` at the boundary its Prepare committed at, or `aborted` when the epoch + fails first. The legacy rules run on the edge side, unchanged: flysim's `RateLimiter` and the + clamp. They read `stimulusRemainingMs` from the last `Agent.Commit` or `Agent.Rollback` reply. + After a restore the pulse is unknown and a request is refused with a retry of one frame. + *Amended 2026-09-29 (TASK-01 review N1):* a sugar admitted but not yet reported on by a commit + counts as an active pulse, at its full duration (`AdmissionQueue::pending_stimulus_ms`). The + legacy `stimulate` activates the pulse the moment it admits, so this matches: + - two sugars between two commits get one admission and one `PulseActive`, as the legacy drain + gives them; + - the rate-limit slot is not spent on the refused one. + + The retry advice may differ by less than a frame. Legacy reports the pulse decayed by the + ticks between drains; here it is undecayed until the commit reports it. +- *The operator's `POST /reward` pulse is refused (declared).* In the legacy loop it is off unless + an operator sets `control.allow_reward`. Every shipped configuration leaves it off, and the API + answers 403. The session runtime has no counterpart to turn on, because a reinforcement outside + `Agent.Commit` is not a session-framework operation. `LegacyAdmission::reward` therefore always + refuses. A legacy trace that carries a reward pulse cannot be reproduced; FND-01's checker + refuses one as well. + ## 16. Checkpoint format of record **Order at a boundary (amended 2026-09-23, review round 1).** A slot save due at `Ready(k)` diff --git a/docs/design/session-framework/step-v1.md b/docs/design/session-framework/step-v1.md index bf8d167..ff1de4d 100644 --- a/docs/design/session-framework/step-v1.md +++ b/docs/design/session-framework/step-v1.md @@ -65,6 +65,19 @@ amendment). The boundary number does not change; the epoch does. A pause request lands on `Ready(e', k)`; any failure inside it is `Failed → Restoring(new epoch)`. Capture is not allowed in `RollingBack`. +**Amendment, 2026-09-29 (TASK-01).** Two edges are implemented as written above (`fly-session` +`phase.rs`): `Ready(k) -> RollingBack(k) -> Ready(k)`, where the epoch is the coordinator's and +the boundary stays the same. One edge is added for a checkpoint of another format installed as a +session's start (the legacy composition's FLYSIM01 import): + +```text +Ready(0), no transition taken -> Restoring(k) -> Paused(k) +``` + +The install is the group restore of [state-media-v1](state-media-v1.md) section 6, unchanged. Only +a session that has not advanced may take the edge; the coordinator enforces this, because the phase +alone cannot tell a fresh `Ready(0)` from a reset one. + ## 3. Transaction sequence ### Phase A: prepare all agents concurrently @@ -111,6 +124,12 @@ and returns StepResult for `k+1`. It MUST NOT advance another interval while wai the next request. Transport/control scaffolding may have a measured fixed latency; it must be declared in its descriptor and conformance tests. +*Amendment, 2026-09-29 (TASK-01):* as built, the clock the executor is handed is +`brainTicks x tickDuration` from the agent's `PreparedDecision`, exact in `RationalNs`. For the +legacy profile this is the legacy `network.ms` in nanoseconds. An artifact-backed inspection reaches +the executor and the task as bytes: the coordinator holds each attachment the task declares +(`inspection.memory`) from the world's reply until the transition that reads it has been evaluated. + ### Phase C: observe and evaluate the task The coordinator receives the environment result and verifies batch identity, boundary, diff --git a/docs/design/session-framework/workers-v1.md b/docs/design/session-framework/workers-v1.md index 9769270..d4a9732 100644 --- a/docs/design/session-framework/workers-v1.md +++ b/docs/design/session-framework/workers-v1.md @@ -426,6 +426,22 @@ composition that declares no rollback policy treats the request as a task failur "cannot reset the environment directly": the coordinator applies the policy through the section 7 methods. +**Amendment, 2026-09-29 (TASK-01).** The Rust interfaces, as built in `fly-session::task`: + +- The inspection argument is an `Inspection`: the observation's typed `inspection` value, plus the + bytes of every attachment the task declares (`Task::inspection_attachments`, for example + `inspection.memory`). A synthetic task declares none, and its inspection reads as the typed value + it always was. +- `Evaluation.slot_saves` names the `Environment.SaveSlot`s the transition asks for at the boundary + it reached. They are applied after every Commit, saves first. +- `Task::rollback(scope', restored)` is step 3 of a declared rollback policy. It returns the next + contexts. +- `Task::restored(scope', restored, clock)` runs after a group restore installed the ledger. A task + whose executor state is transient re-observes the restored world here, and returns the contexts + the coordinator holds against the checkpoint's. +- A task and an executor that are one object (`pokered-macros-v1`) are two handles on one shared + state. + ## 5. Admission and audience boundary The first synthetic implementation has no audience input. Later integration maps permitted @@ -453,6 +469,13 @@ first and refunds the second, and the slice wiring the bridge tests both. This i accepted/applied/aborted distinction the paragraph above asks for, for this one interaction kind; paid interactions in general still need the public v2 contract. +**Amendment, 2026-09-29 (TASK-01).** As built, the coordinator's `AdmissionQueue` is the +admission record: an admitted stimulus carries its interaction id into `preStepStimulations`, and it +ends `applied` (with its boundary) or `aborted` (the epoch failed before its Prepare committed). The +legacy composition's rules run on the edge side of the queue. No other interaction kind is admitted. +The legacy operator reward pulse is refused (legacy-gameboy-v1 section 15, amendment of +2026-09-29). + ## 6. Health, shutdown and extensions All workers implement the common Hello/Status/Shutdown/Acknowledge methods. Capture/restore diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index 3c6e925..f0447b9 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -435,6 +435,20 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "fly-legacy-session" +version = "0.1.1" +dependencies = [ + "fly-session", + "flybrain-core", + "flybrain-gb", + "flybus", + "flysim", + "serde_json", + "tempfile", + "tokio", +] + [[package]] name = "fly-session" version = "0.1.1" diff --git a/services/flysim/Cargo.toml b/services/flysim/Cargo.toml index 2673363..d98e038 100644 --- a/services/flysim/Cargo.toml +++ b/services/flysim/Cargo.toml @@ -2,6 +2,7 @@ resolver = "3" members = [ "crates/fly-edge", + "crates/fly-legacy-session", "crates/fly-session", "crates/fly-session-types", "crates/flybrain-core", diff --git a/services/flysim/crates/fly-legacy-session/Cargo.toml b/services/flysim/crates/fly-legacy-session/Cargo.toml new file mode 100644 index 0000000..dba2810 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "fly-legacy-session" +version.workspace = true +edition = "2024" +rust-version.workspace = true +license.workspace = true +publish = false +description = "The live fly's composition on the session framework: the pokered-macros-v1 task and executor, the FLYSIM01 import, and the parity harness against the legacy loop's FLY_TRACE." + +[lib] +name = "fly_legacy_session" +path = "src/lib.rs" + +[dependencies] +# The session framework and its legacy workers (AGENT-01, ENV-01). +fly-session = { path = "../fly-session" } +flybus = { path = "../flybus" } +# The unchanged legacy engine the task and executor run: flysim's macro layer, flybrain-gb's +# palette, macro executor, PokeState, reward adapter and ratchet, read through MEM-01's image. +# flysim is a library dependency only; nothing here changes the service it builds. +flysim = { path = "../flysim" } +flybrain-gb = { path = "../flybrain-gb" } +flybrain-core = { path = "../flybrain-core" } +serde_json = { workspace = true } +tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] } + +[dev-dependencies] +tempfile = "3" diff --git a/services/flysim/crates/fly-legacy-session/src/admission.rs b/services/flysim/crates/fly-legacy-session/src/admission.rs new file mode 100644 index 0000000..c17ebeb --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/admission.rs @@ -0,0 +1,126 @@ +//! Sugar, admitted by the legacy rules onto the coordinator's admission queue, and the operator +//! reward pulse, refused (`legacy-gameboy-v1` section 15 and its amendment of 2026-09-29). +//! +//! The rules are flysim's own, unchanged: `flysim::ratelimit::RateLimiter` (the per-minute limit +//! and "no overlap with an active pulse") and the duration clamp to `[1, sugar_max_ms]`. What +//! changed is the pulse they read: the agent's `stimulusRemainingMs` from the **last completed +//! commit** ([`AdmissionQueue::stimulus_remaining_ms`]), which the operator accepted as one commit +//! stale. Until the first commit of an epoch it is unknown, and a request is refused with a retry. +//! A sugar admitted and not yet reported on by a commit counts as active from its admission, as +//! the legacy loop's `stimulate` makes it active at once, so two sugars between two commits are +//! one admission and one `PulseActive` refusal, exactly as the legacy drain answers them. +//! +//! The operator's `POST /reward` pulse is refused. The legacy loop refuses it too unless an +//! operator turns `control.allow_reward` on (it is off in every shipped configuration); the new +//! runtime has no counterpart to turn on, and says so rather than approximating one -- a +//! reinforcement outside `Agent.Commit` is not a session-framework operation. + +use flysim::ratelimit::{RateLimiter, Refusal}; + +use fly_session::coordinator::{Admission, AdmissionQueue}; +use fly_session::fly_session_types::gameboy::STIMULUS_REWARD_PULSE; +use fly_session::types::*; + +/// Why `POST /reward` is refused (`legacy-gameboy-v1` section 15, amendment of 2026-09-29). +pub const OPERATOR_REWARD_REFUSED: &str = "the operator reward pulse is not available on the session runtime (legacy-gameboy-v1 section 15)"; + +/// Retry advice while the pulse is unknown: one frame, rounded up. +pub const UNKNOWN_PULSE_RETRY_MS: u64 = 17; + +/// The edge-side admission of the legacy composition. +pub struct LegacyAdmission { + queue: AdmissionQueue, + agent_id: Id, + limiter: RateLimiter, + default_ms: f64, + max_ms: f64, + serial: u64, +} + +impl LegacyAdmission { + /// flysim's defaults: 6 per minute, 400 ms by default, at most 1000 ms. + pub fn new(queue: AdmissionQueue, agent_id: Id) -> LegacyAdmission { + let control = flysim::config::Config::default().control; + LegacyAdmission::with_limits( + queue, + agent_id, + control.sugar_per_minute, + control.sugar_default_ms, + control.sugar_max_ms, + ) + } + + pub fn with_limits( + queue: AdmissionQueue, + agent_id: Id, + per_minute: usize, + default_ms: f64, + max_ms: f64, + ) -> LegacyAdmission { + LegacyAdmission { + queue, + agent_id, + limiter: RateLimiter::new(per_minute), + default_ms, + max_ms, + serial: 0, + } + } + + fn next_id(&mut self, kind: &str) -> Id { + self.serial += 1; + id(&format!("{kind}-{}", self.serial)) + } + + /// `POST /stimulate`: the legacy rule over the last commit's pulse. On admission the sugar is + /// queued for the next Prepare; the result is its interaction id and the clamped duration. + pub fn sugar(&mut self, now_ms: u64, duration_ms: Option) -> Result<(Id, f64), Refusal> { + // Read the pulse, decide and queue under one lock, so a commit cannot land between the + // reads and the push (TASK-01 review R2-3). A sugar admitted and not yet reported on by + // a commit is an active pulse, as it is in the legacy loop the moment `stimulate` runs: + // a second request before the next commit is refused (`PulseActive`), not admitted + // into a pulse that would take the max and add nothing (review N1). + let agent_id = self.agent_id.clone(); + let interaction_id = self.next_id("sugar"); + let (limiter, default_ms, max_ms) = (&mut self.limiter, self.default_ms, self.max_ms); + let admission = self.queue.admit_with(&agent_id, |remaining, pending| { + let Some(remaining) = remaining else { + return Err(Refusal::PulseActive { + retry_after_ms: UNKNOWN_PULSE_RETRY_MS, + }); + }; + limiter.admit(now_ms, remaining.max(pending.unwrap_or(0.0)))?; + let duration = duration_ms.unwrap_or(default_ms).clamp(1.0, max_ms).min(max_ms); + Ok(Admission::Stimulus { + agent_id: agent_id.clone(), + interaction_id: interaction_id.clone(), + kind_id: id(STIMULUS_REWARD_PULSE), + duration_ms: duration, + }) + }); + if admission.is_err() { + // A refusal spends no id. + self.serial -= 1; + } + let Admission::Stimulus { duration_ms: duration, .. } = admission?; + Ok((interaction_id, duration)) + } + + /// `POST /reward`: refused, always (the legacy default, `control.allow_reward = false`). + pub fn reward(&mut self, _value: f64) -> Result { + Err(OPERATOR_REWARD_REFUSED) + } + + /// Admits exactly this sugar, bypassing the rules: a parity run replays the legacy loop's + /// admitted inputs, it does not re-decide them. + pub fn replay_sugar(&mut self, duration_ms: f64) -> Id { + let interaction_id = self.next_id("sugar"); + self.queue.admit(Admission::Stimulus { + agent_id: self.agent_id.clone(), + interaction_id: interaction_id.clone(), + kind_id: id(STIMULUS_REWARD_PULSE), + duration_ms, + }); + interaction_id + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/composition.rs b/services/flysim/crates/fly-legacy-session/src/composition.rs new file mode 100644 index 0000000..9085f6c --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/composition.rs @@ -0,0 +1,765 @@ +//! The legacy Game Boy composition on the session framework: one legacy agent (AGENT-01), the +//! legacy environment (ENV-01), and the `pokered-macros-v1` task and executor (this crate) in the +//! coordinator, over one router, in any of the launcher's execution modes. +//! +//! This is the whole new runtime of the live fly short of its edge (EDGE-01) and its FLYSIM01 +//! export (STATE-02): what CUT-01's shadow runs beside the legacy service. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use flybus::{Grants, Pattern, Policy, RouterConfig}; + +use fly_session::coordinator::{AgentSlot, Coordinator, StepDetails, StepReport}; +use fly_session::fly_session_types::extensions::ROLLBACK_POLICY; +use fly_session::fly_session_types::gameboy; +use fly_session::launcher::{ + ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT, + ThreadBudget, Via, +}; +use fly_session::legacy_agent::{LegacyProfileKind, SPIKES_ATTACHMENT}; +use fly_session::legacy_env::BackendConfig; +use fly_session::task::ActionExecutor; +use fly_session::types::*; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flysim::snapshot::MacroMode; + +use crate::task::{PokeredConfig, PokeredTask, TaskRecord}; +use fly_session::legacy_checkpoint::{ + AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind, + SaveReport, SaveTicket, TaskHalf, now_wall_ms, +}; +use flysim::store::Checkpoint; +use std::time::Instant; + +fn grants(f: impl FnOnce(&mut Grants)) -> Grants { + let mut g = Grants::default(); + f(&mut g); + g +} + +/// The transitions a service session keeps in memory for diagnosis (about a minute at 60 Hz). +const HISTORY: usize = 4096; + +/// Every other boundary's snapshot: the legacy feed's `snapshot_hz` (30 Hz) at 60 Hz. +const SNAPSHOT_EVERY: u64 = 2; + +const COORDINATOR_CLIENT: &str = "coordinator"; +const ENV_CLIENT: &str = "legacy-world"; +const ENV_SERVICE: &str = "env.world"; +const ENV_WORKER: &str = "world"; +const AGENT_CLIENT: &str = "legacy-fly"; + +/// How one legacy session is composed. +#[derive(Clone, Debug)] +pub struct LegacyConfig { + pub mode: ExecutionMode, + pub rom_path: PathBuf, + pub dataset_dir: PathBuf, + pub profile: LegacyProfileKind, + pub macro_mode: MacroMode, + pub agent_id: Id, + pub agent_threads: usize, + /// Record the step details and the task records (a parity run). + pub record: bool, +} + +/// The macro channels and the macro group's hold for a mode: the decoder preset flysim builds. +pub fn channels_and_hold(mode: MacroMode) -> (Vec, f64) { + let channels: Vec<&str> = if mode.dealt() { + flybrain_gb::macro_channels(crate::task::GAME) + } else { + Vec::new() + }; + let preset = gameboy_decoder_config_with_macros(&channels); + let hold_ms = preset + .macros + .as_ref() + .or(preset.exclusive.as_ref()) + .map_or(0.0, |group| group.hold_ms); + (channels.iter().map(|c| (*c).to_owned()).collect(), hold_ms) +} + +/// A running legacy session: its launcher, its coordinator and the task object. +pub struct LegacySession { + pub coordinator: Coordinator, + pub task: PokeredTask, + pub launcher: Launcher, + pub rom: Vec, + pub config: LegacyConfig, + session_id: Id, + backend: BackendConfig, + /// Which generation of the world is running: 1 is the one the session started. + world_generation: u32, + /// The legacy store policy, once attached ([`LegacySession::attach_store`]). + checkpointer: Option, + saves: u64, + /// Saves on the writer thread whose outcome has not been collected. + pending_saves: Vec, + /// Captures sent and not yet collected ([`LegacySession::begin_save`]). + pending_captures: Vec<(fly_session::coordinator::PendingCapture, SaveKind, TaskHalf)>, + /// The feed event log's watermark the saves record: the restored file's, carried over (the + /// session runtime has no feed event log of its own before EDGE-01). + last_event_id: u64, +} + +/// Where the legacy store lives and how often it is written (the service's `[paths]` and +/// `[loop]`). +#[derive(Clone, Debug)] +pub struct StoreConfig { + pub hot_dir: PathBuf, + pub durable_dir: PathBuf, + pub keep_generations: usize, + pub hot_seconds: f64, + pub checkpoint_seconds: f64, + pub speed: f64, +} + +/// This build's legacy compatibility string (`flysim --print-compatibility`): the kernel, the +/// adapter, the profile's dataset fingerprint, the plasticity rule and the pokered symbols. It is +/// the restore gate and what every save records (`legacy-gameboy-v1` section 12). +pub fn compatibility_of(config: &LegacyConfig) -> String { + let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new(); + let profile = config.profile.profile(); + flybrain_gb::Compatibility { + neural_kernel_version: gameboy::KERNEL_VERSION, + adapter: flybrain_gb::GameAdapter::id(&adapter), + dataset_fingerprint: &profile.dataset_fingerprint, + plasticity_version: gameboy::PLASTICITY_VERSION, + pokered_commit: &flybrain_gb::GameAdapter::symbol_provenance(&adapter), + } + .string() +} + +/// How a session came up. +#[derive(Debug)] +pub enum Boot { + /// No checkpoint in either store: a fresh fly, warmed up. + Fresh, + /// A candidate restored, after `skipped` were refused. + Restored { + candidate: flysim::store::Candidate, + skipped: Vec<(flysim::store::Candidate, String)>, + migrated_from: Option, + imported: crate::import::Imported, + }, +} + +/// `Sim::boot` on the session runtime: restore from the live FLYSIM01 stores in the legacy order +/// (hot latest, hot previous, durable latest, durable previous, milestone archives by rank), each +/// candidate held to the legacy gate (`RestoreGate`: the cartridge and the compatibility decision +/// with `FLY_ACCEPT_ADAPTERS`), falling to the next on *any* refusal -- unreadable, gated, or +/// refused by a participant's `State.StageRestore` or the task. A refused install fences its +/// session, so each attempt runs on a session of its own (a directory under `root` each). No +/// candidate at all is a fresh start; candidates that all fail are an error, as the legacy loop +/// refuses to start a fresh fly over them. Either way the store is attached and the startup +/// durable save is written, and the intervals run from then. +pub async fn boot( + root: &Path, + config: LegacyConfig, + store: &StoreConfig, +) -> Result<(LegacySession, Boot), String> { + let hot = flysim::store::Store::new(&store.hot_dir, store.keep_generations); + let durable = flysim::store::Store::new(&store.durable_dir, store.keep_generations); + let candidates = flysim::store::restore_order(&hot, &durable); + let rom = std::fs::read(&config.rom_path) + .map_err(|e| format!("the cartridge {}: {e}", config.rom_path.display()))?; + let adapter = flybrain_gb::pokemon_red::PokemonRedReward::new(); + let gate = fly_session::legacy_checkpoint::RestoreGate::from_env( + &sha256_hex(&rom), + &compatibility_of(&config), + flybrain_gb::GameAdapter::migrates_from(&adapter), + ); + let mut skipped: Vec<(flysim::store::Candidate, String)> = Vec::new(); + let mut outcome = None; + for (attempt, candidate) in candidates.iter().enumerate() { + let checkpoint = match flysim::store::load(&candidate.path) { + Ok(checkpoint) => checkpoint, + Err(e) => { + skipped.push((candidate.clone(), format!("{e:#}"))); + continue; + } + }; + let migrated_from = match gate.check(&checkpoint) { + Ok(from) => from, + Err(reason) => { + skipped.push((candidate.clone(), reason)); + continue; + } + }; + let mut session = + LegacySession::start(&root.join(format!("attempt-{attempt}")), config.clone()).await?; + let installed = match session.bootstrap().await { + Ok(()) => session.import_checkpoint(&checkpoint, &id("e2")).await, + Err(e) => Err(e), + }; + match installed { + Ok(imported) => { + let rank = session.task.rank(); + session.attach_store(store)?; + session + .checkpointer_mut() + .expect("attached") + .restored(rank, imported.rank_since_ms); + outcome = Some(( + session, + Boot::Restored { + candidate: candidate.clone(), + skipped: std::mem::take(&mut skipped), + migrated_from, + imported, + }, + )); + break; + } + Err(reason) => { + session.stop().await; + skipped.push((candidate.clone(), reason)); + } + } + } + let (mut session, boot) = match outcome { + Some(pair) => pair, + None if candidates.is_empty() => { + let mut session = LegacySession::start(&root.join("fresh"), config).await?; + session.bootstrap().await?; + session.attach_store(store)?; + (session, Boot::Fresh) + } + None => { + let reasons: Vec = skipped + .iter() + .map(|(candidate, reason)| format!("{}: {reason}", candidate.origin)) + .collect(); + return Err(format!( + "every one of the {} checkpoint candidates failed to load; refusing to start a \ + fresh run over them:\n{}", + candidates.len(), + reasons.join("\n") + )); + } + }; + // `Sim::boot`: a durable save of the state the process starts from, then the intervals. + session.save(SaveKind::Durable).await?; + session + .checkpointer_mut() + .expect("attached") + .start_intervals(Instant::now()); + Ok((session, boot)) +} + +/// A save [`LegacySession::advance`] queued at the boundary it reached. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SaveQueued { + pub generation: u64, + pub durable: bool, + pub archive_rank: Option, +} + +/// One transition as a parity run sees it. +pub struct Step { + pub report: StepReport, + pub details: Option, + pub records: Vec, +} + +impl LegacySession { + /// Builds the router, launches the world and the fly, and builds the coordinator with the task + /// object's two faces. Nothing has been initialized yet. + pub async fn start(root: &Path, config: LegacyConfig) -> Result { + let rom = std::fs::read(&config.rom_path) + .map_err(|e| format!("the cartridge {}: {e}", config.rom_path.display()))?; + let rom_digest = sha256_hex(&rom); + let session_id = id("legacy"); + let epoch = id("e1"); + let store_root = root.join("store"); + let sockets = root.join("sockets"); + std::fs::create_dir_all(&sockets).map_err(|e| format!("sockets: {e}"))?; + let agent_service = format!("agent.{}", config.agent_id); + let policy = Policy::closed() + .client( + COORDINATOR_CLIENT, + grants(|g| { + g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]; + g.publish = vec![Pattern::prefix("session.")]; + g.manage_topics = vec![Pattern::prefix("session.")]; + g.register = vec![Pattern::prefix("session.")]; + }), + ) + // The launcher's supervisor: health checks and shutdown, never a registration. + .client( + SUPERVISOR_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]), + ) + .client( + ENV_CLIENT, + grants(|g| g.register = vec![Pattern::exact(ENV_SERVICE)]), + ) + .client( + &format!("{ENV_CLIENT}-r2"), + grants(|g| g.register = vec![Pattern::exact(ENV_SERVICE)]), + ) + .client( + AGENT_CLIENT, + grants(|g| g.register = vec![Pattern::exact(&agent_service)]), + ); + let mut router_config = RouterConfig::new(&store_root); + router_config.policy = policy; + let router = flybus::Router::new(router_config).map_err(|e| format!("router: {e}"))?; + let budget = ThreadBudget::new(2 + config.agent_threads, 1).map_err(|e| e.message)?; + let mut launcher = Launcher::start( + router, + config.mode, + // In-process participants reach the router in memory: no socket between two tasks + // of one process (a separate process always uses the socket). + Via::Memory, + &store_root, + &sockets, + budget, + ) + .await + .map_err(|e| format!("launcher: {}", e.message))?; + + let mut backend = BackendConfig::legacy(&rom_digest); + backend.slots = vec![id(crate::task::SLOT)]; + launcher + .launch_legacy_environment(LegacyEnvironmentLaunch { + session_id: session_id.clone(), + worker_id: id(ENV_WORKER), + incarnation_id: id("world-inc-1"), + worker_threads: 1, + rom_path: config.rom_path.clone(), + backend: backend.clone(), + client_id: ENV_CLIENT.to_owned(), + service: ENV_SERVICE.to_owned(), + }) + .await + .map_err(|e| format!("the world: {}", e.message))?; + let environment = launcher + .worker(&id(ENV_WORKER)) + .expect("launched") + .worker_ref(); + + let (macro_channels, hold_ms) = channels_and_hold(config.macro_mode); + let identity = launcher + .launch_legacy_agent(LegacyAgentLaunch { + session_id: session_id.clone(), + agent_id: config.agent_id.clone(), + port_id: id(fly_session::legacy_env::DEFAULT_PORT), + incarnation_id: parse_id(&format!("{}-inc-1", config.agent_id))?, + worker_threads: config.agent_threads, + dataset_dir: config.dataset_dir.clone(), + profile: config.profile, + macro_channels: macro_channels.clone(), + client_id: AGENT_CLIENT.to_owned(), + service: agent_service, + }) + .await + .map_err(|e| format!("the fly: {}", e.message))?; + let agent_ref = launcher + .worker(&config.agent_id) + .expect("launched") + .worker_ref(); + let mut slot = AgentSlot::new( + agent_ref, + config.agent_id.clone(), + id(fly_session::legacy_env::DEFAULT_PORT), + config.profile.profile().asset, + fly_session::legacy_parity::LEGACY_SEED, + ); + slot.worker_threads = identity.worker_threads as u64; + slot.model_version = gameboy::KERNEL_VERSION.to_owned(); + slot.plasticity_version = gameboy::PLASTICITY_VERSION.to_owned(); + + let task = PokeredTask::new( + PokeredConfig { + agent_id: config.agent_id.clone(), + port_id: id(fly_session::legacy_env::DEFAULT_PORT), + mode: config.macro_mode, + macro_channels, + hold_ms, + record: config.record, + }, + &rom, + &rom_digest, + &epoch, + )?; + let client = launcher + .connect(COORDINATOR_CLIENT) + .await + .map_err(|e| format!("connect: {}", e.message))?; + let executors: BTreeMap> = + BTreeMap::from([(config.agent_id.clone(), task.executor())]); + let mut coordinator = Coordinator::new( + client, + session_id.clone(), + epoch, + id("ep1"), + environment, + vec![slot], + task.task(), + executors, + ); + coordinator.set_environment_config( + backend.asset_ref(), + fly_session::environment::synthetic_asset("pokered-task", gameboy::EXECUTOR_ID), + ); + coordinator.set_media( + &[gameboy::VIEW_ID], + &[fly_session::legacy_env::AUDIO_STREAM_ID], + ); + coordinator.set_state_format(fly_session::legacy_env::STATE_FORMAT_ID); + coordinator.set_decision_schema(gameboy::CHANNELS.schema_ref()); + coordinator + .declare_rollback_policy(ROLLBACK_POLICY) + .map_err(|e| e.message)?; + // The legacy loop runs as fast as its brain allows when measured, and the service paces + // itself; a parity run is a measurement. + if config.record { + coordinator.request_commit_attachments(&[SPIKES_ATTACHMENT]); + } else { + // A service session runs indefinitely: its in-memory history stays bounded. + coordinator.bound_history(HISTORY); + // The legacy feed publishes at `snapshot_hz` (30 Hz) from a 60 Hz loop. + coordinator.snapshot_every(SNAPSHOT_EVERY); + } + Ok(LegacySession { + coordinator, + task, + launcher, + rom, + config, + session_id, + backend, + world_generation: 1, + checkpointer: None, + saves: 0, + pending_saves: Vec::new(), + pending_captures: Vec::new(), + last_event_id: 0, + }) + } + + /// Hello, `Environment.Initialize` (the one-frame scaffold), the task's bootstrap on O[0], + /// `Agent.Initialize` (the warm-up): `Ready(0)`. + pub async fn bootstrap(&mut self) -> Result<(), String> { + self.coordinator + .bootstrap() + .await + .map_err(|e| format!("bootstrap ({}): {}", e.detail, e.error.message))?; + if self.config.record { + self.coordinator.disable_pacing(); + } + Ok(()) + } + + /// The agent's identity as an import stamps it. + pub fn agent_import(&self) -> AgentImport { + let (macro_channels, _) = channels_and_hold(self.config.macro_mode); + AgentImport { + agent_id: self.config.agent_id.clone(), + profile: self.config.profile.profile().asset, + seed: fly_session::legacy_parity::LEGACY_SEED, + macro_channels, + } + } + + /// This build's legacy compatibility string ([`compatibility_of`]). + pub fn compatibility(&self) -> String { + compatibility_of(&self.config) + } + + /// Installs a FLYSIM01 checkpoint as this session's start (after [`LegacySession::bootstrap`], + /// before any transition): the world is replaced by a fresh one (the environment stages a + /// restore only on a replacement, as every group restore does), then [`crate::import`] runs + /// the group install and the session resumes at the checkpoint's boundary. + pub async fn import_checkpoint( + &mut self, + checkpoint: &Checkpoint, + epoch: &Id, + ) -> Result { + if self.world_generation != 1 { + return Err("this session has already replaced its world".to_owned()); + } + self.launcher.reap(&id(ENV_WORKER), &id("import")).await; + self.world_generation = 2; + self.launcher + .launch_legacy_environment(LegacyEnvironmentLaunch { + session_id: self.session_id.clone(), + worker_id: id(ENV_WORKER), + incarnation_id: id("world-inc-2"), + worker_threads: 1, + rom_path: self.config.rom_path.clone(), + backend: self.backend.clone(), + client_id: format!("{ENV_CLIENT}-r2"), + service: ENV_SERVICE.to_owned(), + }) + .await + .map_err(|e| format!("the replacement world: {}", e.message))?; + let world = self + .launcher + .worker(&id(ENV_WORKER)) + .expect("launched") + .worker_ref(); + self.coordinator + .replace_participant(&id(ENV_WORKER), world) + .map_err(|e| format!("replacing the world: {}", e.error.message))?; + let rom = self.rom.clone(); + let agent = self.agent_import(); + let imported = crate::import::import_flysim01( + &mut self.coordinator, + &self.task, + checkpoint, + &rom, + &agent, + self.backend.audio_sample_rate, + epoch, + ) + .await?; + if self.config.record { + self.coordinator.disable_pacing(); + } + self.last_event_id = checkpoint.runtime.last_event_id; + Ok(imported) + } + + /// Decodes FLYSIM01 bytes and installs them ([`LegacySession::import_checkpoint`]). + pub async fn import_flysim01( + &mut self, + bytes: &[u8], + epoch: &Id, + ) -> Result { + let checkpoint = flysim::store::decode(bytes).map_err(|e| format!("FLYSIM01: {e:#}"))?; + self.import_checkpoint(&checkpoint, epoch).await + } + + // -- the store (STATE-02) ------------------------------------------------------------------ + + /// Attaches the legacy store policy (`LegacyCheckpointer`): FLYSIM01 generations in the hot + /// and durable stores, milestone archives, the legacy intervals. Rollbacks are deferred from + /// here on, so a milestone capture lands between the boundary's slot save and its rollback. + pub fn attach_store(&mut self, store: &StoreConfig) -> Result<(), String> { + let checkpointer = LegacyCheckpointer::open(CheckpointerConfig { + hot_dir: store.hot_dir.clone(), + durable_dir: store.durable_dir.clone(), + keep_generations: store.keep_generations, + hot_seconds: store.hot_seconds, + checkpoint_seconds: store.checkpoint_seconds, + compatibility: self.compatibility(), + speed: store.speed, + slot_id: id(crate::task::SLOT), + })?; + self.checkpointer = Some(checkpointer); + self.coordinator.defer_rollbacks(true); + Ok(()) + } + + pub fn checkpointer(&self) -> Option<&LegacyCheckpointer> { + self.checkpointer.as_ref() + } + + pub fn checkpointer_mut(&mut self) -> Option<&mut LegacyCheckpointer> { + self.checkpointer.as_mut() + } + + /// One save of the committed boundary, written by the checkpointer's writer thread; waits for + /// the commit, so a caller that goes on to read the store finds it. For the startup and + /// shutdown saves, which the legacy loop takes blocking too. + pub async fn save(&mut self, kind: SaveKind) -> Result { + let ticket = self.queue_save(kind).await?; + ticket + .reply + .await + .map_err(|_| "the checkpoint writer stopped".to_owned())? + } + + /// One save of the committed boundary, queued: the participants capture now (the boundary's + /// state) and the encoding and fsync run on the checkpointer's writer thread while the loop + /// goes on, as the legacy loop hands its saves to its writer thread (TASK-01 review N4). The + /// outcome is collected by [`LegacySession::completed_saves`]. + pub async fn queue_save(&mut self, kind: SaveKind) -> Result { + self.begin_save(kind).await?; + let mut tickets = self.finish_captures().await?; + let last = tickets + .pop() + .ok_or_else(|| "no save was begun".to_owned())?; + self.pending_saves.extend(tickets); + Ok(last) + } + + /// Begins one save of the committed boundary: every participant's `State.Capture` is sent + /// (each takes its state now) and the task's half is taken now; the session may step on + /// while the agent encodes and seals its payload off its lock + /// (`Coordinator::begin_capture`, TASK-01 review N5). [`LegacySession::finish_captures`] + /// hands it to the writer. + pub async fn begin_save(&mut self, kind: SaveKind) -> Result<(), String> { + self.saves += 1; + let capture = self + .coordinator + .begin_capture(&parse_id(&format!("legacy-save-{}", self.saves))?) + .await + .map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?; + let (task, _slot_filled) = self.task.task_half(); + self.pending_captures.push((capture, kind, task)); + Ok(()) + } + + /// Collects every begun capture, in order, and queues it to the checkpointer's writer. + pub async fn finish_captures(&mut self) -> Result, String> { + let mut tickets = Vec::new(); + for (capture, kind, task) in std::mem::take(&mut self.pending_captures) { + let (boundary, world, agents) = self + .coordinator + .finish_capture(capture) + .await + .map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?; + let [(_, agent)] = <[(Id, Vec); 1]>::try_from(agents) + .map_err(|_| "the legacy composition has exactly one agent".to_owned())?; + let capture = LegacyCapture { + boundary, + agent_payload: agent, + world_payload: world, + task, + }; + let last_event_id = self.last_event_id; + let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?; + tickets.push(checkpointer.save(kind, capture, last_event_id, now_wall_ms())?); + } + Ok(tickets) + } + + /// The saves queued so far that have committed (or failed), without waiting; with `wait`, + /// every queued save's outcome. Every outcome is reported, a failed save as its own `Err` + /// beside the others (TASK-01 review R2-2): the caller decides. + pub async fn completed_saves(&mut self, wait: bool) -> Vec> { + let mut done = Vec::new(); + let mut still = Vec::new(); + for mut ticket in std::mem::take(&mut self.pending_saves) { + let stopped = || Err("the checkpoint writer stopped".to_owned()); + if wait { + done.push((&mut ticket.reply).await.unwrap_or_else(|_| stopped())); + } else { + match ticket.reply.try_recv() { + Ok(result) => done.push(result), + Err(tokio::sync::oneshot::error::TryRecvError::Empty) => still.push(ticket), + Err(tokio::sync::oneshot::error::TryRecvError::Closed) => done.push(stopped()), + } + } + } + self.pending_saves = still; + done + } + + /// Hands every begun capture to the writer now and reports what was queued. `advance` does + /// this after the next step so the agent's sealing overlaps it; a step that fails does it + /// before returning the error, and a caller that pauses (or is about to stop stepping) calls + /// this so a save begun at the last boundary reaches the writer as the legacy loop's + /// immediate hand-off would have (TASK-01 review R2-1). + pub async fn flush_captures(&mut self) -> Result, String> { + let mut saves = Vec::new(); + for ticket in self.finish_captures().await? { + saves.push(SaveQueued { + generation: ticket.generation, + durable: ticket.durable, + archive_rank: ticket.archive_rank, + }); + self.pending_saves.push(ticket); + } + Ok(saves) + } + + /// One transition and what the legacy loop does at the boundary it reaches, in the declared + /// order (`legacy-gameboy-v1` sections 4 and 16): the slot save (inside the step), the + /// milestone archive when the rank climbed (`Sim::track_rank`), the rollback, a durable save + /// after it, then the interval saves (`checkpoint_if_due`). + pub async fn advance(&mut self) -> Result<(Step, Vec), String> { + let report = match self.coordinator.step().await { + Ok(report) => report, + Err(e) => { + // The legacy writer already has the saves of the earlier boundaries: hand the + // begun captures over before reporting the failure (TASK-01 review R2-1). + let flushed = self.flush_captures().await.err(); + let mut message = + format!("step ({} at {}): {}", e.detail, e.phase, e.error.message); + if let Some(flush) = flushed { + message.push_str(&format!("; and the pending saves: {flush}")); + } + return Err(message); + } + }; + // The captures begun at the last boundary: the agent sealed its payload while this + // transition's Prepare ticked. + let saves = self.flush_captures().await?; + if self.checkpointer.is_some() { + let rank = self.task.rank(); + let ms = self.task.brain_ms(); + let change = self + .checkpointer + .as_mut() + .expect("attached") + .observe_rank(rank, ms); + if let Some(RankChange::Climbed(rank)) = change { + self.begin_save(SaveKind::Milestone(rank)).await?; + } + } + let rolled_back = self + .coordinator + .apply_pending_rollback() + .await + .map_err(|e| { + format!( + "rollback ({} at {}): {}", + e.detail, e.phase, e.error.message + ) + })?; + if self.checkpointer.is_some() { + if rolled_back { + self.begin_save(SaveKind::Durable).await?; + } + let due = self + .checkpointer + .as_mut() + .expect("attached") + .due(Instant::now()); + if let Some(kind) = due { + self.begin_save(kind).await?; + } + } + Ok(( + Step { + report, + details: self.coordinator.take_details(), + records: self.task.take_records(), + }, + saves, + )) + } + + /// One transition, with its details when recorded ([`LegacySession::advance`] without the + /// saves it reports). + pub async fn step(&mut self) -> Result { + self.advance().await.map(|(step, _)| step) + } + + /// A durable save, as the legacy loop takes on shutdown, then the store's writer is closed. + pub async fn shutdown_save(&mut self) -> Result, String> { + if self.checkpointer.is_none() { + return Ok(None); + } + self.flush_captures().await?; + let report = self.save(SaveKind::Durable).await?; + let outcomes = self.completed_saves(true).await; + if let Some(checkpointer) = self.checkpointer.as_mut() { + checkpointer.close(); + } + // Every queued save has been waited for; the first failure is the shutdown's. + for outcome in outcomes { + outcome?; + } + Ok(Some(report)) + } + + pub async fn stop(mut self) { + self.launcher.reap_all(&id("done")).await; + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/driver.rs b/services/flysim/crates/fly-legacy-session/src/driver.rs new file mode 100644 index 0000000..89c2c82 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/driver.rs @@ -0,0 +1,79 @@ +//! A stub readout for parity runs that must earn real rewards: the rotation driver of flysim's ROM +//! tests (`tests/rom_catch.rs`, `tests/rom_macros_mode.rs`) -- a decoder of its own, fed rates +//! that lean on one macro population at a time, rotating every [`BURST_FRAMES`] frames. +//! +//! The brain still ticks and decodes exactly as it would; the driver only replaces the decision +//! the executor is handed, at the one point the legacy loop lets a harness do that +//! (`flysim::frame::FrameObserver::readout`). A session run hands the same driver the same +//! `(ms, bound)` in its executor ([`crate::task::PokeredTask::set_driver`]), so both arms press the +//! same macros and the rewards those macros earn reach `Agent.Commit`. Not a service path. + +use flybrain_core::decoder::PopulationDecoder; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flybrain_core::ordered::NumberMap; + +/// Frames the stub leans on one channel before the rotation moves on (`rom_catch.rs`). +pub const BURST_FRAMES: u32 = 24; +/// The hot population's rate, and every other one's (`rom_catch.rs`). +const HOT: f64 = 16.0; +const REST: f64 = 10.0; + +/// Replaces a decision, given the brain clock and the scene's bound channels. +pub trait DecisionDriver: Send { + fn readout(&mut self, ms: f64, bound: &[String], active: &mut Vec); +} + +/// The rotation: one macro population hot at a time, in channel order. +pub struct RotationDriver { + decoder: PopulationDecoder, + channels: Vec<&'static str>, + frame: u32, +} + +impl Default for RotationDriver { + fn default() -> Self { + Self::new() + } +} + +impl RotationDriver { + pub fn new() -> RotationDriver { + let channels = flybrain_gb::macro_channels(crate::task::GAME); + let mut decoder = PopulationDecoder::new(gameboy_decoder_config_with_macros(&channels)) + .expect("the preset is well formed"); + decoder.calibrate(&rates(&channels, None)); + RotationDriver { + decoder, + channels, + frame: 0, + } + } +} + +fn rates(channels: &[&str], hot: Option<&str>) -> NumberMap { + let mut rates = NumberMap::new(); + for channel in channels { + rates.set(channel, REST); + } + for bucket in 0..8 { + rates.set(&format!("command_{bucket}"), REST); + } + if let Some(channel) = hot { + rates.set(channel, HOT); + } + rates +} + +impl DecisionDriver for RotationDriver { + fn readout(&mut self, ms: f64, bound: &[String], active: &mut Vec) { + let hot = self.channels[(self.frame / BURST_FRAMES) as usize % self.channels.len()]; + self.frame += 1; + *active = self.decoder.decode_bound( + &rates(&self.channels, Some(hot)), + ms, + false, + None, + Some(bound), + ); + } +} diff --git a/services/flysim/crates/fly-legacy-session/src/import.rs b/services/flysim/crates/fly-legacy-session/src/import.rs new file mode 100644 index 0000000..ccf2b32 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/import.rs @@ -0,0 +1,140 @@ +//! A FLYSIM01 checkpoint as a session's start: the legacy fly's own save, installed into the new +//! runtime through the ordinary group restore (`Coordinator::import`). +//! +//! The halves are STATE-02's (`fly_session::legacy_checkpoint`): the world as ENV-01's `FLYENV01` +//! payload at `k = emulatorFrame - 1` with the ratchet's snapshot as slot `best`; the agent as its +//! `FLYAGT01` payload with the file's reinforcement count and the file's framebuffer as the next +//! input, as `LegacyFrame::restore` installs it; the task as `{reward, ratchet, slotFilled}`. The ids +//! come from the file (`flysim01-g`, source scope `(session, legacy, k)`). +//! +//! The rest is `restore: legacy-transient-reset` (`legacy-gameboy-v1` section 14): the executor +//! starts fresh and observes the restored boundary, and the agent's readout transient starts as a +//! fresh process has it. The decision context the agent resumes with is computed here, from the +//! task's ledger and the checkpoint's own memory image. After the install the coordinator holds the +//! task to it: `Task::restored` re-observes the restored world and must derive the same context. + +use std::collections::BTreeMap; + +use fly_session::coordinator::{Coordinator, ImportSpec, ImportedAgent}; +use fly_session::legacy_agent::legacy_remainder_to_rational; +use fly_session::legacy_checkpoint::{ + AgentImport, agent_payload, halves, import_checkpoint_id, legacy_source_scope, world_payload, +}; +use fly_session::types::*; +use flybrain_gb::{DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, MemoryImage}; +use flysim::store::Checkpoint; + +use crate::task::PokeredTask; + +/// What an import installed. +#[derive(Clone, Debug)] +pub struct Imported { + pub boundary: u64, + pub epoch: Id, + pub brain_ticks: u64, + pub checkpoint_id: Id, + /// The file's `rankSinceMs` and generation, for the host's rank tracking and store. + pub rank_since_ms: f64, + pub generation: u64, +} + +/// The checkpoint's memory image at its boundary, read as the environment reads it after an +/// import: the emulator state imported into a stopped emulator, then MEM-01's one bulk read. +pub fn image_of(rom: &[u8], emulator_state: &[u8]) -> Result { + let mut emulator = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES) + .map_err(|e| format!("the cartridge: {e}"))?; + emulator + .import_state(emulator_state) + .map_err(|e| format!("the emulator state: {e}"))?; + Ok(emulator.read_memory_image()) +} + +/// Installs a FLYSIM01 checkpoint as the start of a bootstrapped session that has taken no +/// transition, onto a replacement world. `task` is the composition's task object. +pub async fn import_flysim01( + coordinator: &mut Coordinator, + task: &PokeredTask, + checkpoint: &Checkpoint, + rom: &[u8], + agent: &AgentImport, + audio_sample_rate: u64, + new_epoch: &Id, +) -> Result { + let descriptor = coordinator + .descriptor() + .cloned() + .ok_or("the session never bootstrapped")?; + let halves = halves( + checkpoint, + coordinator.episode_id(), + &id(crate::task::SLOT), + audio_sample_rate, + )?; + let boundary = halves.world.boundary; + let checkpoint_id = import_checkpoint_id(halves.host.generation); + let scope = legacy_source_scope(coordinator.session_id(), boundary); + let world = world_payload( + &halves.world, + &coordinator.environment_ref().worker_id, + &checkpoint_id, + &scope, + &descriptor.configuration_digest, + ); + + // The task's ledger, and from it and the restored image the context the agent resumes with. + let (ledger, task_attachments) = + PokeredTask::ledger_of(&halves.task, !checkpoint.runtime.ratchet_game.is_empty()) + .map_err(|e| format!("the task ledger: {}", e.message))?; + let brain_ms = halves.agent.network.ms; + // `Sim::boot` seeds the palette from the restored brain's RNG state. + task.set_palette_seed(halves.agent.network.rng as u32); + let image = image_of(rom, &halves.world.emulator)?; + let context = task.preview_context(&ledger, &task_attachments, &image, brain_ms)?; + let payload = agent_payload( + &halves.agent, + halves.reinforcements, + &checkpoint.runtime.framebuffer, + agent, + &checkpoint_id, + &scope, + &context, + )?; + let remainder = legacy_remainder_to_rational(halves.agent.remainder) + .map_err(|e| format!("the remainder: {e}"))?; + let audio_positions: BTreeMap = descriptor + .audio + .iter() + .map(|stream| (stream.stream_id.clone(), halves.world.audio_next_sample)) + .collect(); + let spec = ImportSpec { + checkpoint_id: checkpoint_id.clone(), + source_scope: scope, + boundary, + world_payload: world, + agents: vec![ImportedAgent { + agent_id: agent.agent_id.clone(), + payload, + brain_ticks: brain_ms as u64, + remainder, + context, + }], + task_ledger: ledger, + task_attachments, + audio_positions, + }; + coordinator + .import(spec, new_epoch) + .await + .map_err(|e| format!("the import ({}): {}", e.detail, e.error.message))?; + coordinator + .resume() + .map_err(|e| format!("resuming the import: {}", e.error.message))?; + Ok(Imported { + boundary, + epoch: new_epoch.clone(), + brain_ticks: brain_ms as u64, + checkpoint_id, + rank_since_ms: halves.host.rank_since_ms, + generation: halves.host.generation, + }) +} diff --git a/services/flysim/crates/fly-legacy-session/src/lib.rs b/services/flysim/crates/fly-legacy-session/src/lib.rs new file mode 100644 index 0000000..d1cda7c --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/lib.rs @@ -0,0 +1,19 @@ +//! The live fly on the session framework (TASK-01). +//! +//! - [`task`]: `pokered-macros-v1`, the Pokémon Red task and its action executor as one object, +//! running the legacy macro engine and reward adapter unchanged over the boundary memory image. +//! - [`composition`]: the legacy agent, the legacy environment and the task under one coordinator. +//! - [`import`]: a FLYSIM01 checkpoint as the session's start. +//! - [`admission`]: sugar by the legacy rules; the operator reward pulse refused. +//! - [`trace`]: the session's `FLY_TRACE`, in the legacy loop's format, and the comparison. +//! - [`driver`]: a stub readout for parity runs that must earn rewards. +//! +//! `docs/design/session-framework/legacy-gameboy-v1.md` is the contract, `implementation.md` +//! TASK-01 the record. + +pub mod admission; +pub mod composition; +pub mod driver; +pub mod import; +pub mod task; +pub mod trace; diff --git a/services/flysim/crates/fly-legacy-session/src/task.rs b/services/flysim/crates/fly-legacy-session/src/task.rs new file mode 100644 index 0000000..db3f2bf --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/task.rs @@ -0,0 +1,985 @@ +//! `pokered-macros-v1`: the Pokémon Red task and its action executor, one object +//! (`legacy-gameboy-v1` section 10, `workers-v1` section 4 amendment of 2026-09-23). +//! +//! Nothing here is a port of a rule. The reward adapter (`PokemonRedReward`), the ratchet, and the +//! macro layer (`flysim::macros::MacroLayer` over `flybrain-gb`'s palette, executor and `PokeState`) +//! are the very types the legacy loop runs, called in `flysim::frame::LegacyFrame`'s order. What +//! changed is what they read: a boundary's 64 KiB memory image and the cartridge, through +//! `flybrain_gb::ImageReader` (MEM-01), instead of a live emulator. +//! +//! | legacy frame | here | +//! | --- | --- | +//! | `execute`: `MacroLayer::decide` over the emulator | Phase B, [`ActionExecutor::apply`] over `ImageReader(O[k])` | +//! | `evaluate`: `adapter.sample`, `MacroLayer::observe`, location, progress | Phase C, [`Task::evaluate_transition`] over `ImageReader(O[k+1])` | +//! | `boundary`: the ratchet's capture and decision | Phase C too: a slot save and a rollback request, applied by the coordinator at `Ready(k+1)` | +//! | `rollback`: `recover_game`'s `clear_transient`, `cancel`, `observe` | [`Task::rollback`] over `ImageReader(O'[k+1])` | +//! +//! The ratchet keeps its ledger here; its *slot* lives in the environment (`gameboy-slots-v1`). +//! The ratchet only needs to know a slot exists (its budget test is `snapshot.is_none()`), so it +//! holds a marker [`Snapshot`] in place of the bytes. +//! +//! `restore: legacy-transient-reset` (section 14): a restore installs the adapter and the ratchet, +//! and the executor starts as a fresh process has it -- a new macro layer with empty ledgers and +//! nothing running, which observes the restored boundary before it decides anything. + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex, MutexGuard}; + +use serde_json::{Value, json}; + +use fly_session::fly_session_types::gameboy::{ + self, ChannelsDecision, Location, MemoryInspection, ReadoutContext, RollbackRequest, +}; +use fly_session::legacy_checkpoint::TaskHalf; +use fly_session::task::{ + ActionExecutor, Bootstrap, Evaluation, Inspection, RollbackEvaluation, Task, +}; +use fly_session::types::*; +use flybrain_core::decoder::gameboy::to_button_mask; +use flybrain_gb::adapter::GameAdapter; +use flybrain_gb::emulator::FRAMEBUFFER_LEN; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flybrain_gb::ratchet::{Ratchet, Snapshot}; +use flybrain_gb::{AdapterLedger, Cartridge, ImageReader, MemoryImage}; +use flysim::config::Config; +use flysim::macros::{MacroEvent, MacroLayer, macro_layer}; +use flysim::snapshot::MacroMode; + +/// The attachment the image travels under (ENV-01's `legacy_env::MEMORY_ATTACHMENT`). +pub const MEMORY_ATTACHMENT: &str = fly_session::legacy_env::MEMORY_ATTACHMENT; +/// The composition's one slot, which is the ratchet's. +pub const SLOT: &str = fly_session::legacy_env::DEFAULT_SLOT; +/// The game id the adapter and the palette are chosen by. +pub const GAME: &str = "pokemon-red"; +/// The palette seed of a fresh start. The legacy loop seeds the palette from the brain's RNG +/// state after the warm-up (`Sim::boot`: `rng_state() as u32`), which the task cannot read: the +/// agent does not publish it. It is also never read: `MacroMachine`'s generator is written and +/// never consulted (no macro has a random step), which `tests/palette_seed.rs` holds on the +/// cartridge, so a fresh start's constant presses exactly what the legacy seed presses. A +/// restore uses the legacy seed itself, the imported agent state's RNG +/// ([`PokeredTask::set_palette_seed`]). +pub const PALETTE_SEED: u32 = 0; + +fn schema(name: &str) -> SchemaRef { + let digest = digest_of_bytes(format!("fly-legacy-session-schema-v1\n{name}\n1\n").as_bytes()); + SchemaRef::new(name, 1, &digest).expect("a task-local schema reference is valid") +} + +/// The task ledger's schema: STATE-02's `TaskHalf` ledger `{reward, ratchet, slotFilled}` -- +/// FLYSIM01's `reward` and `ratchet`, and whether the environment's slot `best` holds the +/// ratchet's snapshot. Nothing else: the executor's ledgers and the adapter's transient +/// observations are not captured (`legacy-transient-reset`). +pub fn ledger_schema() -> SchemaRef { + schema("pokered-task-ledger-v1") +} +/// The attachment the task ledger's adapter state travels as (its JSON). +pub const REWARD_ATTACHMENT: &str = "reward"; + +/// The executor's capture: a marker only, because its state is transient (section 10, "Capture"). +pub fn executor_schema() -> SchemaRef { + schema("pokered.executor.v1") +} +pub fn progress_schema() -> SchemaRef { + schema("pokered.progress.v1") +} +pub fn event_schema() -> SchemaRef { + schema("pokered.event.v1") +} + +fn state_error(message: impl std::fmt::Display) -> DomainError { + DomainError::before(ErrorCode::IncompatibleState, message) +} + +/// The ratchet's stand-in for a slot it knows the environment holds. +fn slot_marker() -> Snapshot { + Snapshot { + game: format!("slot:{SLOT}").into_bytes(), + frame: vec![0; FRAMEBUFFER_LEN], + } +} + +/// The legacy trace's JSON of one macro event (`flysim::trace::macro_json`). +pub fn macro_json(phase: &str, event: &MacroEvent) -> Value { + json!({ + "phase": phase, + "slot": event.slot, + "name": event.name, + "outcome": event.outcome.map(|outcome| outcome.as_str()), + }) +} + +/// What the object did in one transition, for the trace and the ledger comparison: the fields of +/// `flysim-legacy-frame-trace-v1` that are the task's and the executor's. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct TaskRecord { + /// The boundary the transition started from. + pub boundary: u64, + /// The decision as the executor was given it, as the legacy active set (buttons, then the + /// macro channel). + pub decision: Vec, + /// The bound channels the decision was masked to (the context of this transition's Prepare). + pub bound: Vec, + pub mask: u32, + /// `macroEvents`, phases `execute`, `evaluate` and `rollback`, in order. + pub macro_events: Vec, + /// SHA-256 of work RAM, `$C000-$DFFF`, of O[k+1]. + pub wram_digest: String, + /// `rewards`: `{kind, value, stimulationMs}` in adapter order. + pub rewards: Vec, + pub rank: u32, + /// The ratchet asked for a slot save at `Ready(k+1)`. + pub saved: bool, + /// The ratchet asked for a rollback at `Ready(k+1)`, and it ran. + pub rolled_back: bool, + /// The ledgers after the boundary: adapter, ratchet and executor, as one canonical string. + pub ledgers: String, +} + +/// The ledgers as one canonical string: the adapter's export (its lifetime ledgers), the +/// ratchet's state and whether it holds a slot, and the executor's observable state -- scene, +/// bound channels, running macro, outcome counts, "nearer the objective". A legacy loop computes +/// the same string from its own parts, which is how a parity run compares ledgers frame by frame. +pub fn ledgers_of( + adapter: &PokemonRedReward, + ratchet: &Ratchet, + macros: Option<&MacroLayer>, +) -> String { + let executor = match macros { + Some(layer) => json!({ + "scene": layer.scene_name(), + "bound": layer.bound_channels(), + "running": layer.running(), + "counts": format!("{:?}", layer.counts()), + "nearer": layer.nearer_the_objective(), + }), + None => Value::Null, + }; + json!({ + "adapter": adapter.export_state(), + "ratchet": serde_json::to_value(ratchet.state).expect("serializes"), + "slot": ratchet.snapshot.is_some(), + "executor": executor, + }) + .to_string() +} + +/// How the object is configured. Everything here is composition, not state. +#[derive(Clone, Debug)] +pub struct PokeredConfig { + pub agent_id: Id, + pub port_id: Id, + pub mode: MacroMode, + /// `executor.macroChannels`, composition order; empty in raw mode. + pub macro_channels: Vec, + /// The macro group's `holdMs` from the decoder configuration. + pub hold_ms: f64, + /// Record a [`TaskRecord`] per transition (a parity run); off in service. + pub record: bool, +} + +struct Inner { + config: PokeredConfig, + cartridge: Cartridge, + adapter: PokemonRedReward, + ratchet: Ratchet, + macros: Option, + epoch: Id, + /// O[k]: the image the executor reads in Phase B and the task reads as "old" in Phase C. + current: Option<(u64, MemoryImage)>, + /// The brain clock of the transition in flight (Phase B's clock), in ms. + ms: f64, + evaluations: u64, + issued: u64, + last_source_step: u64, + open: Option, + records: Vec, + /// A parity run's stub readout ([`crate::driver`]); never set in service. + driver: Option>, + /// Addresses the engine read that the image does not capture ([`Watched`]). + uncaptured: std::collections::BTreeSet, + /// The seed the next fresh macro layer is built with ([`PALETTE_SEED`], or a restored + /// agent's RNG state as the legacy loop seeds it). + palette_seed: u32, +} + +/// The one object. [`PokeredTask::task`] and [`PokeredTask::executor`] are its two faces; the +/// coordinator holds each where it expects a task and an executor, and both reach the same state. +#[derive(Clone)] +pub struct PokeredTask { + inner: Arc>, +} + +impl PokeredTask { + /// A fresh object over the cartridge. `rom_digest` is the environment's `contentDigest`: a + /// cartridge that is not it is refused (`legacy-gameboy-v1` section 8). + pub fn new( + config: PokeredConfig, + rom: &[u8], + rom_digest: &str, + epoch: &Id, + ) -> Result { + let cartridge = Cartridge::verified(rom, rom_digest).map_err(|e| e.to_string())?; + let adapter = PokemonRedReward::new(); + let ratchet = Ratchet::with_policy(adapter.recovery_policy()); + let macros = fresh_layer(&config, PALETTE_SEED); + Ok(Self { + inner: Arc::new(Mutex::new(Inner { + config, + cartridge, + adapter, + ratchet, + macros, + epoch: epoch.clone(), + current: None, + ms: 0.0, + evaluations: 0, + issued: 0, + last_source_step: 0, + open: None, + records: Vec::new(), + driver: None, + uncaptured: std::collections::BTreeSet::new(), + palette_seed: PALETTE_SEED, + })), + }) + } + + fn lock(&self) -> MutexGuard<'_, Inner> { + self.inner + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// The task face. + pub fn task(&self) -> Box { + Box::new(TaskFace(self.clone())) + } + + /// The executor face. + pub fn executor(&self) -> Box { + Box::new(ExecutorFace(self.clone())) + } + + /// Replace every decision the executor is handed by `driver`'s, as a legacy harness does + /// through `FrameObserver::readout`. A parity run's tool; the service never sets one. + pub fn set_driver(&self, driver: Box) { + self.lock().driver = Some(driver); + } + + /// Every address the engine has read that the image does not capture. Empty is the contract + /// (`legacy-gameboy-v1` section 8): a register window reads `$FF` in the image. + pub fn uncaptured_reads(&self) -> Vec { + self.lock().uncaptured.iter().copied().collect() + } + + /// Seeds the next restore's fresh macro layer as the legacy loop does after a restore: with + /// the restored brain's RNG state (`rng_state() as u32`). + pub fn set_palette_seed(&self, seed: u32) { + self.lock().palette_seed = seed; + } + + /// The records since the last call. + pub fn take_records(&self) -> Vec { + std::mem::take(&mut self.lock().records) + } + + /// The ledgers as one canonical string: the adapter's export, the ratchet's state, and the + /// executor's observable state (scene, bound channels, running macro, outcome counts). + pub fn ledgers(&self) -> String { + self.lock().ledgers() + } + + /// The ledger of a task half (STATE-02's `TaskHalf`, FLYSIM01's `reward` and `ratchet`), with + /// whether the ratchet holds a snapshot (which the environment's slot `best` now holds). + /// + /// The adapter's lifetime ledger grows with play and is past the 32 KiB `TypedValue` bound on + /// the live fly (42-46 KB at rank 12-15), so it is artifact-backed (`workers-v1` section 1): + /// the typed value is `{reward: {digest, byteLength}, ratchet, slotFilled}` and the reward's + /// JSON travels as the attachment [`REWARD_ATTACHMENT`]. + pub fn ledger_of( + half: &TaskHalf, + slot_filled: bool, + ) -> DomainResult<(TypedValue, BTreeMap>)> { + // The adapter's own JSON, exactly as FLYSIM01's `reward` member holds it. + let reward = serde_json::to_vec(&half.reward) + .map_err(|e| state_error(format!("the adapter ledger: {e}")))?; + let value = json!({ + "reward": {"digest": digest_of_bytes(&reward), "byteLength": reward.len().to_string()}, + "ratchet": serde_json::to_value(half.ratchet) + .map_err(|e| state_error(format!("the ratchet: {e}")))?, + "slotFilled": slot_filled, + }); + let typed = TypedValue::new(ledger_schema(), value).map_err(|e| state_error(e.0))?; + Ok(( + typed, + BTreeMap::from([(REWARD_ATTACHMENT.to_owned(), reward)]), + )) + } + + /// The task's half of a FLYSIM01 export at the committed boundary, and whether the slot is + /// filled. + pub fn task_half(&self) -> (TaskHalf, bool) { + let inner = self.lock(); + ( + TaskHalf { + reward: inner.adapter.export_state(), + ratchet: inner.ratchet.state, + }, + inner.ratchet.snapshot.is_some(), + ) + } + + /// The brain time of the last transition (its Prepare's clock), in ms: `network.ms`. + pub fn brain_ms(&self) -> f64 { + self.lock().ms + } + + /// The adapter's ladder rank now (`Sim::track_rank` reads it after each transition). + pub fn rank(&self) -> u32 { + self.lock().adapter.progress().rank + } + + /// The context a restore of `ledger` onto the boundary `image` shows at brain time `ms`: what + /// [`Task::restored`] will compute after the install, computed before it so the agent's + /// payload can carry it. Changes nothing. + pub fn preview_context( + &self, + ledger: &TypedValue, + attachments: &BTreeMap>, + image: &MemoryImage, + ms: f64, + ) -> Result { + let inner = self.lock(); + let (adapter, _ratchet) = + parse_ledger(&inner, ledger, attachments).map_err(|e| e.message)?; + let mut layer = fresh_layer(&inner.config, inner.palette_seed); + if let Some(layer) = layer.as_mut() { + let mut reader = ImageReader::new(image, &inner.cartridge); + let _ = layer.observe(&mut reader, &AdapterLedger(&adapter), ms); + } + Ok(ReadoutContext { + boot: adapter.boot(), + bound: layer + .as_ref() + .map(MacroLayer::bound_channels) + .unwrap_or_default(), + location: adapter + .location() + .map(|(area, x, y)| Location { area, x, y }), + } + .to_typed()) + } + + /// The readout context the task would hand the decoder now. + pub fn context(&self) -> ReadoutContext { + self.lock().context() + } +} + +/// `Sim::boot`'s layer: the configuration's palette at the macro group's hold. +fn fresh_layer(config: &PokeredConfig, seed: u32) -> Option { + let mut service = Config::default(); + service.loop_.game = GAME.to_owned(); + service.macros.mode = config.mode; + macro_layer(&service, config.hold_ms, seed) +} + +/// The image reader the engine is handed: `ImageReader`, plus a record of any address it was asked +/// for that the image does not capture (`legacy-gameboy-v1` section 8, MEM-01 amendment). Such a +/// read answers `$FF` where the live emulator would answer the register, so the engine and the +/// legacy loop could disagree; the record makes that visible rather than silent. +struct Watched<'a> { + reader: ImageReader<'a>, + uncaptured: &'a mut std::collections::BTreeSet, +} + +impl flybrain_gb::adapter::MemoryReader for Watched<'_> { + fn read8(&mut self, address: u16) -> u8 { + if !flybrain_gb::captured(address) { + self.uncaptured.insert(address); + } + self.reader.read8(address) + } + + fn read_rom(&mut self, bank: u8, address: u16) -> Option { + self.reader.read_rom(bank, address) + } +} + +fn decision_active(decision: &ChannelsDecision) -> Vec { + let mut active: Vec = gameboy::GAMEBOY_BUTTONS + .iter() + .zip(decision.buttons) + .filter(|(_, down)| *down) + .map(|(name, _)| (*name).to_owned()) + .collect(); + if let Some(channel) = &decision.macro_channel { + active.push(channel.clone()); + } + active +} + +fn intent_of(mask: u32) -> ControllerIntent { + let control = fly_session::legacy_env::control_of("p1", mask as u8); + ControllerIntent { + buttons: control.buttons, + axes: control.axes, + } +} + +impl Inner { + fn image_of(&self, inspection: &Inspection) -> DomainResult { + let typed = MemoryInspection::from_typed(&inspection.value) + .map_err(|e| DomainError::before(ErrorCode::IdentityMismatch, e.0))?; + if typed.rom_digest != self.cartridge.sha256_hex() { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "the inspection's romDigest is not the executor's cartridge", + )); + } + let bytes = inspection + .attachments + .get(MEMORY_ATTACHMENT) + .ok_or_else(|| { + DomainError::new( + ErrorCode::BufferInvalid, + format!( + "boundary {} has no {MEMORY_ATTACHMENT}", + inspection.boundary + ), + MutationCertainty::Unknown, + ) + })?; + MemoryImage::from_bytes(bytes).map_err(|e| { + DomainError::new( + ErrorCode::BufferInvalid, + e.to_string(), + MutationCertainty::Unknown, + ) + }) + } + + fn context(&self) -> ReadoutContext { + ReadoutContext { + boot: self.adapter.boot(), + bound: self + .macros + .as_ref() + .map(MacroLayer::bound_channels) + .unwrap_or_default(), + location: self + .adapter + .location() + .map(|(area, x, y)| Location { area, x, y }), + } + } + + fn contexts(&self) -> BTreeMap { + BTreeMap::from([(self.config.agent_id.clone(), self.context().to_typed())]) + } + + fn progress_value(&self) -> TypedValue { + let progress = self.adapter.progress(); + TypedValue::new( + progress_schema(), + json!({ + "rank": progress.rank, + "uniqueLocations": progress.unique_locations, + "rewardTotal": progress.reward_total, + "best": self.ratchet.state.best, + "recoveries": self.ratchet.state.recoveries, + }), + ) + .expect("progress fits the contract") + } + + fn ledgers(&self) -> String { + ledgers_of(&self.adapter, &self.ratchet, self.macros.as_ref()) + } + + fn observe(&mut self, image: &MemoryImage, ms: f64) -> Vec { + let cartridge = self.cartridge.clone(); + let Inner { + macros, + adapter, + uncaptured, + .. + } = self; + let mut reader = Watched { + reader: ImageReader::new(image, &cartridge), + uncaptured, + }; + match macros.as_mut() { + Some(layer) => layer.observe(&mut reader, &AdapterLedger(&*adapter), ms), + None => Vec::new(), + } + } + + fn event( + &mut self, + source_step: u64, + rule: &str, + ordinal: u32, + kind: &str, + payload: Value, + ) -> TaskEvent { + self.issued += 1; + TaskEvent { + id: event_id(&self.epoch, source_step, rule, ordinal), + kind_id: id(kind), + source_step, + agent_id: Some(self.config.agent_id.clone()), + payload: TypedValue::new(event_schema(), payload).expect("an event payload fits"), + } + } + + fn close(&mut self) { + if let Some(mut record) = self.open.take() { + record.ledgers = self.ledgers(); + self.records.push(record); + } + } +} + +struct TaskFace(PokeredTask); +struct ExecutorFace(PokeredTask); + +impl Task for TaskFace { + fn schema(&self) -> SchemaRef { + progress_schema() + } + + fn inspection_attachments(&self) -> Vec { + vec![MEMORY_ATTACHMENT.to_owned()] + } + + fn bootstrap( + &mut self, + initial: &Inspection, + bindings: &[PortBinding], + ) -> DomainResult { + let mut inner = self.0.lock(); + if bindings.len() != 1 + || bindings[0].agent_id != inner.config.agent_id + || bindings[0].port_id != inner.config.port_id + { + return Err(DomainError::before( + ErrorCode::IdentityMismatch, + "pokered-macros-v1 serves exactly one agent on its one port", + )); + } + let image = inner.image_of(initial)?; + // `Sim::boot` on a fresh start: the layer observes O[0] once, at the warm-up's end. The + // agent is initialized after this, but its warm-up is the profile's constant, so the + // brain time the legacy loop observes at is known: exactly `warmupMs`. + let ms = gameboy::WARMUP_MS as f64; + inner.ms = ms; + inner.observe(&image, ms); + inner.current = Some((initial.boundary, image)); + Ok(Bootstrap { + contexts: inner.contexts(), + progress: inner.progress_value(), + events: Vec::new(), + }) + } + + fn evaluate_transition( + &mut self, + scope: &Scope, + old: &Inspection, + new: &Inspection, + _applied_controls: &[PortControl], + ) -> DomainResult { + let mut inner = self.0.lock(); + match &inner.current { + Some((boundary, _)) if *boundary == old.boundary && old.boundary == scope.step => {} + _ => { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "the task evaluates the transition from the boundary it last observed", + )); + } + } + let image = inner.image_of(new)?; + let ms = inner.ms; + let k1 = scope.step + 1; + inner.evaluations += 1; + inner.last_source_step = k1; + + // `LegacyFrame::evaluate`: rewards from the frame just produced, then the scene, then the + // location (the agent's, from the context), then the rank. + let cartridge = inner.cartridge.clone(); + let rewards = { + let Inner { + adapter, + uncaptured, + .. + } = &mut *inner; + let mut reader = Watched { + reader: ImageReader::new(&image, &cartridge), + uncaptured, + }; + adapter.sample(&mut reader, ms) + }; + let abandoned = inner.observe(&image, ms); + let progress = inner.adapter.progress(); + + // `LegacyFrame::boundary`, the decision half: the ratchet captures on a safe frame above + // its best -- a slot save at `Ready(k+1)` -- and says whether to roll back. + let safe = inner.adapter.safe_for_snapshot(); + let nearer = inner + .macros + .as_ref() + .is_some_and(MacroLayer::nearer_the_objective); + let game_over = inner.adapter.game_over(); + let mut saved = false; + let recover = inner.ratchet.observe_with_progress( + safe, + u64::from(progress.rank), + progress.unique_locations as u64, + ms as u64, + game_over, + nearer, + || { + saved = true; + slot_marker() + }, + ); + + let mut outcome = AgentOutcome::default(); + let mut events = Vec::new(); + for (n, event) in rewards.iter().enumerate() { + let ordinal = n as u32; + let task_event = inner.event( + k1, + "reward", + ordinal, + "pokered.reward", + json!({"kind": event.kind, "label": event.label, "value": event.value}), + ); + outcome.rewards.push(Reward { + event_id: task_event.id.clone(), + rule_id: id(event.kind), + value: event.value, + }); + // `Stimulus.durationMs` is positive: an event that drives no pulse is a Reward alone, + // as the legacy `stimulate(0)` changes nothing. + if event.stimulation_ms > 0 { + outcome.stimulations.push(Stimulus { + id: task_event.id.clone(), + kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(), + duration_ms: f64::from(event.stimulation_ms), + }); + } + events.push(task_event); + } + let episode = recover.then(|| EpisodeRequest { + kind: EpisodeRequestKind::Rollback, + reason: id(if game_over { "game-over" } else { "stall" }), + outcome: RollbackRequest { + slot_id: SLOT.to_owned(), + trigger: if game_over { "game-over" } else { "stall" }.to_owned(), + } + .to_typed(), + }); + + if let Some(record) = inner.open.as_mut() { + record + .macro_events + .extend(abandoned.iter().map(|e| macro_json("evaluate", e))); + record.wram_digest = sha256_hex(&image.as_bytes()[0xc000..=0xdfff]); + record.rewards = rewards + .iter() + .map(|e| json!({"kind": e.kind, "value": e.value, "stimulationMs": e.stimulation_ms})) + .collect(); + record.rank = progress.rank; + record.saved = saved; + } + let next_contexts = inner.contexts(); + let progress_value = inner.progress_value(); + inner.current = Some((new.boundary, image)); + if !recover { + inner.close(); + } + Ok(Evaluation { + outcomes: BTreeMap::from([(inner.config.agent_id.clone(), outcome)]), + next_contexts, + progress: progress_value, + events, + episode, + slot_saves: if saved { vec![id(SLOT)] } else { Vec::new() }, + }) + } + + fn rollback( + &mut self, + scope: &Scope, + restored: &Inspection, + ) -> DomainResult { + let mut inner = self.0.lock(); + let image = inner.image_of(restored)?; + let ms = inner.ms; + inner.epoch = scope.epoch.clone(); + // `recover_game`'s task half: the adapter's transient observations; then the executor + // cancels and observes the restored game (`LegacyFrame::rollback`). + inner.adapter.clear_transient(); + let mut events = match inner.macros.as_mut() { + Some(layer) => layer.cancel(ms), + None => Vec::new(), + }; + events.extend(inner.observe(&image, ms)); + if let Some(record) = inner.open.as_mut() { + record.rolled_back = true; + record + .macro_events + .extend(events.iter().map(|e| macro_json("rollback", e))); + } + inner.current = Some((restored.boundary, image)); + inner.close(); + Ok(RollbackEvaluation { + next_contexts: inner.contexts(), + events: Vec::new(), + }) + } + + fn restored( + &mut self, + scope: &Scope, + restored: &Inspection, + clock: &RationalNs, + ) -> DomainResult>> { + let mut inner = self.0.lock(); + let image = inner.image_of(restored)?; + let ms = clock_ms(clock)?; + inner.epoch = scope.epoch.clone(); + inner.ms = ms; + // `Sim::boot` after a restore: a fresh layer (installed by `install_restore`) observes the + // restored game once, at the restored brain time, before the first frame decides. + inner.observe(&image, ms); + inner.current = Some((restored.boundary, image)); + Ok(Some(inner.contexts())) + } + + fn progress(&self) -> TypedValue { + self.0.lock().progress_value() + } + + fn evaluations(&self) -> u64 { + self.0.lock().evaluations + } + + fn capture(&self) -> DomainResult { + let (half, slot_filled) = self.0.task_half(); + PokeredTask::ledger_of(&half, slot_filled).map(|(typed, _)| typed) + } + + fn capture_attachments(&self) -> DomainResult>> { + let (half, slot_filled) = self.0.task_half(); + PokeredTask::ledger_of(&half, slot_filled).map(|(_, attachments)| attachments) + } + + fn validate_restore(&self, state: &TypedValue) -> DomainResult<()> { + self.validate_restore_with(state, &BTreeMap::new()) + } + + fn validate_restore_with( + &self, + state: &TypedValue, + attachments: &BTreeMap>, + ) -> DomainResult<()> { + let inner = self.0.lock(); + parse_ledger(&inner, state, attachments).map(|_| ()) + } + + fn install_restore(&mut self, epoch: &Id, state: &TypedValue) -> DomainResult<()> { + self.install_restore_with(epoch, state, &BTreeMap::new()) + } + + fn install_restore_with( + &mut self, + epoch: &Id, + state: &TypedValue, + attachments: &BTreeMap>, + ) -> DomainResult<()> { + let mut inner = self.0.lock(); + let (adapter, ratchet) = parse_ledger(&inner, state, attachments)?; + inner.adapter = adapter; + inner.ratchet = ratchet; + // `legacy-transient-reset`: a fresh executor, nothing running, empty ledgers. + inner.macros = fresh_layer(&inner.config, inner.palette_seed); + inner.current = None; + inner.open = None; + inner.epoch = epoch.clone(); + inner.evaluations = 0; + inner.issued = 0; + inner.last_source_step = 0; + Ok(()) + } + + fn rebase_ids(&self, _to_epoch: &Id) -> DomainResult> { + Err(DomainError::before( + ErrorCode::Unsupported, + "pokered-macros-v1 compares runs by FLY_TRACE, not by rebased event ids", + )) + } + + fn event_watermarks(&self) -> (u64, u64) { + let inner = self.0.lock(); + (inner.last_source_step, inner.issued) + } +} + +fn parse_ledger( + inner: &Inner, + state: &TypedValue, + attachments: &BTreeMap>, +) -> DomainResult<(PokemonRedReward, Ratchet)> { + if state.schema != ledger_schema() { + return Err(state_error( + "the captured ledger is not a pokered-macros-v1 ledger", + )); + } + let bytes = attachments + .get(REWARD_ATTACHMENT) + .ok_or_else(|| state_error("the ledger's reward attachment is missing"))?; + let declared = &state.value["reward"]; + if declared["digest"].as_str() != Some(digest_of_bytes(bytes).as_str()) + || declared["byteLength"].as_str() != Some(bytes.len().to_string().as_str()) + { + return Err(state_error( + "the reward attachment is not the one the ledger names", + )); + } + let reward: Value = serde_json::from_slice(bytes) + .map_err(|e| state_error(format!("the reward attachment is not JSON: {e}")))?; + let mut value = state.value.clone(); + value["reward"] = reward; + let half = TaskHalf::from_ledger(&value).map_err(state_error)?; + let slot_filled = state + .value + .get("slotFilled") + .and_then(Value::as_bool) + .ok_or_else(|| state_error("the ledger has no slotFilled"))?; + // `LegacyFrame::restore`'s order: the adapter (unless the file has none), then the ratchet + // bounded by the adapter's ladder. + let mut adapter = PokemonRedReward::new(); + if !half.reward.is_null() { + adapter + .import_state(&half.reward) + .map_err(|e| state_error(format!("adapter: {e}")))?; + } + let mut ratchet = Ratchet::with_policy(adapter.recovery_policy()); + ratchet + .import( + Some(half.ratchet), + slot_filled.then(slot_marker), + adapter.rank_ladder().len(), + ) + .map_err(|e| state_error(format!("ratchet: {e}")))?; + let _ = inner; + Ok((adapter, ratchet)) +} + +impl ActionExecutor for ExecutorFace { + fn apply( + &mut self, + scope: &Scope, + decision: &TypedValue, + current: &Inspection, + _progress: &TypedValue, + clock: &RationalNs, + ) -> DomainResult<(ControllerIntent, Vec)> { + let mut inner = self.0.lock(); + let decision = ChannelsDecision::from_typed(decision) + .map_err(|e| DomainError::before(ErrorCode::IdentityMismatch, e.0))?; + let image = match &inner.current { + Some((boundary, image)) if *boundary == current.boundary && *boundary == scope.step => { + image.clone() + } + _ => { + return Err(DomainError::before( + ErrorCode::InvalidPhase, + "the executor reads the boundary the task last observed", + )); + } + }; + // The clock is the brain time after Prepare, whole milliseconds (the legacy + // `network.ms`), which is what the macro layer's windows read. + let ms = clock_ms(clock)?; + inner.ms = ms; + let mut active = decision_active(&decision); + let bound = inner + .macros + .as_ref() + .map(MacroLayer::bound_channels) + .unwrap_or_default(); + if let Some(driver) = inner.driver.as_mut() { + driver.readout(ms, &bound, &mut active); + } + let raw = to_button_mask(&active); + let cartridge = inner.cartridge.clone(); + let (mask, events) = { + let Inner { + macros, + adapter, + uncaptured, + .. + } = &mut *inner; + match macros.as_mut() { + Some(layer) => { + let mut reader = Watched { + reader: ImageReader::new(&image, &cartridge), + uncaptured, + }; + let decided = + layer.decide(&active, raw, ms, &mut reader, &AdapterLedger(&*adapter)); + (decided.mask, decided.events) + } + None => (raw, Vec::new()), + } + }; + if inner.config.record { + inner.open = Some(TaskRecord { + boundary: scope.step, + decision: active, + bound, + mask, + macro_events: events.iter().map(|e| macro_json("execute", e)).collect(), + ..TaskRecord::default() + }); + } + Ok((intent_of(mask), Vec::new())) + } + + fn capture(&self) -> DomainResult { + TypedValue::new(executor_schema(), json!({"executor": gameboy::EXECUTOR_ID})) + .map_err(|e| DomainError::invalid(e.0)) + } + + fn validate_restore(&self, state: &TypedValue) -> DomainResult<()> { + if state.schema != executor_schema() + || state.value.get("executor").and_then(Value::as_str) != Some(gameboy::EXECUTOR_ID) + { + return Err(state_error( + "the captured executor is not pokered-macros-v1", + )); + } + Ok(()) + } + + /// Nothing to install: the executor's state is transient (`legacy-transient-reset`), and + /// the task's install already gave it a fresh layer. + fn install_restore(&mut self, state: &TypedValue) -> DomainResult<()> { + self.validate_restore(state) + } +} + +/// Brain time in ms from the executor's clock: exact whole nanoseconds of whole milliseconds. +pub fn clock_ms(clock: &RationalNs) -> DomainResult { + if clock.denominator != 1 || !clock.numerator.is_multiple_of(1_000_000) { + return Err(DomainError::invalid( + "the executor clock is not a whole number of milliseconds", + )); + } + Ok((clock.numerator / 1_000_000) as f64) +} diff --git a/services/flysim/crates/fly-legacy-session/src/trace.rs b/services/flysim/crates/fly-legacy-session/src/trace.rs new file mode 100644 index 0000000..9bb33cd --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/src/trace.rs @@ -0,0 +1,238 @@ +//! The session's own `FLY_TRACE`: the legacy loop's trace format (`flysim-legacy-frame-trace-v1`, +//! FND-01) written from a session-framework run, and the comparison of two of them. +//! +//! FND-01's trace is what the running service does, frame by frame, as digests. A new-runtime +//! session driven from the same checkpoint with the same admissions must write the same lines. So +//! the session trace is assembled from exactly what crosses the session's boundaries -- +//! `Agent.Prepare` (ticks, clock, remainder, decision), `Agent.Commit` (rates, spike bitset), the +//! executor's joypad batch, `Environment.Advance`'s view, the task's image-derived fields, and the +//! boundary actions -- and compared as JSON, with one declared exclusion: the decision is compared +//! as `gameboy-channels-v1` sees it ([`channels`]): the buttons down, and the first channel of the +//! context's bound set the decode holds. The decoder's list order is not in the decision schema, +//! and a macro channel the macro group still holds after its scene unbound it (the legacy `active` +//! can carry one) reaches nothing: the macro layer starts only a bound channel, and the joypad mask +//! is the buttons'. The mask, the macro events and every other field are compared as they are. + +use std::collections::BTreeSet; + +use serde_json::{Value, json}; + +use fly_session::coordinator::StepDetails; +use fly_session::fly_session_types::gameboy::GAMEBOY_BUTTONS; +use fly_session::legacy_parity::trace_rates_digest; +use fly_session::types::*; + +use crate::task::TaskRecord; + +pub const FORMAT: &str = "flysim-legacy-frame-trace-v1"; + +/// flysim's `remainder_ns`: the exact rational nanoseconds of the frame remainder. +fn remainder_json(remainder: &RationalNs) -> Value { + json!({"numerator": remainder.numerator.to_string(), "denominator": remainder.denominator.to_string()}) +} + +fn popcount(bytes: &[u8]) -> u64 { + bytes.iter().map(|b| u64::from(b.count_ones())).sum() +} + +/// One transition line of the session's trace, built from the coordinator's details of the +/// transition and the task's record of it. +pub fn line(details: &StepDetails, record: &TaskRecord) -> Result { + let [(agent_id, prepared)] = details.prepared.as_slice() else { + return Err("the legacy composition has exactly one agent".to_owned()); + }; + let commit = details + .commits + .iter() + .find(|(id, _)| id == agent_id) + .map(|(_, result)| result) + .ok_or("no commit for the agent")?; + let spikes = details + .commit_attachments + .iter() + .find(|(id, name, _)| { + id == agent_id && name == fly_session::legacy_agent::SPIKES_ATTACHMENT + }) + .map(|(_, _, bytes)| bytes) + .ok_or("the commit carried no spike bitset")?; + let step: u64 = details + .engine_frame + .as_deref() + .ok_or("O[k] has no engineFrame")? + .parse() + .map_err(|_| "engineFrame is not a U64")?; + let admissions: Vec = details + .admissions + .iter() + .map(|admission| match admission { + fly_session::coordinator::Admission::Stimulus { duration_ms, .. } => { + json!({"kind": "sugar", "durationMs": duration_ms}) + } + }) + .collect(); + let framebuffer = details + .view_digests + .iter() + .find(|(view, _)| view == "lcd") + .map(|(_, digest)| digest.clone()) + .ok_or("O[k+1] has no lcd view")?; + let boundary_actions: Vec = details + .boundary_actions + .iter() + .map(|action| { + json!({ + "kind": action.kind.as_str(), + "slotId": action.slot_id, + "stateDigest": action.state_digest, + }) + }) + .collect(); + Ok(json!({ + "behaviour": { + "step": step.to_string(), + "admissions": admissions, + "ticksAdvanced": prepared.ticks_advanced.to_string(), + "brainTicks": prepared.brain_ticks.to_string(), + "remainder": remainder_json(&prepared.remainder), + "ratesDigest": trace_rates_digest(&commit.telemetry)?, + "spikesDigest": sha256_hex(spikes), + "spikeCount": popcount(spikes), + "decision": record.decision, + "mask": record.mask, + "macroEvents": record.macro_events, + "framebufferDigest": framebuffer, + "wramDigest": record.wram_digest, + "rewards": record.rewards, + "rank": record.rank, + "acknowledgedBoundary": (step + 1).to_string(), + "boundaryActions": boundary_actions, + } + })) +} + +/// The decision as `gameboy-channels-v1` sees it, given the bound channels it was masked to: the +/// buttons down, and the first bound channel the active set holds (AGENT-01's rule). +pub fn channels(decision: &Value, bound: &[String]) -> (BTreeSet, Option) { + let active: Vec<&str> = decision + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + let buttons = active + .iter() + .filter(|name| GAMEBOY_BUTTONS.contains(name)) + .map(|name| (*name).to_owned()) + .collect(); + let macro_channel = bound + .iter() + .find(|channel| active.contains(&channel.as_str())) + .cloned(); + (buttons, macro_channel) +} + +/// Reads a trace file's transition lines (`behaviour` only), skipping the header and the start +/// boundary line. +pub fn behaviours(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!("header: {e}"))?; + if header["format"] != FORMAT { + return Err(format!("not {FORMAT}: {}", header["format"])); + } + let mut out = Vec::new(); + for line in lines { + let value: Value = serde_json::from_str(line).map_err(|e| format!("line: {e}"))?; + if let Some(behaviour) = value.get("behaviour") { + out.push(behaviour.clone()); + } + } + Ok(out) +} + +/// What a comparison found, for the report. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Agreement { + pub transitions: u64, + pub sugar: u64, + pub reward_pulses: u64, + pub rewards: u64, + pub reward_kinds: Vec, + pub macro_events: u64, + pub pressed: u64, + pub saves: u64, + pub rollbacks: u64, + pub spikes: u64, +} + +/// Every transition identical, field by field; the decision as [`channels`] of the session's bound +/// set for that transition. The first difference is the error, with both values. +pub fn compare( + legacy: &[Value], + session: &[Value], + bounds: &[Vec], +) -> Result { + if bounds.len() != session.len() { + return Err("one bound set per session transition".to_owned()); + } + if legacy.len() != session.len() { + return Err(format!( + "the legacy trace has {} transitions, the session's {}", + legacy.len(), + session.len() + )); + } + let mut agreement = Agreement::default(); + for (n, (a, b)) in legacy.iter().zip(session).enumerate() { + let (Some(a_map), Some(b_map)) = (a.as_object(), b.as_object()) else { + return Err(format!("transition {n}: not an object")); + }; + let keys: BTreeSet<&String> = a_map.keys().chain(b_map.keys()).collect(); + for key in keys { + let (x, y) = (&a[key.as_str()], &b[key.as_str()]); + let same = if key == "decision" { + channels(x, &bounds[n]) == channels(y, &bounds[n]) + } else { + x == y + }; + if !same { + return Err(format!( + "transition {n} (step {}) {key}:\n legacy {x}\n session {y}", + a["step"] + )); + } + } + agreement.transitions += 1; + for admission in a["admissions"].as_array().into_iter().flatten() { + match admission["kind"].as_str() { + Some("sugar") => agreement.sugar += 1, + Some("reward") => agreement.reward_pulses += 1, + _ => {} + } + } + for reward in a["rewards"].as_array().into_iter().flatten() { + agreement.rewards += 1; + if let Some(kind) = reward["kind"].as_str() + && !agreement.reward_kinds.iter().any(|k| k == kind) + { + agreement.reward_kinds.push(kind.to_owned()); + } + } + agreement.macro_events += a["macroEvents"].as_array().map_or(0, |v| v.len() as u64); + if a["mask"].as_u64().unwrap_or(0) != 0 { + agreement.pressed += 1; + } + for action in a["boundaryActions"].as_array().into_iter().flatten() { + match action["kind"].as_str() { + Some("save-slot") => agreement.saves += 1, + Some("rollback") => agreement.rollbacks += 1, + _ => {} + } + } + agreement.spikes += a["spikeCount"].as_u64().unwrap_or(0); + } + Ok(agreement) +} + +/// `GAMEBOY_BUTTONS`, re-exported for the decision reconstruction's tests. +pub const BUTTONS: [&str; 8] = GAMEBOY_BUTTONS; diff --git a/services/flysim/crates/fly-legacy-session/tests/ledger_size.rs b/services/flysim/crates/fly-legacy-session/tests/ledger_size.rs new file mode 100644 index 0000000..57538c2 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/ledger_size.rs @@ -0,0 +1,130 @@ +//! The task ledger is not bounded by the 32 KiB `TypedValue` limit (TASK-01 review B1). +//! +//! The adapter's lifetime ledger grows with play (42-46 KB on the live fly at rank 12-15). The +//! pokered-macros-v1 ledger keeps it as an attachment beside a small typed value, so a ledger of +//! any size captures, validates and installs, and a malformed one is an error, never a panic. +//! ROM-free: the cartridge is ENV-01's toy one, which the task never reads here. + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; + +use fly_legacy_session::task::{PokeredConfig, PokeredTask, REWARD_ATTACHMENT}; +use fly_session::fly_session_types::gameboy::ReadoutContext; +use fly_session::legacy_checkpoint::TaskHalf; +use fly_session::legacy_env_parity::toy_cart; +use fly_session::types::*; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flysim::snapshot::MacroMode; + +fn task() -> PokeredTask { + let rom = toy_cart::rom(0); + PokeredTask::new( + PokeredConfig { + agent_id: id("fly"), + port_id: id("p1"), + mode: MacroMode::Raw, + macro_channels: Vec::new(), + hold_ms: 0.0, + record: false, + }, + &rom, + &digest_of_bytes(&rom), + &id("e1"), + ) + .expect("the object") +} + +/// A real adapter state grown past 64 KB: thousands of walked tiles, as a long life has. +fn big_reward() -> Value { + let mut reward = PokemonRedReward::new().export_state(); + let tiles: Vec = (0..12_000) + .map(|n| json!(format!("{}:{}:{}", n % 200, n / 200 % 64, n / 12_800))) + .collect(); + reward["tiles"] = Value::Array(tiles); + reward +} + +#[test] +fn a_ledger_past_32_kib_captures_validates_and_installs() { + let reward = big_reward(); + let bytes = serde_json::to_vec(&reward).unwrap(); + assert!(bytes.len() > 64 * 1024, "{} bytes", bytes.len()); + // The adapter itself takes it, so it is a real ledger and not just a large JSON value. + PokemonRedReward::new() + .import_state(&reward) + .expect("an adapter state"); + + let half = TaskHalf { + reward, + ratchet: Default::default(), + }; + let (typed, attachments) = PokeredTask::ledger_of(&half, false).expect("any size"); + assert!( + typed.to_json().to_string().len() < 1024, + "the typed value stays small" + ); + assert_eq!(attachments[REWARD_ATTACHMENT], bytes); + + let object = task(); + let mut face = object.task(); + face.validate_restore_with(&typed, &attachments) + .expect("validates"); + face.install_restore_with(&id("e2"), &typed, &attachments) + .expect("installs"); + let (restored, slot) = object.task_half(); + assert!(!slot); + let mut direct = PokemonRedReward::new(); + direct.import_state(&half.reward).unwrap(); + assert_eq!( + restored.reward, + direct.export_state(), + "the installed adapter is the imported one" + ); + // And what it captures back is a ledger of the same kind, which installs again. + let (again, again_attachments) = (face.capture().unwrap(), face.capture_attachments().unwrap()); + assert!(again_attachments[REWARD_ATTACHMENT].len() > 32 * 1024); + face.validate_restore_with(&again, &again_attachments) + .expect("re-validates"); + + // The context preview reads it too. + let image = flybrain_gb::MemoryImage::zeroed(); + let context = object + .preview_context(&typed, &attachments, &image, 1_000.0) + .expect("previews"); + assert!(ReadoutContext::from_typed(&context).is_ok()); +} + +#[test] +fn a_bad_ledger_is_an_error_not_a_panic() { + let half = TaskHalf { + reward: big_reward(), + ratchet: Default::default(), + }; + let (typed, attachments) = PokeredTask::ledger_of(&half, false).unwrap(); + let face = task().task(); + for (what, attachments) in [ + ("missing", BTreeMap::new()), + ( + "another", + BTreeMap::from([(REWARD_ATTACHMENT.to_owned(), b"{}".to_vec())]), + ), + ( + "truncated", + BTreeMap::from([( + REWARD_ATTACHMENT.to_owned(), + attachments[REWARD_ATTACHMENT][..100].to_vec(), + )]), + ), + ] { + let err = face + .validate_restore_with(&typed, &attachments) + .unwrap_err(); + assert_eq!( + err.code, + ErrorCode::IncompatibleState, + "{what}: {}", + err.message + ); + } +} diff --git a/services/flysim/crates/fly-legacy-session/tests/palette_seed.rs b/services/flysim/crates/fly-legacy-session/tests/palette_seed.rs new file mode 100644 index 0000000..115f008 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/palette_seed.rs @@ -0,0 +1,79 @@ +//! The palette seed is never read (TASK-01 review N3). +//! +//! The legacy loop seeds the macro palette with the brain's RNG state after boot; a fresh session +//! start cannot see it and uses `PALETTE_SEED`. That is equivalent only while no macro reads its +//! generator. This holds it on the cartridge: two macro layers seeded differently, handed the same +//! decisions (the ROM tests' rotation driver) over the same frames, press the same buttons and +//! report the same events, frame by frame. A macro that ever draws from its generator breaks it +//! here rather than in a shadow run. +//! +//! ROM job: `FLY_ROM` and `FLY_DOOR_CHECKPOINT` (the operator's rom env script). + +use fly_legacy_session::composition::channels_and_hold; +use fly_legacy_session::driver::{DecisionDriver, RotationDriver}; +use flybrain_core::decoder::gameboy::to_button_mask; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator}; +use flysim::config::Config; +use flysim::macros::macro_layer; +use flysim::snapshot::MacroMode; + +#[test] +fn two_palette_seeds_press_the_same_buttons() { + let (Some(rom), Some(path)) = ( + std::env::var_os("FLY_ROM"), + std::env::var_os("FLY_DOOR_CHECKPOINT"), + ) else { + eprintln!("skipping: FLY_ROM or FLY_DOOR_CHECKPOINT is not set"); + return; + }; + let rom = std::fs::read(rom).expect("the cartridge"); + let checkpoint = flysim::store::load(std::path::Path::new(&path)).expect("FLYSIM01"); + let mut emulator = + Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).expect("binjgb"); + emulator + .import_state(&checkpoint.runtime.emulator) + .expect("the emulator state"); + let mut adapter = PokemonRedReward::new(); + adapter + .import_state(&checkpoint.runtime.reward) + .expect("the adapter state"); + let mut config = Config::default(); + config.loop_.game = "pokemon-red".to_owned(); + config.macros.mode = MacroMode::Macros; + let (_, hold_ms) = channels_and_hold(MacroMode::Macros); + let mut a = macro_layer(&config, hold_ms, 0).expect("a layer"); + let mut b = macro_layer(&config, hold_ms, 0xdead_beef).expect("a layer"); + let mut driver = RotationDriver::new(); + let mut ms = checkpoint.agent.network.ms; + let frames = std::env::var("FLY_TASK01_SEED_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(3000); + let mut macros = 0; + for frame in 0..frames { + assert_eq!( + a.bound_channels(), + b.bound_channels(), + "frame {frame}: bound" + ); + let mut active = Vec::new(); + driver.readout(ms, &a.bound_channels(), &mut active); + let raw = to_button_mask(&active); + let da = a.decide(&active, raw, ms, &mut emulator, &AdapterLedger(&adapter)); + let db = b.decide(&active, raw, ms, &mut emulator, &AdapterLedger(&adapter)); + assert_eq!(da.mask, db.mask, "frame {frame}: mask"); + assert_eq!(da.events, db.events, "frame {frame}: events"); + macros += da.events.iter().filter(|e| e.outcome.is_none()).count(); + emulator.set_buttons(da.mask as u8); + emulator.run_frame().expect("a frame"); + let _ = emulator.take_audio_u8(); + ms += 17.0; + let _ = adapter.sample(&mut emulator, ms); + let ea = a.observe(&mut emulator, &AdapterLedger(&adapter), ms); + let eb = b.observe(&mut emulator, &AdapterLedger(&adapter), ms); + assert_eq!(ea, eb, "frame {frame}: observe"); + } + assert!(macros > 10, "the driver started macros ({macros})"); + eprintln!("{frames} frames, {macros} macros started: two seeds, the same presses"); +} diff --git a/services/flysim/crates/fly-legacy-session/tests/rollback_sequence.rs b/services/flysim/crates/fly-legacy-session/tests/rollback_sequence.rs new file mode 100644 index 0000000..0a46beb --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/rollback_sequence.rs @@ -0,0 +1,537 @@ +//! The coordinator's boundary actions on the legacy workers, without a ROM: ENV-01's toy +//! cartridge, AGENT-01's toy connectome, and a scripted task that asks for a slot save at +//! boundary 3, a reward at 4 and a rollback onto the slot at 6. +//! +//! What it holds, in-process and as processes: +//! +//! - the rollback runs `Ready(e, 6) -> RollingBack(6) -> Ready(e', 6)`, in the policy's order +//! (`RestoreSlot`, the task's part, `Agent.Rollback`), and the session steps on in `e'`; +//! - the restored boundary is the saved one: the task reads O'[6]'s memory image and it is O[3]'s; +//! - the step details record the save's state digest and the rollback, and the trace carries them +//! as boundary actions, saves first; +//! - admitted sugar is cut into the next Prepare and reported applied at the boundary it committed. + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; + +use serde_json::json; + +use flybus::{Grants, Pattern, Policy, RouterConfig}; + +use fly_session::coordinator::{AdmissionEnd, AgentSlot, Coordinator}; +use fly_session::fly_session_types::extensions::ROLLBACK_POLICY; +use fly_session::fly_session_types::gameboy::{ + self, ChannelsDecision, ReadoutContext, RollbackRequest, +}; +use fly_session::fly_session_types::trace::BoundaryActionKind; +use fly_session::launcher::{ + ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT, + ThreadBudget, Via, +}; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_env::{BackendConfig, MEMORY_ATTACHMENT, STATE_FORMAT_ID}; +use fly_session::legacy_env_parity::toy_cart; +use fly_session::task::{ + ActionExecutor, Bootstrap, Evaluation, Inspection, RollbackEvaluation, Task, +}; +use fly_session::types::*; + +fn grants(f: impl FnOnce(&mut Grants)) -> Grants { + let mut g = Grants::default(); + f(&mut g); + g +} + +fn schema(name: &str) -> SchemaRef { + SchemaRef::new(name, 1, &digest_of_bytes(name.as_bytes())).unwrap() +} + +/// What the scripted task saw. +#[derive(Default)] +struct Seen { + /// Boundary -> the image digest the task read for it (the last reading wins). + images: BTreeMap, + restored: Option<(u64, String)>, +} + +struct Scripted { + agent: Id, + seen: Arc>, + evaluations: u64, +} + +fn context() -> TypedValue { + ReadoutContext { + boot: false, + bound: Vec::new(), + location: None, + } + .to_typed() +} + +fn image_digest(inspection: &Inspection) -> DomainResult { + let bytes = inspection + .attachments + .get(MEMORY_ATTACHMENT) + .ok_or_else(|| DomainError::invalid("no image"))?; + assert_eq!(bytes.len(), 65_536); + Ok(digest_of_bytes(bytes)) +} + +impl Task for Scripted { + fn schema(&self) -> SchemaRef { + schema("scripted.progress") + } + + fn inspection_attachments(&self) -> Vec { + vec![MEMORY_ATTACHMENT.to_owned()] + } + + fn bootstrap( + &mut self, + initial: &Inspection, + _bindings: &[PortBinding], + ) -> DomainResult { + let digest = image_digest(initial)?; + self.seen + .lock() + .unwrap() + .images + .insert(initial.boundary, digest); + Ok(Bootstrap { + contexts: BTreeMap::from([(self.agent.clone(), context())]), + progress: self.progress(), + events: Vec::new(), + }) + } + + fn evaluate_transition( + &mut self, + scope: &Scope, + old: &Inspection, + new: &Inspection, + _controls: &[PortControl], + ) -> DomainResult { + assert_eq!(old.boundary, scope.step, "O[k] is the old inspection"); + assert_eq!(new.boundary, scope.step + 1, "O[k+1] is the new one"); + self.evaluations += 1; + let k1 = scope.step + 1; + self.seen + .lock() + .unwrap() + .images + .insert(k1, image_digest(new)?); + let mut outcome = AgentOutcome::default(); + let mut events = Vec::new(); + if k1 == 4 { + let event = TaskEvent { + id: event_id(&scope.epoch, k1, "scripted", 0), + kind_id: id("scripted.reward"), + source_step: k1, + agent_id: Some(self.agent.clone()), + payload: TypedValue::new(schema("scripted.event"), json!({})).unwrap(), + }; + outcome.rewards.push(Reward { + event_id: event.id.clone(), + rule_id: id("scripted"), + value: 0.5, + }); + outcome.stimulations.push(Stimulus { + id: event.id.clone(), + kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(), + duration_ms: 100.0, + }); + events.push(event); + } + Ok(Evaluation { + outcomes: BTreeMap::from([(self.agent.clone(), outcome)]), + next_contexts: BTreeMap::from([(self.agent.clone(), context())]), + progress: self.progress(), + events, + episode: (k1 == 6).then(|| EpisodeRequest { + kind: EpisodeRequestKind::Rollback, + reason: id("stall"), + outcome: RollbackRequest { + slot_id: "best".into(), + trigger: "stall".into(), + } + .to_typed(), + }), + slot_saves: if k1 == 3 { + vec![id("best")] + } else { + Vec::new() + }, + }) + } + + fn rollback( + &mut self, + scope: &Scope, + restored: &Inspection, + ) -> DomainResult { + assert_eq!(restored.boundary, scope.step); + self.seen.lock().unwrap().restored = Some((restored.boundary, image_digest(restored)?)); + Ok(RollbackEvaluation { + next_contexts: BTreeMap::from([(self.agent.clone(), context())]), + events: Vec::new(), + }) + } + + fn progress(&self) -> TypedValue { + TypedValue::new( + schema("scripted.progress"), + json!({"evaluations": self.evaluations}), + ) + .unwrap() + } + + fn evaluations(&self) -> u64 { + self.evaluations + } + + fn capture(&self) -> DomainResult { + Ok(self.progress()) + } + + fn validate_restore(&self, _state: &TypedValue) -> DomainResult<()> { + Ok(()) + } + + fn install_restore(&mut self, _epoch: &Id, _state: &TypedValue) -> DomainResult<()> { + Ok(()) + } + + fn rebase_ids(&self, _to_epoch: &Id) -> DomainResult> { + Ok(BTreeMap::new()) + } + + fn event_watermarks(&self) -> (u64, u64) { + (0, 0) + } +} + +/// The joypad the decision's buttons ask for. +struct Buttons; + +impl ActionExecutor for Buttons { + fn apply( + &mut self, + _scope: &Scope, + decision: &TypedValue, + _current: &Inspection, + _progress: &TypedValue, + _clock: &RationalNs, + ) -> DomainResult<(ControllerIntent, Vec)> { + let decision = + ChannelsDecision::from_typed(decision).map_err(|e| DomainError::invalid(e.0))?; + let control = fly_session::legacy_env::control_of("p1", decision.mask()); + Ok(( + ControllerIntent { + buttons: control.buttons, + axes: control.axes, + }, + Vec::new(), + )) + } + + fn capture(&self) -> DomainResult { + Ok(TypedValue::new(schema("buttons"), json!({})).unwrap()) + } + + fn validate_restore(&self, _state: &TypedValue) -> DomainResult<()> { + Ok(()) + } + + fn install_restore(&mut self, _state: &TypedValue) -> DomainResult<()> { + Ok(()) + } +} + +async fn run(mode: ExecutionMode) { + let root = tempfile::tempdir().unwrap(); + let rom = toy_cart::rom(0); + let rom_path = root.path().join("toy.gb"); + std::fs::write(&rom_path, &rom).unwrap(); + let store = root.path().join("store"); + let sockets = root.path().join("sockets"); + std::fs::create_dir_all(&sockets).unwrap(); + let policy = Policy::closed() + .client( + "coordinator", + grants(|g| { + g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]; + g.publish = vec![Pattern::prefix("session.")]; + g.manage_topics = vec![Pattern::prefix("session.")]; + g.register = vec![Pattern::prefix("session.")]; + }), + ) + .client( + SUPERVISOR_CLIENT, + grants(|g| g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]), + ) + .client( + "world", + grants(|g| g.register = vec![Pattern::exact("env.world")]), + ) + .client( + "fly", + grants(|g| g.register = vec![Pattern::exact("agent.fly")]), + ); + let mut config = RouterConfig::new(&store); + config.policy = policy; + let router = flybus::Router::new(config).unwrap(); + let mut launcher = Launcher::start( + router, + mode, + Via::Unix, + &store, + &sockets, + ThreadBudget::new(3, 1).unwrap(), + ) + .await + .unwrap(); + let mut backend = BackendConfig::legacy(&digest_of_bytes(&rom)); + backend.slots = vec![id("best")]; + launcher + .launch_legacy_environment(LegacyEnvironmentLaunch { + session_id: id("s"), + worker_id: id("world"), + incarnation_id: id("world-1"), + worker_threads: 1, + rom_path, + backend: backend.clone(), + client_id: "world".into(), + service: "env.world".into(), + }) + .await + .unwrap(); + launcher + .launch_legacy_agent(LegacyAgentLaunch { + session_id: id("s"), + agent_id: id("fly"), + port_id: id("p1"), + incarnation_id: id("fly-1"), + worker_threads: 1, + dataset_dir: fly_session::legacy_parity::toy::dir(), + profile: LegacyProfileKind::Toy, + macro_channels: Vec::new(), + client_id: "fly".into(), + service: "agent.fly".into(), + }) + .await + .unwrap(); + let mut slot = AgentSlot::new( + launcher.worker(&id("fly")).unwrap().worker_ref(), + id("fly"), + id("p1"), + LegacyProfileKind::Toy.profile().asset, + fly_session::legacy_parity::LEGACY_SEED, + ); + slot.model_version = gameboy::KERNEL_VERSION.into(); + slot.plasticity_version = gameboy::PLASTICITY_VERSION.into(); + let seen = Arc::new(Mutex::new(Seen::default())); + let task = Scripted { + agent: id("fly"), + seen: seen.clone(), + evaluations: 0, + }; + let executors: BTreeMap> = + BTreeMap::from([(id("fly"), Box::new(Buttons) as Box)]); + let mut coordinator = Coordinator::new( + launcher.connect("coordinator").await.unwrap(), + id("s"), + id("e1"), + id("ep1"), + launcher.worker(&id("world")).unwrap().worker_ref(), + vec![slot], + Box::new(task), + executors, + ); + coordinator.set_environment_config( + backend.asset_ref(), + fly_session::environment::synthetic_asset("scripted", "scripted-v1"), + ); + coordinator.set_media( + &[gameboy::VIEW_ID], + &[fly_session::legacy_env::AUDIO_STREAM_ID], + ); + coordinator.set_state_format(STATE_FORMAT_ID); + coordinator.set_decision_schema(gameboy::CHANNELS.schema_ref()); + coordinator + .declare_rollback_policy(ROLLBACK_POLICY) + .unwrap(); + coordinator.record_details(true); + coordinator + .bootstrap() + .await + .unwrap_or_else(|e| panic!("bootstrap: {}", e.error.message)); + coordinator.disable_pacing(); + let admissions = coordinator.admissions(); + assert_eq!( + admissions.stimulus_remaining_ms(&id("fly")), + None, + "no commit yet" + ); + + let mut actions = Vec::new(); + for k in 0..9u64 { + if k == 2 { + // Two sugars before the next commit: the legacy drain admits the first and refuses + // the second (its pulse is already active), and so does the session's admission. + let mut legacy = flysim::ratelimit::RateLimiter::new(6); + let mut remaining = admissions + .stimulus_remaining_ms(&id("fly")) + .expect("committed"); + let legacy_answers: Vec<_> = [300.0, 250.0] + .iter() + .map(|duration: &f64| { + let answer = legacy.admit(1_000, remaining); + if answer.is_ok() { + remaining = remaining.max(*duration); + } + answer + }) + .collect(); + let mut sugar = + fly_legacy_session::admission::LegacyAdmission::new(admissions.clone(), id("fly")); + let first = sugar.sugar(1_000, Some(300.0)).map(|(_, d)| d); + let second = sugar.sugar(1_000, Some(250.0)).map(|(_, d)| d); + assert_eq!(first, Ok(300.0)); + assert_eq!(legacy_answers[0], Ok(())); + assert_eq!( + second.err(), + legacy_answers[1].err(), + "the second is refused as legacy refuses it" + ); + assert_eq!(admissions.queued(), 1); + } + let report = coordinator.step().await.unwrap_or_else(|e| { + panic!( + "{} step {k}: {} ({})", + mode.label(), + e.error.message, + e.detail + ) + }); + assert_eq!(report.boundary, k + 1); + assert!( + !report.paused && !report.terminal, + "a rollback is not an episode end" + ); + let details = coordinator.take_details().unwrap(); + if k == 2 { + assert_eq!( + details.admissions.len(), + 1, + "the sugar is cut into Prepare(2)" + ); + } + for action in &details.boundary_actions { + actions.push((k + 1, action.kind, action.state_digest.clone())); + } + if k + 1 == 6 { + let rollback = details.rollback.as_ref().expect("the rollback's details"); + assert_eq!(rollback.epoch, id("e1.rb1")); + assert_eq!(rollback.observation.boundary, 6); + assert!( + rollback.observation.audio.is_empty(), + "a restore plays no interval" + ); + assert_eq!(rollback.agents.len(), 1); + } + } + assert_eq!( + coordinator.epoch(), + &id("e1.rb1"), + "the session steps on in the new epoch" + ); + assert_eq!(actions.len(), 2); + assert_eq!( + (actions[0].0, actions[0].1), + (3, BoundaryActionKind::SaveSlot) + ); + assert!( + actions[0].2.is_some(), + "a save records the saved state's digest" + ); + assert_eq!( + (actions[1].0, actions[1].1, actions[1].2.clone()), + (6, BoundaryActionKind::Rollback, None) + ); + let phases: Vec = coordinator + .trace + .phases + .iter() + .map(|p| format!("{}->{}", p.from, p.to)) + .collect(); + assert!( + phases.contains(&"Ready(6)->RollingBack(6)".to_owned()), + "{phases:?}" + ); + assert!( + phases.contains(&"RollingBack(6)->Ready(6)".to_owned()), + "{phases:?}" + ); + let traced: Vec<(u64, usize)> = coordinator + .trace + .transitions + .iter() + .map(|t| { + ( + t.behaviour.acknowledged_boundary, + t.behaviour.boundary_actions.len(), + ) + }) + .filter(|(_, n)| *n > 0) + .collect(); + assert_eq!( + traced, + vec![(3, 1), (6, 1)], + "the trace carries the boundary actions" + ); + let seen = std::mem::take(&mut *seen.lock().unwrap()); + let (boundary, restored) = seen.restored.clone().expect("the task rolled back"); + assert_eq!(boundary, 6); + assert_eq!( + restored, seen.images[&3], + "O'[6] is the world saved at boundary 3" + ); + assert_ne!( + restored, seen.images[&6], + "and not the one the rollback threw away" + ); + let ended = admissions.take_ended(); + assert_eq!(ended.len(), 1); + assert_eq!(ended[0].1, AdmissionEnd::Applied { boundary: 3 }); + assert_eq!( + admissions.pending_stimulus_ms(&id("fly")), + None, + "nothing pending once committed" + ); + assert!(admissions.stimulus_remaining_ms(&id("fly")).is_some()); + let audit = coordinator.audit.join(" "); + for needle in [ + "save-slot:best@3", + "restore-slot:best@6", + "agent-rollback:fly@6", + "rolled-back:best@6", + ] { + assert!(audit.contains(needle), "{needle} in {audit}"); + } + launcher.reap_all(&id("done")).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_save_then_a_rollback_in_process() { + run(ExecutionMode::InProcess).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_save_then_a_rollback_as_processes() { + if !fly_session::launcher::default_worker_program().is_file() { + eprintln!("process mode skipped: no worker program"); + return; + } + run(ExecutionMode::Process).await; +} diff --git a/services/flysim/crates/fly-legacy-session/tests/save_handoff.rs b/services/flysim/crates/fly-legacy-session/tests/save_handoff.rs new file mode 100644 index 0000000..859c39d --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/save_handoff.rs @@ -0,0 +1,126 @@ +//! TASK-01 round-2 review notes R2-1 and R2-2 on the session's save hand-off. The toy raw +//! composition from power-on (`FLY_ROM`; a build without it skips): +//! +//! - R2-1: a save begun at boundary k reaches the writer even when the step after it fails, and +//! `flush_captures` hands it over while the loop idles (a pause), as the legacy loop's writer +//! thread has it from the boundary on. +//! - R2-2: `completed_saves` reports every queued save's outcome, a failed one beside the rest. + +use std::path::PathBuf; + +use fly_legacy_session::composition::{ + LegacyConfig, LegacySession, StoreConfig, +}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_checkpoint::SaveKind; +use fly_session::legacy_parity; +use fly_session::types::id; +use flysim::snapshot::MacroMode; + +async fn session(root: &std::path::Path) -> Option<(LegacySession, StoreConfig)> { + let Some(rom_path) = std::env::var_os("FLY_ROM").map(PathBuf::from) else { + eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)"); + return None; + }; + let config = LegacyConfig { + mode: ExecutionMode::InProcess, + rom_path, + dataset_dir: legacy_parity::toy::dir(), + profile: LegacyProfileKind::Toy, + macro_mode: MacroMode::Raw, + agent_id: id("fly"), + agent_threads: 1, + record: true, + }; + let mut session = LegacySession::start(&root.join("run"), config) + .await + .expect("the session starts"); + session.bootstrap().await.expect("Ready(0)"); + let store = StoreConfig { + hot_dir: root.join("hot"), + durable_dir: root.join("durable"), + keep_generations: 4, + // Saves only when asked. + hot_seconds: 1e9, + checkpoint_seconds: 1e9, + speed: 1.0, + }; + session.attach_store(&store).expect("the store attaches"); + Some((session, store)) +} + +/// One step, then the interval save it began (the first boundary is due for a durable one) +/// written and collected, so a test starts with nothing queued. +async fn warm_up(session: &mut LegacySession) { + session.advance().await.expect("a step"); + session.flush_captures().await.expect("the flush"); + for outcome in session.completed_saves(true).await { + outcome.expect("the first save"); + } +} + +fn files_in(dir: &std::path::Path) -> usize { + std::fs::read_dir(dir) + .map(|entries| entries.filter_map(Result::ok).count()) + .unwrap_or(0) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_begun_save_reaches_the_writer_when_the_next_step_fails() { + let root = tempfile::tempdir().expect("tmp"); + let Some((mut session, _)) = session(root.path()).await else { return }; + warm_up(&mut session).await; + for _ in 0..2 { + session.advance().await.expect("a step"); + } + session.begin_save(SaveKind::Hot).await.expect("a capture begins"); + // The next transition fails at its commit. + session.coordinator.injections.at_step = 3; + session.coordinator.injections.undeclared_stimulus = true; + let error = session.advance().await.err().expect("the step fails"); + assert!(error.starts_with("step ("), "{error}"); + let outcomes = session.completed_saves(true).await; + assert_eq!(outcomes.len(), 1, "the save begun before the failed step was written"); + let report = outcomes.into_iter().next().unwrap().expect("and it committed"); + assert!(!report.durable); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_pause_flushes_the_begun_save() { + let root = tempfile::tempdir().expect("tmp"); + let Some((mut session, store)) = session(root.path()).await else { return }; + warm_up(&mut session).await; + session.begin_save(SaveKind::Hot).await.expect("a capture begins"); + let before = files_in(&store.hot_dir); + let queued = session.flush_captures().await.expect("the flush"); + assert_eq!(queued.len(), 1); + let outcomes = session.completed_saves(true).await; + assert_eq!(outcomes.len(), 1); + assert!(outcomes[0].is_ok()); + assert!(files_in(&store.hot_dir) > before, "the hot generation is on disk"); + assert!( + session.flush_captures().await.expect("a second flush").is_empty(), + "nothing is held twice" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn every_save_outcome_is_reported_after_a_failure() { + let root = tempfile::tempdir().expect("tmp"); + let Some((mut session, store)) = session(root.path()).await else { return }; + warm_up(&mut session).await; + // The store's hot directory goes away under the writer: every save after it fails. The + // first failure must not hide the outcomes behind it. + std::fs::remove_dir_all(&store.hot_dir).expect("remove hot"); + std::fs::write(&store.hot_dir, b"not a directory").expect("block hot"); + let mut expected = 0; + for _ in 0..3 { + session.begin_save(SaveKind::Hot).await.expect("begin"); + session.flush_captures().await.expect("flush"); + expected += 1; + } + let outcomes = session.completed_saves(true).await; + assert_eq!(outcomes.len(), expected, "one outcome per queued save: {outcomes:?}"); + assert!(outcomes.iter().all(Result::is_err), "the writes failed: {outcomes:?}"); +} diff --git a/services/flysim/crates/fly-legacy-session/tests/session_trace.rs b/services/flysim/crates/fly-legacy-session/tests/session_trace.rs new file mode 100644 index 0000000..7eb09bf --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/session_trace.rs @@ -0,0 +1,823 @@ +//! TASK-01's pre-shadow proof: a whole new-runtime session -- the legacy agent worker (AGENT-01), +//! the legacy environment worker (ENV-01) and the `pokered-macros-v1` task and executor in the +//! coordinator -- reproduces the legacy loop's `FLY_TRACE` (FND-01) frame by frame: ticks, clock, +//! remainder, rates, spikes, decision, joypad mask, macro events, frame, work RAM, rewards, rank, +//! slot saves and rollbacks. Where the legacy side is a host run in this process, the ledgers +//! (adapter, ratchet, executor) are compared after every boundary too. +//! +//! Every run is an explicit ROM job (the operator's rom env script, never a download): +//! +//! - `toy_raw_from_power_on` (`FLY_ROM`): the committed toy connectome in raw mode from power-on, +//! with sugar admitted through the coordinator's admission queue. +//! - `fafb_service_trace_checkpoints` (`FLY_TASK01_FAFB=1`, `FLY_ENV01_TRACE_DIR`, +//! `FLY_DOOR_CHECKPOINT`): the checkpoints of the service's own traces (the FND-01 review's +//! `rollback`, `climb` and `r58`: a ratchet rollback, a slot save, two real rewards), for each +//! trace's length, against today's legacy loop; the session imported from the same FLYSIM01 +//! files. `FLY_TASK01_TRACE_LIMIT` caps each. +//! - `fafb_reward_segments` (`FLY_TASK01_FAFB=1`): host runs of `LegacyFrame` from stream +//! checkpoints, with sugar, in two arms. The brain arm: the adapter ledger thinned so rewards +//! fire where the fly already is (new area, exits, new ground, wild wins). The driver arm: the +//! brain ticks and decodes as always but the executor is handed the ROM tests' rotation driver's +//! decision (`fly_legacy_session::driver`), which walks, talks, fights and picks up, so real +//! rewards reach `Agent.Commit`. `FLY_TASK01_SEGMENTS` picks the checkpoints (`name=path,...`), +//! `FLY_TASK01_FRAMES` the length. +//! +//! Execution modes: in-process, then process (the workspace's `fly-session` binary); a build +//! without it skips process mode and says so. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use serde_json::Value; + +use fly_legacy_session::admission::LegacyAdmission; +use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold}; +use fly_legacy_session::driver::{DecisionDriver, RotationDriver}; +use fly_legacy_session::task::ledgers_of; +use fly_legacy_session::trace::{self, Agreement}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity; +use fly_session::types::id; +use flybrain_core::agent::{AgentConfig, NeuralAgent}; +use flybrain_core::dataset::{BrainDataset, load_brain_dataset_from_dir}; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flybrain_gb::adapter::GameAdapter; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flybrain_gb::ratchet::Ratchet; +use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator}; +use flysim::config::Config; +use flysim::frame::{LegacyFrame, Parts}; +use flysim::macros::macro_layer; +use flysim::snapshot::MacroMode; +use flysim::trace::FrameTrace; + +fn rom_path() -> Option { + match std::env::var_os("FLY_ROM") { + Some(path) => Some(PathBuf::from(path)), + None => { + eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)"); + None + } + } +} + +fn fafb() -> Option { + if std::env::var_os("FLY_TASK01_FAFB").is_none() { + eprintln!("skipping: FLY_TASK01_FAFB is not set"); + return None; + } + let dir = legacy_parity::fafb_dir(); + if dir.is_none() { + eprintln!("skipping: data/fafb-v783 is not present in this checkout"); + } + dir +} + +fn env_usize(name: &str, default: usize) -> usize { + std::env::var(name) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +fn modes() -> Vec { + let mut modes = vec![ExecutionMode::InProcess]; + 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 {}", + program.display() + ); + } + modes +} + +/// What each frame admits at its top, in admission order, and whether the rotation driver hands +/// the executor its decisions. +#[derive(Clone, Debug, Default)] +struct Inputs { + /// `(frame index from 1, duration ms)`. + sugar: Vec<(usize, f64)>, + driver: bool, +} + +/// The legacy loop's one look into a decision: the driver's, when the run has one. +struct Driven(Option); + +impl flysim::frame::FrameObserver for Driven { + fn readout(&mut self, ms: f64, bound: Option<&[String]>, active: &mut Vec) { + if let Some(driver) = self.0.as_mut() { + driver.readout(ms, bound.unwrap_or(&[]), active); + } + } +} + +/// How a run starts. +#[derive(Clone)] +enum Start { + PowerOn, + /// A FLYSIM01 file. + Checkpoint(Vec), +} + +/// The run's `FLY_TRACE` behaviours and, when it has them, the ledgers after every boundary. +struct Run { + behaviours: Vec, + ledgers: Vec, + /// The bound set of each transition's decision (session runs only). + bounds: Vec>, +} + +fn decoder_hold(mode: MacroMode) -> (Vec<&'static str>, f64) { + let channels = if mode.dealt() { + flybrain_gb::macro_channels("pokemon-red") + } else { + Vec::new() + }; + let (_, hold) = channels_and_hold(mode); + (channels, hold) +} + +/// The legacy loop in this process: `LegacyFrame` with `FLY_TRACE` on, admitting the inputs at +/// the top of each frame as the service's command drain does, the ledgers read after each +/// boundary. +fn run_legacy( + rom: &[u8], + data: &Arc, + start: &Start, + mode: MacroMode, + frames: usize, + inputs: &Inputs, + trace_path: &Path, +) -> Run { + let mut emulator = + Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).expect("binjgb"); + 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_owned(); + config.macros.mode = mode; + let (channels, hold_ms) = decoder_hold(mode); + let mut agent_config = AgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels)); + agent_config.warmup_ms = config.loop_.warmup_ms; + let mut agent = NeuralAgent::new(Arc::clone(data), agent_config).expect("an agent"); + let mut frame = + LegacyFrame::new().with_trace(Some(FrameTrace::create(trace_path).expect("a trace"))); + match start { + Start::PowerOn => { + frame + .initialize(&mut emulator, &mut agent) + .expect("the first frame and the warm-up"); + } + Start::Checkpoint(bytes) => { + let checkpoint = flysim::store::decode(bytes).expect("FLYSIM01"); + frame + .restore( + &mut Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: None, + }, + &checkpoint, + ) + .expect("the checkpoint restores"); + } + } + let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32); + if let Some(layer) = macros.as_mut() { + let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms); + } + let mut ledgers = Vec::new(); + let mut observer = Driven(inputs.driver.then(RotationDriver::new)); + for k in 1..=frames { + // The command drain: the sugar admitted for this frame, in admission order. + for (_, duration) in inputs.sugar.iter().filter(|(at, _)| *at == k) { + agent.network.stimulate(*duration); + if let Some(trace) = frame.trace_mut() { + trace.sugar(*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 observer) + .expect("a frame"); + frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .expect("the boundary"); + ledgers.push(ledgers_of(&adapter, &ratchet, macros.as_ref())); + } + frame.finish_trace(); + drop(frame); + let text = std::fs::read_to_string(trace_path).expect("the trace reads back"); + Run { + behaviours: trace::behaviours(&text).expect("a FLY_TRACE"), + ledgers, + bounds: Vec::new(), + } +} + +/// The same run on the session framework. +#[allow(clippy::too_many_arguments)] +async fn run_session( + mode: ExecutionMode, + rom_path: &Path, + dataset_dir: &Path, + profile: LegacyProfileKind, + macro_mode: MacroMode, + start: &Start, + frames: usize, + inputs: &Inputs, +) -> Run { + let root = tempfile::tempdir().expect("tmp"); + let config = LegacyConfig { + mode, + rom_path: rom_path.to_owned(), + dataset_dir: dataset_dir.to_owned(), + profile, + macro_mode, + agent_id: id("fly"), + agent_threads: 1, + record: true, + }; + let mut session = LegacySession::start(root.path(), config) + .await + .unwrap_or_else(|e| panic!("the session starts: {e}")); + if inputs.driver { + session.task.set_driver(Box::new(RotationDriver::new())); + } + session + .bootstrap() + .await + .unwrap_or_else(|e| panic!("Ready(0): {e}")); + if let Start::Checkpoint(bytes) = start { + session + .import_flysim01(bytes, &id("e2")) + .await + .unwrap_or_else(|e| panic!("the FLYSIM01 import: {e}")); + } + let mut admission = LegacyAdmission::new(session.coordinator.admissions(), id("fly")); + assert!( + admission.reward(1.0).is_err(), + "the operator reward pulse is refused" + ); + let mut behaviours = Vec::new(); + let mut ledgers = Vec::new(); + let mut bounds = Vec::new(); + for k in 1..=frames { + for (_, duration) in inputs.sugar.iter().filter(|(at, _)| *at == k) { + admission.replay_sugar(*duration); + } + let step = session + .step() + .await + .unwrap_or_else(|e| panic!("{} frame {k}: {e}", mode.label())); + let details = step.details.expect("details are recorded"); + let [record] = step.records.as_slice() else { + panic!("frame {k}: {} task records", step.records.len()); + }; + behaviours.push( + trace::line(&details, record).unwrap_or_else(|e| panic!("frame {k}: {e}"))["behaviour"] + .clone(), + ); + ledgers.push(record.ledgers.clone()); + bounds.push(record.bound.clone()); + } + let ended = session.coordinator.admissions().take_ended(); + assert_eq!( + ended.len(), + inputs.sugar.iter().filter(|(k, _)| *k <= frames).count(), + "every admission ended" + ); + assert!( + ended + .iter() + .all(|(_, end)| matches!(end, fly_session::coordinator::AdmissionEnd::Applied { .. })), + "and every one was applied" + ); + let uncaptured = session.task.uncaptured_reads(); + assert!( + uncaptured.is_empty(), + "the engine read addresses the image does not capture: {:04x?}", + uncaptured + ); + session.stop().await; + Run { + behaviours, + ledgers, + bounds, + } +} + +fn report(what: &str, agreement: &Agreement, elapsed: std::time::Duration) { + eprintln!( + "{what} ({elapsed:?}): {} transitions identical ({} sugar, {} rewards {:?}, \ + {} macro events, {} pressed, {} slot saves, {} rollbacks, {} spikes)", + agreement.transitions, + agreement.sugar, + agreement.rewards, + agreement.reward_kinds, + agreement.macro_events, + agreement.pressed, + agreement.saves, + agreement.rollbacks, + agreement.spikes + ); +} + +fn compare_ledgers(legacy: &[String], session: &[String]) { + assert_eq!(legacy.len(), session.len()); + for (k, (a, b)) in legacy.iter().zip(session).enumerate() { + assert_eq!(a, b, "the ledgers after frame {}", k + 1); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn toy_raw_from_power_on() { + let Some(rom_path) = rom_path() else { return }; + let rom = std::fs::read(&rom_path).expect("the cartridge"); + let data = Arc::new(load_brain_dataset_from_dir(legacy_parity::toy::dir()).expect("the toy")); + let frames = env_usize("FLY_TASK01_TOY_FRAMES", 600); + let inputs = Inputs { + sugar: vec![(40, 300.0), (frames / 2, 500.0)], + driver: false, + }; + let dir = tempfile::tempdir().expect("tmp"); + let legacy = run_legacy( + &rom, + &data, + &Start::PowerOn, + MacroMode::Raw, + frames, + &inputs, + &dir.path().join("trace.jsonl"), + ); + for mode in modes() { + let started = std::time::Instant::now(); + let session = run_session( + mode, + &rom_path, + &legacy_parity::toy::dir(), + LegacyProfileKind::Toy, + MacroMode::Raw, + &Start::PowerOn, + frames, + &inputs, + ) + .await; + let agreement = trace::compare(&legacy.behaviours, &session.behaviours, &session.bounds) + .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + compare_ledgers(&legacy.ledgers, &session.ledgers); + assert_eq!(agreement.sugar, 2); + report( + &format!("toy raw, {}", mode.label()), + &agreement, + started.elapsed(), + ); + } +} + +/// The checkpoints of the service's own traces (the FND-01 review's `rollback` -- a ratchet +/// rollback on the first boundary, a real `talk` reward -- `climb` -- a ratchet slot save -- and +/// `r58` -- a real `talk` reward -- with their start checkpoints). +/// +/// Those traces were recorded by the service as it stood on 2026-09-23. The macro engine has +/// changed since (loop-review rows 59 to 67), so from some frame on they are not what today's +/// engine does. The reference is therefore FND-01's harness at this tree -- `LegacyFrame` with +/// `FLY_TRACE` on, which FND-01 proved byte-identical to the service's loop -- run here from the +/// same checkpoint for the trace's length; the session must match it frame by frame, ledgers +/// included. How far the recorded service trace agrees with today's legacy loop is reported, not +/// asserted. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fafb_service_trace_checkpoints() { + let Some(rom_path) = rom_path() else { return }; + let Some(dataset) = fafb() else { return }; + let Some(dir) = std::env::var_os("FLY_ENV01_TRACE_DIR").map(PathBuf::from) else { + eprintln!("skipping: FLY_ENV01_TRACE_DIR is not set"); + return; + }; + let rom = std::fs::read(&rom_path).expect("the cartridge"); + let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset")); + let limit = env_usize("FLY_TASK01_TRACE_LIMIT", usize::MAX); + let names: Vec = std::env::var("FLY_TASK01_TRACES") + .map(|v| v.split(',').map(str::to_owned).collect()) + .unwrap_or_else(|_| vec!["rollback".into(), "climb".into(), "r58".into()]); + for name in names { + let checkpoint = if name == "r58" { + std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from) + } else { + Some(dir.join(format!("{name}.checkpoint"))) + }; + let Some(checkpoint) = checkpoint.filter(|c| c.is_file()) else { + eprintln!("skipping {name}: no checkpoint"); + continue; + }; + let text = + std::fs::read_to_string(dir.join(format!("{name}.trace.jsonl"))).expect("the trace"); + let mut service = trace::behaviours(&text).expect("a FLY_TRACE"); + service.truncate(limit); + let frames = service.len(); + let bytes = std::fs::read(&checkpoint).expect("the checkpoint"); + let start = Start::Checkpoint(bytes); + let tmp = tempfile::tempdir().expect("tmp"); + let started = std::time::Instant::now(); + let legacy = run_legacy( + &rom, + &data, + &start, + MacroMode::Macros, + frames, + &Inputs::default(), + &tmp.path().join("trace.jsonl"), + ); + let agreed = legacy + .behaviours + .iter() + .zip(&service) + .take_while(|(today, recorded)| today == recorded) + .count(); + eprintln!( + "legacy loop {name}: {frames} frames in {:?}; the recorded service trace agrees with \ + today's loop for its first {agreed} transitions", + started.elapsed() + ); + for mode in modes() { + let started = std::time::Instant::now(); + let session = run_session( + mode, + &rom_path, + &dataset, + LegacyProfileKind::Production, + MacroMode::Macros, + &start, + frames, + &Inputs::default(), + ) + .await; + let agreement = + trace::compare(&legacy.behaviours, &session.behaviours, &session.bounds) + .unwrap_or_else(|e| panic!("{name}, {}: {e}", mode.label())); + compare_ledgers(&legacy.ledgers, &session.ledgers); + report( + &format!("service checkpoint {name}, {}", mode.label()), + &agreement, + started.elapsed(), + ); + } + } +} + +/// Runs `frames` transitions of a booted session with the store attached, recording the +/// session's `FLY_TRACE` behaviours, ledgers and bound sets, and every save it took. +async fn run_booted( + session: &mut LegacySession, + frames: usize, +) -> (Run, Vec) { + let mut run = Run { + behaviours: Vec::new(), + ledgers: Vec::new(), + bounds: Vec::new(), + }; + let mut saves = Vec::new(); + for k in 1..=frames { + let (step, saved) = session + .advance() + .await + .unwrap_or_else(|e| panic!("frame {k}: {e}")); + saves.extend(saved); + let details = step.details.expect("details are recorded"); + let [record] = step.records.as_slice() else { + panic!("frame {k}: {} task records", step.records.len()); + }; + run.behaviours.push( + trace::line(&details, record).unwrap_or_else(|e| panic!("frame {k}: {e}"))["behaviour"] + .clone(), + ); + run.ledgers.push(record.ledgers.clone()); + run.bounds.push(record.bound.clone()); + } + (run, saves) +} + +/// The SHADOW-01 entry gate: the session runtime boots from a live FLYSIM01 store, runs, saves, +/// restarts and restores from its own save, and every segment matches the legacy loop's trace. +/// +/// The store holds one durable generation, a stream checkpoint (the FND-01 review's `rollback` +/// file when `FLY_ENV01_TRACE_DIR` is set: a ratchet rollback on the first boundary, so the +/// after-rollback durable save is exercised; else `FLY_DOOR_CHECKPOINT`). Process one boots from +/// it (the legacy candidate order and gate, `boot`), writes its startup durable save, runs +/// `FLY_TASK01_BOOT_FRAMES` transitions with the legacy boundary saves, and shuts down with a +/// durable save. Process two boots from the same store and so restores process one's shutdown +/// save -- a file the session runtime wrote -- and runs on. The legacy loop runs the first +/// segment from the original file and the second from process one's save, which is also the +/// proof that the legacy loop reads what the session runtime writes. In-process then process. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fafb_boot_run_save_restore() { + let Some(rom_path) = rom_path() else { return }; + let Some(dataset) = fafb() else { return }; + // The rollback file (a ratchet rollback on the first boundary), and the live fly's largest + // task ledgers: row 64 (42 KB) and the row 65 yard (46 KB), past the 32 KiB TypedValue bound + // (TASK-01 review B1). `FLY_TASK01_BOOT_SOURCES` picks others (`name=path,...`). + let sources: Vec<(String, PathBuf)> = match std::env::var("FLY_TASK01_BOOT_SOURCES") { + Ok(list) => list + .split(',') + .filter_map(|item| { + item.split_once('=') + .map(|(n, p)| (n.to_owned(), PathBuf::from(p))) + }) + .collect(), + Err(_) => [ + ( + "rollback", + std::env::var_os("FLY_ENV01_TRACE_DIR") + .map(|dir| PathBuf::from(dir).join("rollback.checkpoint")), + ), + ( + "row64", + std::env::var_os("FLY_ROW64_CHECKPOINT").map(PathBuf::from), + ), + ( + "row65-yard", + std::env::var_os("FLY_ROW65_YARD_CHECKPOINT").map(PathBuf::from), + ), + ] + .into_iter() + .filter_map(|(name, path)| path.filter(|p| p.is_file()).map(|p| (name.to_owned(), p))) + .collect(), + }; + if sources.is_empty() { + eprintln!("skipping: no source checkpoint"); + return; + } + let rom = std::fs::read(&rom_path).expect("the cartridge"); + let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset")); + let frames = env_usize("FLY_TASK01_BOOT_FRAMES", 900); + for (name, source) in sources { + let original = std::fs::read(&source).expect("the checkpoint"); + let decoded = flysim::store::decode(&original).expect("FLYSIM01"); + let generation = decoded.runtime.generation; + eprintln!( + "boot source {name}: generation {generation}, task ledger {} bytes of adapter JSON", + serde_json::to_vec(&decoded.runtime.reward) + .map(|v| v.len()) + .unwrap_or(0) + ); + for mode in modes() { + let root = tempfile::tempdir().expect("tmp"); + let store = fly_legacy_session::composition::StoreConfig { + hot_dir: root.path().join("hot"), + durable_dir: root.path().join("durable"), + keep_generations: 4, + // The intervals are wall clock; a parity run takes its saves at the boundaries the + // legacy loop names (startup, a climb, a rollback, shutdown) and not on a timer. + hot_seconds: 1e9, + checkpoint_seconds: 1e9, + speed: 1.0, + }; + flysim::store::Store::new(&store.durable_dir, store.keep_generations) + .commit(generation, &original, None) + .expect("the seeded store"); + let config = |mode| LegacyConfig { + mode, + rom_path: rom_path.clone(), + dataset_dir: dataset.clone(), + profile: LegacyProfileKind::Production, + macro_mode: MacroMode::Macros, + agent_id: id("fly"), + agent_threads: 1, + record: true, + }; + + // Process one. + let started = std::time::Instant::now(); + let (mut one, boot) = fly_legacy_session::composition::boot( + &root.path().join("p1"), + config(mode), + &store, + ) + .await + .unwrap_or_else(|e| panic!("{}: boot one: {e}", mode.label())); + match &boot { + fly_legacy_session::composition::Boot::Restored { candidate, .. } => { + assert_eq!( + candidate.generation, + Some(generation), + "the seeded generation" + ); + } + other => panic!("boot one: {other:?}"), + } + let startup = one.checkpointer().expect("attached").next_generation() - 1; + assert!( + startup > generation, + "the startup save takes a generation above the store's" + ); + let (run_one, saves_one) = run_booted(&mut one, frames).await; + let shutdown = one + .shutdown_save() + .await + .expect("the shutdown save") + .expect("a store"); + one.stop().await; + assert!(shutdown.durable); + let legacy_one = run_legacy( + &rom, + &data, + &Start::Checkpoint(original.clone()), + MacroMode::Macros, + frames, + &Inputs::default(), + &root.path().join("legacy-one.jsonl"), + ); + let agreement = + trace::compare(&legacy_one.behaviours, &run_one.behaviours, &run_one.bounds) + .unwrap_or_else(|e| panic!("{} segment one: {e}", mode.label())); + compare_ledgers(&legacy_one.ledgers, &run_one.ledgers); + report( + &format!("boot {name} segment one, {}", mode.label()), + &agreement, + started.elapsed(), + ); + eprintln!( + " saves: startup g{startup}, during the run {:?}, shutdown g{}", + saves_one + .iter() + .map(|s| (s.generation, s.durable, s.archive_rank)) + .collect::>(), + shutdown.generation + ); + if agreement.rollbacks > 0 { + assert!( + saves_one.iter().any(|s| s.durable), + "a rollback is followed by a durable save" + ); + } + + // Process two: restores process one's shutdown save. + let started = std::time::Instant::now(); + let (mut two, boot) = fly_legacy_session::composition::boot( + &root.path().join("p2"), + config(mode), + &store, + ) + .await + .unwrap_or_else(|e| panic!("{}: boot two: {e}", mode.label())); + let restored_path = match &boot { + fly_legacy_session::composition::Boot::Restored { candidate, .. } => { + assert_eq!( + candidate.generation, + Some(shutdown.generation), + "the latest save" + ); + candidate.path.clone() + } + other => panic!("boot two: {other:?}"), + }; + let written = std::fs::read(&restored_path).expect("the session's own save"); + let (run_two, _) = run_booted(&mut two, frames).await; + two.stop().await; + let legacy_two = run_legacy( + &rom, + &data, + &Start::Checkpoint(written), + MacroMode::Macros, + frames, + &Inputs::default(), + &root.path().join("legacy-two.jsonl"), + ); + let agreement = + trace::compare(&legacy_two.behaviours, &run_two.behaviours, &run_two.bounds) + .unwrap_or_else(|e| panic!("{} segment two: {e}", mode.label())); + compare_ledgers(&legacy_two.ledgers, &run_two.ledgers); + report( + &format!("boot {name} segment two, {}", mode.label()), + &agreement, + started.elapsed(), + ); + } + } +} + +/// Thins a checkpoint's adapter ledger so the fly earns rewards: the current map is unvisited +/// (an `AREA` payout on the first sample), its exits unfound (`boundary`), its ground unwalked +/// (`exploration`), and no wild win is a replay (`battle`). +fn reward_bearing(bytes: &[u8]) -> Vec { + let mut checkpoint = flysim::store::decode(bytes).expect("FLYSIM01"); + let reward = &mut checkpoint.runtime.reward; + let map = reward["location"] + .as_str() + .and_then(|l| l.split(':').next()) + .unwrap_or("0") + .to_owned(); + if let Some(seen) = reward["seen"].as_array_mut() { + seen.retain(|key| { + let key = key.as_str().unwrap_or(""); + key != format!("map:{map}") && !key.starts_with(&format!("boundary:{map}:")) + }); + } + if let Some(tiles) = reward["tiles"].as_array_mut() { + tiles.retain(|tile| !tile.as_str().unwrap_or("").starts_with(&format!("{map}:"))); + } + if let Some(counts) = reward["tileCounts"].as_object_mut() { + counts.remove(&map); + } + reward["wildWins"] = serde_json::json!({}); + reward["replayBlocked"] = serde_json::json!([]); + flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).expect("encodes") +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fafb_reward_segments() { + let Some(rom_path) = rom_path() else { return }; + let Some(dataset) = fafb() else { return }; + let rom = std::fs::read(&rom_path).expect("the cartridge"); + let segments: Vec<(String, PathBuf)> = match std::env::var("FLY_TASK01_SEGMENTS") { + Ok(list) => list + .split(',') + .filter_map(|item| { + item.split_once('=') + .map(|(n, p)| (n.to_owned(), PathBuf::from(p))) + }) + .collect(), + Err(_) => [ + "FLY_DOOR_CHECKPOINT", + "FLY_CATCH_CHECKPOINT", + "FLY_ENGAGE_CHECKPOINT", + // The live fly's largest task ledgers (42 and 46 KB, TASK-01 review B1). + "FLY_ROW64_CHECKPOINT", + "FLY_ROW65_YARD_CHECKPOINT", + ] + .iter() + .filter_map(|var| std::env::var_os(var).map(|p| ((*var).to_owned(), PathBuf::from(p)))) + .collect(), + }; + let frames = env_usize("FLY_TASK01_FRAMES", 1200); + let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset")); + let arms: Vec = std::env::var("FLY_TASK01_ARMS") + .map(|v| v.split(',').map(str::to_owned).collect()) + .unwrap_or_else(|_| vec!["brain".into(), "driver".into()]); + for (segment, path) in segments { + for arm in &arms { + let name = format!("{segment} {arm}"); + let original = std::fs::read(&path).expect("the checkpoint"); + let bytes = if arm == "brain" { + reward_bearing(&original) + } else { + original + }; + let inputs = Inputs { + sugar: vec![(10, 400.0), (frames / 2, 250.0)], + driver: arm == "driver", + }; + let dir = tempfile::tempdir().expect("tmp"); + let started = std::time::Instant::now(); + let start = Start::Checkpoint(bytes); + let legacy = run_legacy( + &rom, + &data, + &start, + MacroMode::Macros, + frames, + &inputs, + &dir.path().join("trace.jsonl"), + ); + eprintln!( + "legacy loop {name}: {frames} frames in {:?}", + started.elapsed() + ); + for mode in modes() { + let started = std::time::Instant::now(); + let session = run_session( + mode, + &rom_path, + &dataset, + LegacyProfileKind::Production, + MacroMode::Macros, + &start, + frames, + &inputs, + ) + .await; + let agreement = + trace::compare(&legacy.behaviours, &session.behaviours, &session.bounds) + .unwrap_or_else(|e| panic!("{name}, {}: {e}", mode.label())); + compare_ledgers(&legacy.ledgers, &session.ledgers); + report( + &format!("segment {name}, {}", mode.label()), + &agreement, + started.elapsed(), + ); + } + } + } +} diff --git a/services/flysim/crates/fly-legacy-session/tests/speed.rs b/services/flysim/crates/fly-legacy-session/tests/speed.rs new file mode 100644 index 0000000..a90340b --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/speed.rs @@ -0,0 +1,265 @@ +//! TASK-01 review N5: the session runtime's cost per frame against the legacy loop's, on the same +//! box, from the same checkpoint, in the service configuration (no trace, no step details). +//! +//! `FLY_TASK01_BENCH=1` (plus rom-env and `data/fafb-v783`): the legacy loop (`LegacyFrame`, the +//! service's frame, trace off) and the session (agent, world and task under the coordinator, +//! details off) each run `FLY_TASK01_BENCH_FRAMES` unpaced frames after a warm-up, with +//! `FLY_TASK01_BENCH_THREADS` sweep threads (the release container runs 3). Reported: ms per frame, +//! the realtime factor at 1x (one frame is 16.74 ms of game time), and the session's per-method +//! latencies from the coordinator's metrics. Then the session runs paced at 1x for the same +//! number of frames and reports the realtime factor it held. + +use std::sync::Arc; +use std::time::Instant; + +use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity; +use fly_session::types::id; +use flybrain_core::agent::{AgentConfig, NeuralAgent}; +use flybrain_core::dataset::load_brain_dataset_from_dir; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flybrain_core::lif::SweepPlan; +use flybrain_gb::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::macro_layer; +use flysim::snapshot::MacroMode; + +/// The legacy frame's phases, timed through the one hook the stream itself uses. +struct Phases { + last: Instant, + sums: std::collections::BTreeMap<&'static str, f64>, + on: bool, +} + +impl flysim::frame::FrameObserver for Phases { + fn after(&mut self, phase: flysim::frame::FramePhase, _agent: &mut NeuralAgent) { + let now = Instant::now(); + if self.on { + let name = match phase { + flysim::frame::FramePhase::Ticked => "legacy.ticks", + flysim::frame::FramePhase::Executed => "legacy.decode+execute", + flysim::frame::FramePhase::Emulated => "legacy.frame", + flysim::frame::FramePhase::Advanced => "legacy.take_frame", + flysim::frame::FramePhase::Committed => "legacy.evaluate+commit", + }; + *self.sums.entry(name).or_default() += (now - self.last).as_secs_f64() * 1000.0; + } + self.last = now; + } +} + +const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0; + +fn env_usize(name: &str, default: usize) -> usize { + std::env::var(name) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn session_against_legacy_per_frame() { + if std::env::var_os("FLY_TASK01_BENCH").is_none() { + eprintln!("skipping: FLY_TASK01_BENCH is not set"); + return; + } + let (Some(rom_path), Some(dataset), Some(checkpoint_path)) = ( + std::env::var_os("FLY_ROM").map(std::path::PathBuf::from), + legacy_parity::fafb_dir(), + std::env::var_os("FLY_DOOR_CHECKPOINT").map(std::path::PathBuf::from), + ) else { + eprintln!("skipping: FLY_ROM, data/fafb-v783 or FLY_DOOR_CHECKPOINT missing"); + return; + }; + let frames = env_usize("FLY_TASK01_BENCH_FRAMES", 1200); + let warmup = env_usize("FLY_TASK01_BENCH_WARMUP", 120); + let threads = env_usize("FLY_TASK01_BENCH_THREADS", 3); + let rom = std::fs::read(&rom_path).unwrap(); + let bytes = std::fs::read(&checkpoint_path).unwrap(); + let checkpoint = flysim::store::decode(&bytes).unwrap(); + + // ---- The legacy loop: the service's frame, trace off. + let data = Arc::new(load_brain_dataset_from_dir(&dataset).unwrap()); + let mut emulator = Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).unwrap(); + 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_owned(); + config.macros.mode = MacroMode::Macros; + let (channels, hold_ms) = channels_and_hold(MacroMode::Macros); + let channels: Vec<&str> = channels.iter().map(String::as_str).collect(); + let mut agent_config = AgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels)); + agent_config.warmup_ms = config.loop_.warmup_ms; + let mut agent = NeuralAgent::new(Arc::clone(&data), agent_config).unwrap(); + if threads > 1 { + agent.set_sweep_plan(SweepPlan::with_threads(threads).unwrap()); + } + let mut frame = LegacyFrame::new(); + frame + .restore( + &mut Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: None, + }, + &checkpoint, + ) + .unwrap(); + let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32); + if let Some(layer) = macros.as_mut() { + let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms); + } + let mut legacy_ms = 0.0; + let mut phases = Phases { + last: Instant::now(), + sums: Default::default(), + on: false, + }; + let mut boundary_ms = 0.0; + for n in 0..warmup + frames { + let started = Instant::now(); + phases.on = n >= warmup; + phases.last = started; + 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 phases).unwrap(); + let at = Instant::now(); + frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .unwrap(); + if n >= warmup { + boundary_ms += at.elapsed().as_secs_f64() * 1000.0; + } + if n >= warmup { + legacy_ms += started.elapsed().as_secs_f64() * 1000.0; + } + } + // What a legacy checkpoint costs the loop: the agent's export (the writer thread encodes). + let at = Instant::now(); + for _ in 0..10 { + std::hint::black_box(agent.export_state()); + } + let export_ms = at.elapsed().as_secs_f64() * 100.0; + drop(agent); + let legacy_per = legacy_ms / frames as f64; + for (name, sum) in &phases.sums { + eprintln!( + " legacy {name:<24} mean {:>8.0} us", + sum * 1000.0 / frames as f64 + ); + } + eprintln!( + " legacy boundary mean {:>8.0} us", + boundary_ms * 1000.0 / frames as f64 + ); + eprintln!( + " legacy agent.export_state mean {:>8.0} us (per checkpoint)", + export_ms * 1000.0 + ); + eprintln!( + "legacy loop: {legacy_per:.2} ms/frame over {frames} frames ({threads} threads), realtime factor at 1x {:.2}", + (FRAME_MS / legacy_per).min(1.0) + ); + + // ---- The session, unpaced then paced, in each mode. + for mode in [ExecutionMode::InProcess, ExecutionMode::Process] { + for paced in [false, true] { + let root = tempfile::tempdir().unwrap(); + let mut session = LegacySession::start( + root.path(), + LegacyConfig { + mode, + rom_path: rom_path.clone(), + dataset_dir: dataset.clone(), + profile: LegacyProfileKind::Production, + macro_mode: MacroMode::Macros, + agent_id: id("fly"), + agent_threads: threads.max(1), + record: false, + }, + ) + .await + .unwrap(); + session.bootstrap().await.unwrap(); + session.import_flysim01(&bytes, &id("e2")).await.unwrap(); + if !paced { + session.coordinator.disable_pacing(); + } + for _ in 0..warmup { + session.step().await.unwrap(); + } + session.coordinator.metrics.clear(); + let _ = fly_session::profile::report(); + let started = Instant::now(); + for _ in 0..frames { + session.step().await.unwrap(); + } + let per = started.elapsed().as_secs_f64() * 1000.0 / frames as f64; + if !paced { + // What a save costs the loop: the participants' State.Capture at the boundary. + let root = tempfile::tempdir().unwrap(); + session + .attach_store(&fly_legacy_session::composition::StoreConfig { + hot_dir: root.path().join("hot"), + durable_dir: root.path().join("durable"), + keep_generations: 2, + hot_seconds: 1e9, + checkpoint_seconds: 1e9, + speed: 1.0, + }) + .unwrap(); + let at = Instant::now(); + for _ in 0..5 { + let ticket = session + .queue_save(fly_session::legacy_checkpoint::SaveKind::Hot) + .await + .unwrap(); + drop(ticket); + } + eprintln!( + " session save (capture on the loop) mean {:>8.0} us", + at.elapsed().as_secs_f64() * 1e6 / 5.0 + ); + } + let factor = FRAME_MS / per; + eprintln!( + "session {} {}: {per:.2} ms/frame, realtime factor {:.2} ({:.2}x the legacy loop's cost)", + mode.label(), + if paced { "paced at 1x" } else { "unpaced" }, + if paced { factor } else { factor.min(1.0) }, + per / legacy_per + ); + if !paced { + for (name, count, mean) in fly_session::profile::report() { + eprintln!( + " span {name:<22} mean {:>8.0} us n {count}", + mean.as_secs_f64() * 1e6 + ); + } + for name in session.coordinator.metrics.names() { + let p = session.coordinator.metrics.percentiles(&name).unwrap(); + eprintln!( + " {name:<24} p50 {:>8.0} us p95 {:>8.0} us n {}", + p.p50_us(), + p.p95_us(), + session.coordinator.metrics.count(&name) + ); + } + } + session.stop().await; + } + } +} diff --git a/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs b/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs new file mode 100644 index 0000000..55b37a8 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs @@ -0,0 +1,207 @@ +//! TASK-01 review N5: the session runtime's cost per frame against the legacy loop's, measured +//! A/B-interleaved on one box so both see the same load: chunks of `FLY_TASK01_AB_CHUNK` frames +//! of the legacy loop (`LegacyFrame`, the service's frame, trace off) alternate with chunks of the +//! session (agent, world and task under the coordinator, service configuration: no details, +//! bounded history, snapshots at 30 Hz), both from the same checkpoint with the same sweep threads. +//! A shared box's load then shifts both arms alike, and the ratio is the comparison. +//! +//! `FLY_TASK01_BENCH=1` plus rom-env and `data/fafb-v783`. Reported per execution mode: mean +//! ms/frame of each arm, the ratio, the fps each sustains unpaced, and the headroom at 1x (one +//! Game Boy frame is 16.74 ms). + +use std::sync::Arc; +use std::time::Instant; + +use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity; +use fly_session::types::id; +use flybrain_core::agent::{AgentConfig, NeuralAgent}; +use flybrain_core::dataset::load_brain_dataset_from_dir; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flybrain_core::lif::SweepPlan; +use flybrain_gb::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; + +const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0; + +fn env_usize(name: &str, default: usize) -> usize { + std::env::var(name) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +struct Legacy { + emulator: Emulator, + adapter: PokemonRedReward, + ratchet: Ratchet, + agent: NeuralAgent, + frame: LegacyFrame, + macros: Option, +} + +impl Legacy { + fn new( + rom: &[u8], + dataset: &std::path::Path, + checkpoint: &flysim::store::Checkpoint, + threads: usize, + ) -> Legacy { + let data = Arc::new(load_brain_dataset_from_dir(dataset).unwrap()); + let mut emulator = + Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).unwrap(); + 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_owned(); + config.macros.mode = MacroMode::Macros; + let (channels, hold_ms) = channels_and_hold(MacroMode::Macros); + let channels: Vec<&str> = channels.iter().map(String::as_str).collect(); + let mut agent_config = + AgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels)); + agent_config.warmup_ms = config.loop_.warmup_ms; + let mut agent = NeuralAgent::new(data, agent_config).unwrap(); + if threads > 1 { + agent.set_sweep_plan(SweepPlan::with_threads(threads).unwrap()); + } + let mut frame = LegacyFrame::new(); + frame + .restore( + &mut Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: None, + }, + checkpoint, + ) + .unwrap(); + let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32); + if let Some(layer) = macros.as_mut() { + let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms); + } + Legacy { + emulator, + adapter, + ratchet, + agent, + frame, + macros, + } + } + + fn step(&mut self) { + let mut parts = Parts { + agent: &mut self.agent, + emulator: &mut self.emulator, + adapter: &mut self.adapter, + ratchet: &mut self.ratchet, + macros: self.macros.as_mut(), + }; + let transition = self.frame.transition(&mut parts, &mut ()).unwrap(); + self.frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .unwrap(); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn session_against_legacy_interleaved() { + if std::env::var_os("FLY_TASK01_BENCH").is_none() { + eprintln!("skipping: FLY_TASK01_BENCH is not set"); + return; + } + let (Some(rom_path), Some(dataset), Some(checkpoint_path)) = ( + std::env::var_os("FLY_ROM").map(std::path::PathBuf::from), + legacy_parity::fafb_dir(), + std::env::var_os("FLY_DOOR_CHECKPOINT").map(std::path::PathBuf::from), + ) else { + eprintln!("skipping: FLY_ROM, data/fafb-v783 or FLY_DOOR_CHECKPOINT missing"); + return; + }; + let frames = env_usize("FLY_TASK01_BENCH_FRAMES", 1800); + let chunk = env_usize("FLY_TASK01_AB_CHUNK", 60); + let threads = env_usize("FLY_TASK01_BENCH_THREADS", 3); + let rom = std::fs::read(&rom_path).unwrap(); + let bytes = std::fs::read(&checkpoint_path).unwrap(); + let checkpoint = flysim::store::decode(&bytes).unwrap(); + for mode in [ExecutionMode::InProcess, ExecutionMode::Process] { + let mut legacy = Legacy::new(&rom, &dataset, &checkpoint, threads); + let root = tempfile::tempdir().unwrap(); + let mut session = LegacySession::start( + root.path(), + LegacyConfig { + mode, + rom_path: rom_path.clone(), + dataset_dir: dataset.clone(), + profile: LegacyProfileKind::Production, + macro_mode: MacroMode::Macros, + agent_id: id("fly"), + agent_threads: threads.max(1), + record: false, + }, + ) + .await + .unwrap(); + session.bootstrap().await.unwrap(); + session.import_flysim01(&bytes, &id("e2")).await.unwrap(); + session.coordinator.disable_pacing(); + // Warm both. + for _ in 0..chunk { + legacy.step(); + session.step().await.unwrap(); + } + session.coordinator.metrics.clear(); + let _ = fly_session::profile::report(); + let (mut legacy_ms, mut session_ms) = (0.0, 0.0); + let mut done = 0; + while done < frames { + let at = Instant::now(); + for _ in 0..chunk { + legacy.step(); + } + legacy_ms += at.elapsed().as_secs_f64() * 1000.0; + let at = Instant::now(); + for _ in 0..chunk { + session.step().await.unwrap(); + } + session_ms += at.elapsed().as_secs_f64() * 1000.0; + done += chunk; + } + let (l, s) = (legacy_ms / done as f64, session_ms / done as f64); + eprintln!( + "{}: legacy {l:.2} ms/frame ({:.0} fps), session {s:.2} ms/frame ({:.0} fps); session/legacy {:.2}; headroom at 1x legacy {:.2} ms, session {:.2} ms ({done} frames each, {chunk}-frame chunks, {threads} threads)", + mode.label(), + 1000.0 / l, + 1000.0 / s, + s / l, + FRAME_MS - l, + FRAME_MS - s + ); + for (name, count, mean) in fly_session::profile::report() { + eprintln!( + " span {name:<26} mean {:>8.0} us n {count}", + mean.as_secs_f64() * 1e6 + ); + } + for name in session.coordinator.metrics.names() { + let p = session.coordinator.metrics.percentiles(&name).unwrap(); + eprintln!( + " {name:<24} p50 {:>8.0} us p95 {:>8.0} us n {}", + p.p50_us(), + p.p95_us(), + session.coordinator.metrics.count(&name) + ); + } + session.stop().await; + } +} diff --git a/services/flysim/crates/fly-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index 9d54739..85ef174 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -20,7 +20,7 @@ use crate::publish::PublicationOutcome; use crate::metrics::Metrics; use crate::phase::{Phase, PhaseMachine}; use crate::rpc::{self, DomainReply, Serials, WorkerRef}; -use crate::task::{ActionExecutor, Task}; +use crate::task::{ActionExecutor, Inspection, Task}; // `crate::types` is this crate's facade over the shared `fly-session-types` crate; the // glob keeps the contract's own names in sight instead of restating them. use crate::types::*; @@ -237,6 +237,11 @@ pub struct AgentSlot { pub worker_threads: u64, pub tick_duration: RationalNs, pub warmup_ticks: u64, + /// The numerical model and plasticity versions the profile runs, which are part of the + /// agent's compatibility identity. The synthetic fake model's by default; the legacy profile + /// runs `lif-1ms-f64-v2` and `fly-kc-mbon-rstdp-v2`. + pub model_version: String, + pub plasticity_version: String, pub committed_step: u64, /// The graph this fly attested to at `Agent.Initialize`, which is what the published /// descriptor says about it. `None` before initialization. @@ -271,6 +276,8 @@ impl AgentSlot { worker_threads: 1, tick_duration: RationalNs::ZERO, warmup_ticks: 0, + model_version: crate::agent::MODEL_VERSION.to_owned(), + plasticity_version: crate::agent::PLASTICITY_VERSION.to_owned(), committed_step: 0, graph: None, telemetry: None, @@ -339,6 +346,43 @@ pub struct Coordinator { /// The rollback policy the composition declares, if any (`legacy-ratchet-rollback-v1` is /// the only one defined). Without one, a task's rollback request is a task failure. rollback_policy: Option, + /// The documents `Environment.Initialize` names. The synthetic arena's by default; a + /// composition with its own backend (the legacy Game Boy) sets them. + backend_config: AssetRef, + task_config: AssetRef, + /// The decision schema every agent's profile registers. + decision_schema: SchemaRef, + /// The inspection attachments the task reads (`Task::inspection_attachments`), and the + /// holds on them: O[k]'s until transition k -> k+1 has been evaluated, O[k+1]'s from the + /// world's result until it becomes the committed boundary's. + inspection_names: Vec, + inspection_held: BTreeMap, + pending_inspection: BTreeMap, + /// O[k]'s inspection with its bytes, as the executor and the task read it. + current_inspection: Option, + /// The environment's advertised capabilities, from `Worker.Hello`. + environment_capabilities: Vec, + /// Agent reply attachments `Agent.Commit` is asked for (`telemetry.spikes`), kept in the + /// step details. None by default. + commit_attachments: Vec, + /// Record [`StepDetails`] for every transition (a parity run). + record_details: bool, + last_details: Option, + /// Audience admissions: queued by the edge, cut into the next Prepare. + admissions: AdmissionQueue, + /// The admissions the transition in flight carries, until it commits or fails. + in_flight_admissions: Vec, + /// How many rollbacks this session has applied, which names the next rollback epoch. + rollbacks: u64, + /// The world's state format, when it is not the synthetic arena's. + state_format_id: Option, + /// Leave a requested rollback for the host to apply (`apply_pending_rollback`). + defer_rollbacks: bool, + pending_rollback: Option<(u64, EpisodeRequest)>, + /// [`Coordinator::bound_history`]. + history_limit: Option, + /// [`Coordinator::snapshot_every`]. + snapshot_every: u64, lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>, stats: Stats, /// The ordered actions this session took, for the ordering assertions. @@ -435,6 +479,31 @@ impl Coordinator { pause: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), episode: None, rollback_policy: None, + backend_config: crate::environment::synthetic_asset( + "counter-arena-backend", + "counter-arena-backend-v1", + ), + task_config: crate::environment::synthetic_asset( + "counter-arena-setup", + "counter-arena-setup-v1", + ), + decision_schema: crate::task::decision_schema(), + inspection_names: Vec::new(), + inspection_held: BTreeMap::new(), + pending_inspection: BTreeMap::new(), + current_inspection: None, + environment_capabilities: Vec::new(), + commit_attachments: Vec::new(), + record_details: false, + last_details: None, + admissions: AdmissionQueue::default(), + in_flight_admissions: Vec::new(), + rollbacks: 0, + state_format_id: None, + defer_rollbacks: false, + pending_rollback: None, + history_limit: None, + snapshot_every: 1, lifecycle_acks: Vec::new(), stats: Stats::default(), audit: Vec::new(), @@ -531,9 +600,10 @@ impl Coordinator { } /// Declares the composition's rollback policy (`workers-v1` section 4 and `step-v1` section 6, - /// both amended 2026-09-23). Only `legacy-ratchet-rollback-v1` is defined. Until the rollback - /// sequence is wired (TASK-01), a declared rollback request pauses the session at its boundary - /// like a terminal one, which is safe; an undeclared one fails the epoch. + /// both amended 2026-09-23). Only `legacy-ratchet-rollback-v1` is defined. With it declared, a + /// rollback request is applied at the boundary it was asked for (`apply_rollback`, TASK-01), + /// and every agent must advertise the policy at `Worker.Hello`; without it the request fails + /// the epoch. pub fn declare_rollback_policy(&mut self, policy: &str) -> Result<(), DomainError> { if policy != fly_session_types::extensions::ROLLBACK_POLICY { return Err(DomainError::invalid(format!("{policy} is not a defined rollback policy"))); @@ -542,6 +612,246 @@ impl Coordinator { Ok(()) } + /// The documents `Environment.Initialize` names: the backend configuration and the task + /// setup. A composition with its own backend sets them before [`Coordinator::bootstrap`]. + pub fn set_environment_config(&mut self, backend_config: AssetRef, task_config: AssetRef) { + self.backend_config = backend_config; + self.task_config = task_config; + } + + /// The view and audio stream ids this composition's world produces, which name the + /// attachments `Environment.Initialize` is asked for (afterwards they come from its + /// descriptor). The synthetic arena's by default. + pub fn set_media(&mut self, views: &[&str], audio_streams: &[&str]) { + self.media_names = views + .iter() + .map(|v| media::view_attachment(v)) + .chain(audio_streams.iter().map(|a| media::audio_attachment(a))) + .collect(); + } + + /// The state format the world's captures declare (`Compatibility.stateFormatId`): the + /// synthetic arena's by default, `fly-gb-env-v1` for the legacy Game Boy world (ENV-01). + pub fn set_state_format(&mut self, state_format_id: &str) { + self.state_format_id = Some(id(state_format_id)); + } + + /// Bounds the session's in-memory history -- the behaviour trace, the phase log, the audit + /// log and the latency samples -- to the newest `keep` entries each, for a session that runs + /// indefinitely (the live fly). Unbounded by default: a test reads all of it. + pub fn bound_history(&mut self, keep: usize) { + self.history_limit = Some(keep); + } + + /// Publishes the committed snapshot of every `n`-th boundary, and of every boundary with task + /// events or boundary actions. Presentation reads snapshots as latest values + /// (`publishing-v1`), and the legacy feed publishes at `snapshot_hz` (30 Hz) from its 60 Hz + /// loop, so a live composition need not pay a publication on every frame. 1 (every boundary) + /// by default. + pub fn snapshot_every(&mut self, n: u64) { + self.snapshot_every = n.max(1); + } + + fn trim_history(&mut self) { + let Some(keep) = self.history_limit else { return }; + fn trim(items: &mut Vec, keep: usize) { + if items.len() > 2 * keep { + items.drain(..items.len() - keep); + } + } + trim(&mut self.trace.transitions, keep); + trim(&mut self.trace.phases, keep); + trim(&mut self.audit, keep); + trim(&mut self.injection_log, keep); + self.metrics.truncate(keep); + } + + /// Leave a rollback the task asks for pending at its boundary, for the host to apply with + /// [`Coordinator::apply_pending_rollback`] after its own captures there. No transition starts + /// while one is pending. + pub fn defer_rollbacks(&mut self, on: bool) { + self.defer_rollbacks = on; + } + + /// The boundary a deferred rollback waits at, if one does. + pub fn pending_rollback(&self) -> Option { + self.pending_rollback.as_ref().map(|(k, _)| *k) + } + + /// Applies a deferred rollback (the declared policy, `apply_rollback`), and adds it to the + /// last transition's trace and step details, where an immediate rollback would have been. + /// Returns whether one was pending. + pub async fn apply_pending_rollback(&mut self) -> Outcome { + let Some((boundary, request)) = self.pending_rollback.take() else { + return Ok(false); + }; + let (action, details) = self.apply_rollback(boundary, &request).await?; + if let Some(trace) = self.trace.transitions.last_mut() + && trace.behaviour.acknowledged_boundary == boundary + { + trace.behaviour.boundary_actions.push(action.clone()); + } + if let Some(step) = self.last_details.as_mut() + && step.step + 1 == boundary + { + step.boundary_actions.push(action); + step.rollback = Some(details); + } + Ok(true) + } + + /// One participant-coherent capture of the committed boundary for the legacy store + /// (STATE-02's `LegacyCheckpointer`): every participant's `State.Capture` payload under + /// `Capturing(k)`, released once read. The task's half is the host's to take from the task. + /// Taken after the boundary's slot save and before a pending rollback, as + /// `legacy-gameboy-v1` section 16 orders a milestone capture. + pub async fn capture_payloads( + &mut self, + checkpoint_id: &Id, + ) -> Outcome<(u64, Vec, Vec<(Id, Vec)>)> { + let pending = self.begin_capture(checkpoint_id).await?; + self.finish_capture(pending).await + } + + /// Sends every participant's `State.Capture` for the committed boundary and returns without + /// waiting for the replies: the capture off the loop (TASK-01 review N5). + /// + /// Each participant takes its state at the boundary when it handles the request, which it + /// does before any request sent after it (a worker takes its lock in arrival order), and a + /// participant that encodes off its lock (the legacy agent) answers the next Prepare while it + /// seals the payload. The session may step on; [`Coordinator::finish_capture`] collects the + /// payloads, in the order sent, whenever the host is ready for them. + pub async fn begin_capture(&mut self, checkpoint_id: &Id) -> Outcome { + let origin = self.phases.phase(); + let Some(boundary) = origin.committed_boundary().filter(|_| origin.is_committed_boundary()) + else { + return Err(SessionFailure { + error: DomainError::before( + ErrorCode::InvalidPhase, + "a coherent capture is taken at a committed boundary only", + ), + phase: origin.label(), + detail: "capture".to_owned(), + participant: None, + }); + }; + self.transition(Phase::Capturing(boundary))?; + let mut participants = vec![self.environment.clone()]; + participants.extend(self.agents.iter().map(|slot| slot.worker.clone())); + let params = object(CaptureParams { checkpoint_id: checkpoint_id.clone() }.to_json()); + let want = vec![crate::state::PAYLOAD_ATTACHMENT.to_owned()]; + let scope = self.scope(boundary); + let mut calls = Vec::new(); + for worker in participants { + let request_id = self.serials.next(&worker.service); + let sent = crate::rpc::send( + &self.bus, + &worker, + "State.Capture", + Some(scope.clone()), + params.clone(), + &[], + request_id, + &want, + ) + .await; + match sent { + Ok(sent) => calls.push((worker, sent)), + Err(e) => { + self.blame(Some(worker.worker_id.clone())); + return Err(self.fail_now(e, "capture")); + } + } + } + self.transition(origin)?; + Ok(PendingCapture { checkpoint_id: checkpoint_id.clone(), boundary, scope, calls }) + } + + /// Collects a capture begun with [`Coordinator::begin_capture`]: the world's payload and + /// every agent's, read and released. + pub async fn finish_capture( + &mut self, + pending: PendingCapture, + ) -> Outcome<(u64, Vec, Vec<(Id, Vec)>)> { + let PendingCapture { checkpoint_id, boundary, scope, calls } = pending; + let mut payloads = Vec::new(); + for (worker, sent) in calls { + let reply = match sent.finish().await { + Ok(reply) => reply, + Err(e) => { + self.blame(Some(worker.worker_id.clone())); + return Err(self.fail_now(e, "capture")); + } + }; + self.check_reply(&worker, &reply, &Some(scope.clone()), "State.Capture")?; + if let Err(e) = reply.result() { + return Err(self.fail_now(e, "capture")); + } + let Some(artifact) = reply.artifacts.get(crate::state::PAYLOAD_ATTACHMENT).cloned() else { + return Err(self.fail_now( + DomainError::before(ErrorCode::BufferInvalid, "State.Capture carried no payload"), + "capture", + )); + }; + let span = crate::profile::span("coord.capture.read"); + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now(DomainError::before(ErrorCode::BufferInvalid, e.message.clone()), "capture") + })?; + drop(span); + self.acknowledge_replies(&worker, std::slice::from_ref(&reply.request_id)).await?; + payloads.push((worker.worker_id.clone(), bytes)); + } + let world = payloads.remove(0).1; + self.audit.push(format!("captured-payloads:{checkpoint_id}@{boundary}")); + Ok((boundary, world, payloads)) + } + + /// The world's compatibility as this composition declares it. + fn world_compatibility(&self, descriptor: &EnvironmentDescriptor) -> crate::state::Compatibility { + let mut compatibility = crate::state::Compatibility::of(descriptor); + if let Some(format) = &self.state_format_id { + compatibility.state_format_id = format.clone(); + } + compatibility + } + + /// The decision schema the agents' profile registers (`gameboy-channels-v1` for the legacy + /// composition). A PreparedDecision carrying another is refused. + pub fn set_decision_schema(&mut self, schema: SchemaRef) { + self.decision_schema = schema; + } + + /// Ask every `Agent.Commit` for these reply attachments and keep their bytes in the step + /// details (the legacy agent's `telemetry.spikes`). Implies [`Coordinator::record_details`]. + pub fn request_commit_attachments(&mut self, names: &[&str]) { + self.commit_attachments = names.iter().map(|n| (*n).to_owned()).collect(); + self.record_details = true; + } + + /// Record [`StepDetails`] for every transition, for a parity run to read. + pub fn record_details(&mut self, on: bool) { + self.record_details = on; + } + + /// The details of the last completed transition, when they are recorded. + pub fn take_details(&mut self) -> Option { + self.last_details.take() + } + + /// The admission queue: the edge's handle for audience and operator inputs. + pub fn admissions(&self) -> AdmissionQueue { + self.admissions.clone() + } + + /// O[k]'s inspection with its bytes, as the task last read it. + pub fn current_inspection(&self) -> Option<&Inspection> { + self.current_inspection.as_ref() + } + + pub fn episode_id(&self) -> &Id { + &self.episode_id + } + pub fn rollback_policy(&self) -> Option<&Id> { self.rollback_policy.as_ref() } @@ -639,6 +949,13 @@ impl Coordinator { self.pending_views.clear(); self.audio.clear(); self.pending_audio.clear(); + self.inspection_held.clear(); + self.pending_inspection.clear(); + // An admission whose Prepare never committed is aborted, and the edge refunds it + // (`legacy-gameboy-v1` section 15). Queued ones stay queued for the restored epoch. + let aborted = std::mem::take(&mut self.in_flight_admissions); + self.admissions.end(aborted, AdmissionEnd::Aborted); + self.admissions.forget_remaining(); match &participant { Some(who) => self.audit.push(format!("fail:{detail}:{who}")), None => self.audit.push(format!("fail:{detail}")), @@ -717,7 +1034,12 @@ impl Coordinator { Ok(()) } - async fn hello(&mut self, worker: WorkerRef, role: Role, required: &str) -> Outcome { + async fn hello( + &mut self, + worker: WorkerRef, + role: Role, + required: &str, + ) -> Outcome<(Id, Vec)> { let params = HelloParams { session_id: self.session_id.clone(), expected_worker_id: worker.worker_id.clone(), @@ -757,19 +1079,33 @@ impl Coordinator { )); } self.audit.push(format!("hello:{}", worker.worker_id)); - Ok(result.incarnation_id) + Ok((result.incarnation_id, result.capabilities)) } async fn hello_environment(&mut self) -> Outcome<()> { let worker = self.environment.clone(); - let incarnation = self.hello(worker, Role::Environment, "world-step-v1").await?; + let (incarnation, capabilities) = + self.hello(worker, Role::Environment, "world-step-v1").await?; self.environment.domain_incarnation = Some(incarnation); + self.environment_capabilities = capabilities; Ok(()) } async fn hello_agent(&mut self, index: usize) -> Outcome<()> { let worker = self.agents[index].worker.clone(); - let incarnation = self.hello(worker, Role::Agent, "agent-step-v1").await?; + let (incarnation, capabilities) = self.hello(worker, Role::Agent, "agent-step-v1").await?; + if self.rollback_policy.is_some() + && !capabilities.iter().any(|c| c == fly_session_types::extensions::ROLLBACK_CAPABILITY) + { + return Err(self.fail_now( + DomainError::before( + ErrorCode::Unsupported, + "the composition declares a rollback policy and the agent does not answer \ + Agent.Rollback", + ), + "hello", + )); + } self.agents[index].worker.domain_incarnation = Some(incarnation); Ok(()) } @@ -791,20 +1127,15 @@ impl Coordinator { .map(|a| PortBinding { port_id: a.port_id.clone(), agent_id: a.agent_id.clone() }) .collect(); let params = EnvironmentInitializeParams { - backend_config: crate::environment::synthetic_asset( - "counter-arena-backend", - "counter-arena-backend-v1", - ), - task_config: crate::environment::synthetic_asset( - "counter-arena-setup", - "counter-arena-setup-v1", - ), + backend_config: self.backend_config.clone(), + task_config: self.task_config.clone(), episode_id: self.episode_id.clone(), port_bindings: bindings.iter().map(PortBinding::pair).collect(), }; let worker = self.environment.clone(); let scope = self.scope(0); - let want = self.media_names.clone(); + self.inspection_names = self.task.inspection_attachments(); + let want = self.wanted_media(); let reply = self .call( &worker, @@ -845,10 +1176,18 @@ impl Coordinator { "port-assignment", )); } - let (views, audio) = media::split_attachments(reply.artifacts); + let mut artifacts = reply.artifacts; + let held = self.take_inspection(&mut artifacts); + let (views, audio) = media::split_attachments(artifacts); self.views = views; self.audio = audio; self.media_names = media::attachment_names(&result.descriptor); + let inspection = self + .read_inspection(0, &result.observation.inspection, &held) + .await + .map_err(|e| self.fail_now(e, "observation-0"))?; + self.inspection_held = held; + self.current_inspection = Some(inspection); self.timelines = AudioTimelines::fresh(&result.descriptor); if let Err(e) = self.timelines.accept(&result.descriptor, &result.observation) { return Err(self.fail_now(e, "observation-0")); @@ -872,8 +1211,85 @@ impl Coordinator { Ok(()) } + /// SHA-256 of each sensory view's bytes as this session holds them, for the step details. + async fn view_digests( + &mut self, + observation: &WorldObservation, + ) -> Outcome> { + let mut out = Vec::new(); + for view in &observation.sensory_views { + let name = media::view_attachment(&view.view_id); + let Some(artifact) = self.views.get(&name).cloned() else { continue }; + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("reading {name}: {}", e.message), + MutationCertainty::Applied, + ), + "details", + ) + })?; + out.push((view.view_id.clone(), digest_of_bytes(&bytes))); + } + Ok(out) + } + + /// The attachments a world reply is asked for: the declared media, then the inspection + /// attachments the task reads. + fn wanted_media(&self) -> Vec { + let mut want = self.media_names.clone(); + for name in &self.inspection_names { + if !want.contains(name) { + want.push(name.clone()); + } + } + want + } + + /// Takes the inspection attachments out of a world reply's artifacts, leaving the media. + fn take_inspection( + &self, + artifacts: &mut BTreeMap, + ) -> BTreeMap { + self.inspection_names + .iter() + .filter_map(|name| artifacts.remove(name).map(|a| (name.clone(), a))) + .collect() + } + + /// Reads one boundary's inspection attachments into the [`Inspection`] the task and the + /// executor read. Every declared attachment must be there: a boundary whose inspection + /// bytes are missing is refused, never replaced by an older one. + async fn read_inspection( + &self, + boundary: u64, + value: &TypedValue, + held: &BTreeMap, + ) -> DomainResult { + let mut attachments = BTreeMap::new(); + for name in &self.inspection_names { + let artifact = held.get(name).ok_or_else(|| { + DomainError::new( + ErrorCode::BufferInvalid, + format!("boundary {boundary}'s inspection arrived without {name}"), + MutationCertainty::Unknown, + ) + })?; + let bytes = artifact.read_all().await.map_err(|e| { + DomainError::new( + ErrorCode::BufferInvalid, + format!("reading {name}: {}", e.message), + MutationCertainty::Unknown, + ) + })?; + attachments.insert(name.clone(), std::sync::Arc::new(bytes)); + } + Ok(Inspection { boundary, value: value.clone(), attachments }) + } + fn bootstrap_task(&mut self) -> Outcome<()> { - let observation = self.observation.clone().expect("initialized"); + let inspection = self.current_inspection.clone().expect("initialized"); let bindings: Vec = self .agents .iter() @@ -881,7 +1297,7 @@ impl Coordinator { .collect(); let bootstrap = self .task - .bootstrap(&observation.inspection, &bindings) + .bootstrap(&inspection, &bindings) .map_err(|e| self.fail_now(e, "task-bootstrap"))?; for event in &bootstrap.events { if event.source_step != 0 { @@ -1101,6 +1517,253 @@ pub struct StepReport { pub terminal: bool, } +/// One audience input the coordinator admits into a Prepare (`workers-v1` section 5 and its +/// amendment; `legacy-gameboy-v1` section 15). +/// +/// The rules that decide *whether* an input is admitted (a rate limiter, "no overlap with an +/// active pulse") are the composition's and run on the edge side of [`AdmissionQueue`], reading +/// [`AdmissionQueue::stimulus_remaining_ms`]: the last completed commit's value, one commit +/// stale at most. The coordinator only places what was admitted at the next admission cut, in +/// admission order, and reports each one applied or aborted. +#[derive(Clone, Debug, PartialEq)] +pub enum Admission { + /// A profile-supported stimulus in `Prepare.preStepStimulations` (sugar: `reward-pulse`). + Stimulus { agent_id: Id, interaction_id: Id, kind_id: Id, duration_ms: f64 }, +} + +impl Admission { + pub fn agent_id(&self) -> &Id { + match self { + Admission::Stimulus { agent_id, .. } => agent_id, + } + } + + pub fn interaction_id(&self) -> &Id { + match self { + Admission::Stimulus { interaction_id, .. } => interaction_id, + } + } +} + +/// How an admission ended: applied by a Prepare whose transition committed at `boundary`, or +/// aborted because the epoch failed first (the edge refunds it). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AdmissionEnd { + Applied { boundary: u64 }, + Aborted, +} + +#[derive(Debug, Default)] +struct AdmissionState { + queued: Vec, + /// Cut into a Prepare whose transition has not committed yet. + in_flight: Vec, + remaining: BTreeMap, + ended: Vec<(Admission, AdmissionEnd)>, +} + +impl AdmissionState { + fn set_remaining(&mut self, agent_id: &Id, remaining: Option) { + match remaining { + Some(ms) => { + self.remaining.insert(agent_id.clone(), ms); + } + None => { + self.remaining.remove(agent_id); + } + } + } +} + +/// The edge's handle on admission: queue what the composition's rules admitted, read the last +/// commit's stimulus pulse, collect the outcomes. Clone it freely; every clone is the same queue. +#[derive(Clone, Debug, Default)] +pub struct AdmissionQueue(std::sync::Arc>); + +impl AdmissionQueue { + fn lock(&self) -> std::sync::MutexGuard<'_, AdmissionState> { + self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Queue an admitted input for the next admission cut. + pub fn admit(&self, admission: Admission) { + self.lock().queued.push(admission); + } + + /// `stimulusRemainingMs` of the agent's last completed commit (an `Agent.Rollback` reply + /// counts as one). `None` before the first commit of an epoch -- after a restore the pulse + /// is unknown and the legacy rule refuses with a retry (`legacy-gameboy-v1` section 15). + pub fn stimulus_remaining_ms(&self, agent_id: &Id) -> Option { + self.lock().remaining.get(agent_id).copied() + } + + /// Inputs admitted and not yet cut into a Prepare. + pub fn queued(&self) -> usize { + self.lock().queued.len() + } + + /// The longest stimulus admitted for the agent that no commit has reported on yet: queued + /// for the next cut, or cut into a Prepare still in flight. The legacy loop applies a sugar + /// the moment it admits it, so its pulse is active for the next request at once; here it + /// is active from admission too, which is what this reads. `None` when there is none. + pub fn pending_stimulus_ms(&self, agent_id: &Id) -> Option { + let state = self.lock(); + state + .queued + .iter() + .chain(state.in_flight.iter()) + .filter(|a| a.agent_id() == agent_id) + .map(|a| match a { + Admission::Stimulus { duration_ms, .. } => *duration_ms, + }) + .reduce(f64::max) + } + + /// Every admission that has ended since the last call, in the order they ended. + pub fn take_ended(&self) -> Vec<(Admission, AdmissionEnd)> { + std::mem::take(&mut self.lock().ended) + } + + fn cut(&self) -> Vec { + let mut state = self.lock(); + let cut = std::mem::take(&mut state.queued); + state.in_flight.extend(cut.iter().cloned()); + cut + } + + fn end(&self, admissions: Vec, end: AdmissionEnd) { + self.commit(admissions, end, &[]); + } + + /// Ends the admissions and records the commit's pulses under one lock. + fn commit(&self, admissions: Vec, end: AdmissionEnd, pulses: &[(Id, Option)]) { + let mut state = self.lock(); + for admission in admissions { + state + .in_flight + .retain(|a| a.interaction_id() != admission.interaction_id()); + state.ended.push((admission, end.clone())); + } + for (agent_id, remaining) in pulses { + state.set_remaining(agent_id, *remaining); + } + } + + /// Decides and queues one admission under the lock every commit takes: `decide` gets the + /// agent's last reported pulse and the longest pending one, and returns the admission to + /// queue (or a refusal). No commit can interleave between the reads and the push, which is + /// the single-threaded legacy loop's answer (TASK-01 review R2-3). + pub fn admit_with( + &self, + agent_id: &Id, + decide: impl FnOnce(Option, Option) -> Result, + ) -> Result { + let mut state = self.lock(); + let remaining = state.remaining.get(agent_id).copied(); + let pending = state + .queued + .iter() + .chain(state.in_flight.iter()) + .filter(|a| a.agent_id() == agent_id) + .map(|a| match a { + Admission::Stimulus { duration_ms, .. } => *duration_ms, + }) + .reduce(f64::max); + let admission = decide(remaining, pending)?; + state.queued.push(admission.clone()); + Ok(admission) + } + + fn set_remaining(&self, agent_id: &Id, remaining: Option) { + self.lock().set_remaining(agent_id, remaining); + } + + fn forget_remaining(&self) { + self.lock().remaining.clear(); + } +} + +/// Everything one transition exchanged, for a parity run (`Coordinator::record_details`): the +/// fields a legacy `FLY_TRACE` line is assembled from. +#[derive(Clone, Debug)] +pub struct StepDetails { + /// The boundary the transition started from. + pub step: u64, + /// O[k]'s `engineFrame`. + pub engine_frame: Option, + /// The admissions this transition's Prepare applied, in admission order. + pub admissions: Vec, + pub prepared: Vec<(Id, PreparedDecision)>, + pub controls: Vec, + pub commits: Vec<(Id, AgentCommitResult)>, + /// `(agent, attachment, bytes)` for each requested commit reply attachment. + pub commit_attachments: Vec<(Id, String, Vec)>, + /// SHA-256 of each O[k+1] view's bytes, by view id. + pub view_digests: Vec<(String, Digest)>, + pub evaluation: crate::task::Evaluation, + /// The boundary actions applied at `Ready(k+1)`, in order. + pub boundary_actions: Vec, + /// After a rollback: the new epoch, the restored observation and each agent's reply. + pub rollback: Option, +} + +/// What a rollback at a boundary produced. +#[derive(Clone, Debug)] +pub struct RollbackDetails { + pub epoch: Id, + pub observation: WorldObservation, + pub view_digests: Vec<(String, Digest)>, + pub agents: Vec<(Id, fly_session_types::extensions::AgentRollbackResult)>, +} + +/// A capture sent to every participant and not yet collected ([`Coordinator::begin_capture`]). +pub struct PendingCapture { + checkpoint_id: Id, + boundary: u64, + scope: Scope, + calls: Vec<(WorkerRef, crate::rpc::SentCall)>, +} + +impl PendingCapture { + /// The committed boundary the capture is of. + pub fn boundary(&self) -> u64 { + self.boundary + } +} + +/// A checkpoint of another format, assembled by an importer in each participant's own capture +/// format, to install as a session's start ([`Coordinator::import`]). +#[derive(Clone, Debug)] +pub struct ImportSpec { + pub checkpoint_id: Id, + /// The scope the payloads record as their source (for a FLYSIM01 file, + /// `legacy_checkpoint::legacy_source_scope`: the session, epoch `legacy`, the boundary). + pub source_scope: Scope, + /// The boundary the checkpoint is at. + pub boundary: u64, + /// The environment's `State.Capture` payload. + pub world_payload: Vec, + /// Every agent, in sorted agent-id order. + pub agents: Vec, + pub task_ledger: TypedValue, + /// The ledger's attachments (`Task::capture_attachments`), by name. + pub task_attachments: BTreeMap>, + /// Each declared audio stream's next sample. + pub audio_positions: BTreeMap, +} + +/// One agent of an [`ImportSpec`]. +#[derive(Clone, Debug)] +pub struct ImportedAgent { + pub agent_id: Id, + /// The agent's `State.Capture` payload. + pub payload: Vec, + pub brain_ticks: u64, + pub remainder: RationalNs, + /// The decision context the payload retains. + pub context: TypedValue, +} + /// One per-agent bus call, ready to dispatch. struct Job { agent_id: Id, @@ -1110,6 +1773,8 @@ struct Job { params: Map, attachments: Vec<(String, flybus::Artifact)>, request_id: DomainRequestId, + /// Reply attachments to extract. + want: Vec, } /// Issues one domain call with owned arguments, so it can run in its own task. @@ -1546,7 +2211,7 @@ impl Coordinator { job.params.clone(), job.attachments.clone(), job.request_id.clone(), - Vec::new(), + job.want.clone(), deadline, ) .await; @@ -1581,7 +2246,7 @@ impl Coordinator { job.params.clone(), job.attachments.clone(), job.request_id.clone(), - Vec::new(), + job.want.clone(), deadline, ) .await; @@ -1642,6 +2307,16 @@ impl Coordinator { "step", )); }; + if let Some((boundary, _)) = &self.pending_rollback { + let boundary = *boundary; + return Err(self.fail_now( + DomainError::before( + ErrorCode::InvalidPhase, + format!("the rollback asked for at boundary {boundary} has not been applied"), + ), + "step", + )); + } if self.episode.is_some() { return Err(self.fail_now( DomainError::before( @@ -1670,26 +2345,39 @@ impl Coordinator { // ---- Phase A: prepare all agents concurrently self.transition(Phase::Preparing(k))?; + let span = crate::profile::span("coord.prepare"); let prepared = self.prepare_all(k, descriptor.step_duration).await?; + drop(span); // ---- Phase B: build and apply one complete batch self.transition(Phase::Applying(k))?; + let span = crate::profile::span("coord.executor"); let controls = self.build_batch(k, &descriptor, &old_observation)?; + drop(span); let batch_id = self.batch_id(k); + let span = crate::profile::span("coord.advance"); let step_result = self.advance(k, &batch_id, &controls).await?; + drop(span); + let span = crate::profile::span("coord.observe"); // ---- Phase C: observe and evaluate the task once self.transition(Phase::Observing(k + 1))?; self.verify_step_result(k, &descriptor, &batch_id, &controls, &old_observation, &step_result)?; let scope = self.scope(k); + let pending_inspection = std::mem::take(&mut self.pending_inspection); + let new_inspection = self + .read_inspection(k + 1, &step_result.observation.inspection, &pending_inspection) + .await + .map_err(|e| self.fail_now(e, "step-result"))?; + let old_inspection = self + .current_inspection + .clone() + .expect("a bootstrapped session holds O[k]'s inspection"); + drop(span); + let span = crate::profile::span("coord.evaluate"); let evaluation = self .task - .evaluate_transition( - &scope, - &old_observation.inspection, - &step_result.observation.inspection, - &controls, - ) + .evaluate_transition(&scope, &old_inspection, &new_inspection, &controls) .map_err(|e| { // Task interpretation failed after prepared brains and the world already // changed, so the epoch is failed rather than re-evaluated. @@ -1726,8 +2414,10 @@ impl Coordinator { } } + drop(span); // ---- Phase D: commit all agent outcomes concurrently self.transition(Phase::Committing(k))?; + let commit_span = crate::profile::span("coord.commit"); let new_views: BTreeMap = step_result .observation .sensory_views @@ -1746,10 +2436,12 @@ impl Coordinator { self.pending_audio.get(&name).map(|a| (name, a.clone())) }) .collect(); - let commits = self + let (commits, commit_attachments) = self .commit_all(k, &step_result.observation, &mut outcomes, &mut next_contexts, &new_views) .await?; + drop(commit_span); + let span = crate::profile::span("coord.boundary"); // Only once every commit succeeded does the committed boundary move. self.transition(Phase::Ready(k + 1))?; for index in 0..self.agents.len() { @@ -1786,9 +2478,54 @@ impl Coordinator { self.audio = new_audio; self.pending_views.clear(); self.pending_audio.clear(); + // O[k] has been evaluated, so its inspection is released; O[k+1]'s is the boundary's. + self.inspection_held = pending_inspection; + self.current_inspection = Some(new_inspection); self.observation = Some(step_result.observation.clone()); self.stats.advances += 1; + // The admissions this transition carried are applied: its Prepare committed. + let applied = std::mem::take(&mut self.in_flight_admissions); + // One lock for the end of the in-flight admissions and the new pulse: an edge thread + // never sees the admission gone and the old pulse still standing (TASK-01 review R2-3). + let pulses: Vec<(Id, Option)> = commits + .iter() + .map(|(agent_id, result)| (agent_id.clone(), result.telemetry.stimulus_remaining_ms)) + .collect(); + self.admissions + .commit(applied.clone(), AdmissionEnd::Applied { boundary: k + 1 }, &pulses); + let view_digests = if self.record_details { + self.view_digests(&step_result.observation).await? + } else { + Vec::new() + }; + + // ---- Ready(k+1): the boundary actions the transition asked for, saves first + // (`step-v1` section 6 amendment). + let mut boundary_actions = Vec::new(); + for slot_id in &evaluation.slot_saves { + let action = self.save_slot(k + 1, slot_id).await?; + boundary_actions.push(action); + } + let mut rollback_details = None; + if let Some(request) = &evaluation.episode + && request.kind == EpisodeRequestKind::Rollback + { + let request = request.clone(); + if self.defer_rollbacks { + // The host takes its captures at this boundary first (a milestone archive is + // captured after the slot save and before the rollback, legacy-gameboy-v1 + // section 16), then applies it: `apply_pending_rollback`. + self.pending_rollback = Some((k + 1, request)); + } else { + let (action, details) = self.apply_rollback(k + 1, &request).await?; + boundary_actions.push(action); + rollback_details = Some(details); + } + } + + drop(span); + let span = crate::profile::span("coord.trace_publish"); let event_ids: Vec = evaluation.events.iter().map(|e| e.id.clone()).collect(); let decisions: BTreeMap = prepared .iter() @@ -1803,7 +2540,23 @@ impl Coordinator { &step_result, &outcomes, &event_ids, + &boundary_actions, ); + if self.record_details { + self.last_details = Some(StepDetails { + step: k, + engine_frame: old_observation.engine_frame.clone(), + admissions: applied, + prepared: prepared.clone(), + controls: controls.clone(), + commits: commits.clone(), + commit_attachments, + view_digests, + evaluation: evaluation.clone(), + boundary_actions: boundary_actions.clone(), + rollback: rollback_details, + }); + } // The prepared decisions and their request ids are needed by the trace, so they are // released only after it has been recorded. for slot in &mut self.agents { @@ -1811,9 +2564,23 @@ impl Coordinator { slot.prepare_request = None; } self.publish_events(k + 1, &evaluation.events).await?; - self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?; + // Every boundary with events or boundary actions is published; otherwise every + // `snapshot_every`-th (1 unless the composition thins it, as the legacy feed publishes at + // `snapshot_hz`, 30 Hz, from a 60 Hz loop). + if self.snapshot_every <= 1 + || (k + 1).is_multiple_of(self.snapshot_every) + || !evaluation.events.is_empty() + || !boundary_actions.is_empty() + { + self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?; + } - let terminal = evaluation.episode.is_some(); + // A rollback request was applied above and is not an episode end; only a terminal one + // pauses the session for the episode policy. + let terminal = evaluation + .episode + .as_ref() + .is_some_and(|request| request.kind == EpisodeRequestKind::Terminal); if terminal { // A terminal event's final rewards are committed; then the session pauses at this // boundary and the declared episode policy runs. No worker resets itself. @@ -1825,8 +2592,10 @@ impl Coordinator { self.pause.store(false, std::sync::atomic::Ordering::SeqCst); self.audit.push(format!("pause:{}", k + 1)); } + drop(span); // The critical path: one whole transition, pacing sleep included. self.metrics.record("step", step_started.elapsed()); + self.trim_history(); Ok(StepReport { boundary: k + 1, paused, terminal }) } @@ -1857,17 +2626,44 @@ impl Coordinator { let scope = self.scope(k); // The task's per-agent decision contexts and the admitted pre-step stimulation list // are frozen here; anything accepted later waits for the next boundary. + let cut = self.admissions.cut(); + let mut admitted = Vec::new(); + for admission in cut { + if self.agent(admission.agent_id()).is_some() { + admitted.push(admission); + } else { + // An input for no configured agent is never applied; the edge refunds it. + self.admissions.end(vec![admission], AdmissionEnd::Aborted); + } + } + self.in_flight_admissions = admitted.clone(); let mut jobs = Vec::new(); let mut bodies = Vec::new(); for index in 0..self.agents.len() { let slot = &self.agents[index]; + let pre_step_stimulations: Vec = admitted + .iter() + .filter_map(|a| match a { + Admission::Stimulus { agent_id, interaction_id, kind_id, duration_ms } + if *agent_id == slot.agent_id => + { + Some(Stimulus { + id: interaction_id.clone(), + kind_id: kind_id.clone(), + duration_ms: *duration_ms, + }) + } + Admission::Stimulus { .. } => None, + }) + .collect(); let params = PrepareParams { agent_id: slot.agent_id.clone(), profile_digest: slot.profile.digest.clone(), interval, decision_context_digest: slot.context_digest.clone(), - // No audience input exists in the first synthetic composition. - pre_step_stimulations: Vec::::new(), + // What the admission cut admitted for this agent, in admission order. The + // synthetic composition has no audience input, so its list is empty. + pre_step_stimulations, }; let params = match params.to_json() { Value::Object(m) => m, @@ -1890,6 +2686,7 @@ impl Coordinator { params, attachments: Vec::new(), request_id, + want: Vec::new(), }); } let results = self.run_jobs(jobs, self.dispatch).await; @@ -1934,7 +2731,7 @@ impl Coordinator { method, )); } - if decision.decision.schema != crate::task::decision_schema() { + if decision.decision.schema != self.decision_schema { return Err(self.fail_now( DomainError::before( ErrorCode::IdentityMismatch, @@ -2009,7 +2806,11 @@ impl Coordinator { ) -> Outcome> { let scope = self.scope(k); let progress = self.task.progress(); - let clock = observation.world_time; + let _ = observation; + let inspection = self + .current_inspection + .clone() + .expect("a bootstrapped session holds O[k]'s inspection"); let mut intents: BTreeMap = BTreeMap::new(); // Sorted agent-id order, never completion order. for index in 0..self.agents.len() { @@ -2019,6 +2820,18 @@ impl Coordinator { .prepared .clone() .expect("every agent is Prepared before the batch is built"); + // `step-v1` section 3, Phase B amendment: the clock is the agent's brain time after + // its Prepare -- its executed ticks at its tick duration, exactly. + let tick = self.agents[index].tick_duration; + let clock = RationalNs::reduced( + u128::from(tick.numerator) * u128::from(decision.brain_ticks), + u128::from(tick.denominator), + ) + .map_err(|e| DomainError::invalid(e.0)); + let clock = match clock { + Ok(clock) => clock, + Err(e) => return Err(self.fail_now(e, "executor")), + }; let executor = self.executors.get_mut(&agent_id).ok_or_else(|| { DomainError::before( ErrorCode::IdentityMismatch, @@ -2032,7 +2845,7 @@ impl Coordinator { let applied = executor.apply( &scope, &decision.decision, - &observation.inspection, + &inspection, &progress, &clock, ); @@ -2101,7 +2914,7 @@ impl Coordinator { let worker = self.environment.clone(); let request_id = self.serials.next(&worker.service); self.last_advance_request = Some(request_id.clone()); - let want = self.media_names.clone(); + let want = self.wanted_media(); self.audit.push(format!("advance:{k}")); self.blame(Some(worker.worker_id.clone())); let advance_deadline = self.deadlines.probe; @@ -2223,7 +3036,9 @@ impl Coordinator { Err(e) => return Err(self.fail_now(e, "advance")), }; self.blame(None); - let (pending_views, pending_audio) = media::split_attachments(reply.artifacts); + let mut artifacts = reply.artifacts; + self.pending_inspection = self.take_inspection(&mut artifacts); + let (pending_views, pending_audio) = media::split_attachments(artifacts); self.pending_views = pending_views; self.pending_audio = pending_audio; @@ -2289,6 +3104,326 @@ impl Coordinator { } } +// ------------------------------------------------------------------------------------------- +// Boundary actions: slot saves and the declared rollback (`step-v1` section 6 amendment) + +/// The epoch a rollback moves to: the session's epoch root, then `.rb`, or a digest-named +/// id when that would pass the `Id` length bound. Deterministic, so two runs of the same +/// session name the same epochs. +fn rollback_epoch(current: &Id, n: u64) -> Id { + let root = match current.rfind(".rb") { + Some(at) if current[at + 3..].chars().all(|c| c.is_ascii_digit()) && at > 0 => { + ¤t[..at] + } + _ => current.as_str(), + }; + let named = format!("{root}.rb{n}"); + match parse_id(&named) { + Ok(epoch) => epoch, + Err(_) => { + let digest = digest_of_bytes(named.as_bytes()); + id(&format!("rb{n}-{}", &digest[..16])) + } + } +} + +impl Coordinator { + fn require_slots(&mut self, what: &str) -> Outcome<()> { + if self + .environment_capabilities + .iter() + .any(|c| c == fly_session_types::extensions::SLOTS_CAPABILITY) + { + return Ok(()); + } + Err(self.fail_now( + DomainError::new( + ErrorCode::Unsupported, + format!("the task asked for {what} and the world does not advertise gameboy-slots-v1"), + MutationCertainty::Applied, + ), + "boundary", + )) + } + + /// `Environment.SaveSlot` at the committed boundary `k`, under the current epoch. + async fn save_slot( + &mut self, + k: u64, + slot_id: &Id, + ) -> Outcome { + self.require_slots("a slot save")?; + let scope = self.scope(k); + let params = fly_session_types::extensions::SaveSlotParams { slot_id: slot_id.clone() }; + let worker = self.environment.clone(); + let reply = self + .call( + &worker, + fly_session_types::extensions::METHOD_SAVE_SLOT, + Some(scope.clone()), + object(params.to_json()), + &[], + &[], + ) + .await?; + let result: fly_session_types::extensions::SaveSlotResult = + reply.parse().map_err(|e| self.fail_now(e, "save-slot"))?; + if let Err(e) = result.validate_against_scope(&scope) { + return Err(self.fail_now(DomainError::invalid(e.0), "save-slot")); + } + if result.slot_id != *slot_id { + return Err(self.fail_now( + DomainError::before(ErrorCode::IdentityMismatch, "the world saved another slot"), + "save-slot", + )); + } + self.audit.push(format!("save-slot:{slot_id}@{k}")); + Ok(fly_session_types::trace::BoundaryAction { + kind: fly_session_types::trace::BoundaryActionKind::SaveSlot, + slot_id: slot_id.clone(), + state_digest: Some(result.state_digest), + }) + } + + /// The declared rollback policy at `Ready(e, k)` (`step-v1` section 6 amendment, steps 2 to + /// 5; `legacy-gameboy-v1` section 11): a new epoch, `Environment.RestoreSlot`, the task's + /// coordinator-local part, `Agent.Rollback` on every agent, then `Ready(e', k)`. Any failure + /// fails the epoch; nothing continues in `e` once one participant is in `e'`. + async fn apply_rollback( + &mut self, + k: u64, + request: &EpisodeRequest, + ) -> Outcome<(fly_session_types::trace::BoundaryAction, RollbackDetails)> { + let Some(policy) = self.rollback_policy.clone() else { + return Err(self.fail_now( + DomainError::new( + ErrorCode::Unsupported, + "the task asked for a rollback and this composition declares no rollback policy", + MutationCertainty::Applied, + ), + "rollback", + )); + }; + self.require_slots("a rollback")?; + let slot_id = match fly_session_types::gameboy::RollbackRequest::from_typed(&request.outcome) + { + Ok(outcome) => outcome.slot_id, + Err(e) => return Err(self.fail_now(DomainError::invalid(e.0), "rollback")), + }; + let slot_id = match parse_id(&slot_id) { + Ok(slot_id) => slot_id, + Err(e) => return Err(self.fail_now(DomainError::invalid(e), "rollback")), + }; + self.transition(Phase::RollingBack(k))?; + let prior = self.epoch.clone(); + self.rollbacks += 1; + let epoch = rollback_epoch(&prior, self.rollbacks); + let scope = scope_at(&self.session_id, &epoch, k); + + // Step 2: the world restores the slot at the same boundary under the new epoch. + let params = fly_session_types::extensions::RestoreSlotParams { + slot_id: slot_id.clone(), + prior_epoch: prior.clone(), + policy: policy.clone(), + }; + let worker = self.environment.clone(); + let want = self.wanted_media(); + let reply = self + .call( + &worker, + fly_session_types::extensions::METHOD_RESTORE_SLOT, + Some(scope.clone()), + object(params.to_json()), + &[], + &want, + ) + .await?; + let result: fly_session_types::extensions::RestoreSlotResult = + reply.parse().map_err(|e| self.fail_now(e, "restore-slot"))?; + if let Err(e) = result.validate_against_scope(&scope) { + return Err(self.fail_now(DomainError::invalid(e.0), "restore-slot")); + } + let descriptor = self.descriptor.clone().expect("bootstrapped"); + let restored = result.observation; + let world_time = self.observation.as_ref().map(|o| o.world_time); + if restored.boundary != k || Some(restored.world_time) != world_time { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + "a restored slot is not at the boundary and world time it was restored at", + ), + "restore-slot", + )); + } + if let Err(e) = restored.validate_against(&descriptor) { + return Err(self.fail_now( + DomainError::new(ErrorCode::BufferInvalid, e, MutationCertainty::Applied), + "restore-slot", + )); + } + if let Err(e) = media::check_required_views(&descriptor, &restored).and_then(|()| { + media::check_required_audio(&descriptor, &restored, media::ObservationOrigin::Installed) + }) { + return Err(self.fail_now(e, "restore-slot")); + } + let mut artifacts = reply.artifacts; + let held = self.take_inspection(&mut artifacts); + let (views, audio) = media::split_attachments(artifacts); + if !audio.is_empty() { + return Err(self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + "a restored slot carried an audio chunk; no interval was played", + MutationCertainty::Applied, + ), + "restore-slot", + )); + } + for view in &restored.sensory_views { + let name = media::view_attachment(&view.view_id); + match views.get(&name) { + Some(artifact) if artifact.reference() == &view.pixels => {} + _ => { + return Err(self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("the restored view {} arrived without a live owned handle", view.view_id), + MutationCertainty::Applied, + ), + "restore-slot", + )); + } + } + } + let inspection = self + .read_inspection(k, &restored.inspection, &held) + .await + .map_err(|e| self.fail_now(e, "restore-slot"))?; + self.audit.push(format!("restore-slot:{slot_id}@{k}:{epoch}")); + + // Step 3, coordinator-local: the task clears its transient observations, the executor + // cancels and observes the restored boundary, which gives the next contexts. + let evaluation = self + .task + .rollback(&scope, &inspection) + .map_err(|e| self.fail_now(e, "task-rollback"))?; + for agent_id in self.agent_ids() { + if !evaluation.next_contexts.contains_key(&agent_id) { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + format!("the task's rollback produced no context for {agent_id}"), + ), + "task-rollback", + )); + } + } + + // Step 4: every agent, with the restored view and its context. No tick. + let attachments: Vec<(String, flybus::Artifact)> = + views.iter().map(|(n, a)| (n.clone(), a.clone())).collect(); + let mut replies = Vec::new(); + for index in 0..self.agents.len() { + let agent_id = self.agents[index].agent_id.clone(); + let context = evaluation.next_contexts[&agent_id].clone(); + let params = fly_session_types::extensions::AgentRollbackParams { + agent_id: agent_id.clone(), + prior_epoch: prior.clone(), + policy: policy.clone(), + input: self.sensory_input(&restored, k), + decision_context: context.clone(), + }; + let worker = self.agents[index].worker.clone(); + let refs: Vec<(&str, &flybus::Artifact)> = + attachments.iter().map(|(n, a)| (n.as_str(), a)).collect(); + let reply = self + .call( + &worker, + fly_session_types::extensions::METHOD_AGENT_ROLLBACK, + Some(scope.clone()), + object(params.to_json()), + &refs, + &[], + ) + .await?; + let result: fly_session_types::extensions::AgentRollbackResult = + reply.parse().map_err(|e| self.fail_now(e, "agent-rollback"))?; + if let Err(e) = result.validate_against_scope(&scope) { + return Err(self.fail_now(DomainError::invalid(e.0), "agent-rollback")); + } + if result.agent_id != agent_id || result.decision_context_digest != context.digest() { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + "an agent rolled back with another identity or context", + ), + "agent-rollback", + )); + } + self.audit.push(format!("agent-rollback:{agent_id}@{k}:{epoch}")); + replies.push((agent_id, context, result)); + } + + // Step 5: every reply in hand. The session is at Ready(e', k). + let view_digests = if self.record_details { + let mut out = Vec::new(); + for view in &restored.sensory_views { + let name = media::view_attachment(&view.view_id); + if let Some(artifact) = views.get(&name) { + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("reading {name}: {}", e.message), + MutationCertainty::Applied, + ), + "details", + ) + })?; + out.push((view.view_id.clone(), digest_of_bytes(&bytes))); + } + } + out + } else { + Vec::new() + }; + self.epoch = epoch.clone(); + let positions = self.timelines.positions(); + self.timelines = match AudioTimelines::restored(&descriptor, &positions) { + Ok(timelines) => timelines, + Err(e) => return Err(self.fail_now(e, "rollback")), + }; + self.views = views; + self.audio.clear(); + self.inspection_held = held; + self.current_inspection = Some(inspection); + self.observation = Some(restored.clone()); + let mut agents = Vec::new(); + for (agent_id, context, result) in replies { + let slot = self + .agents + .iter_mut() + .find(|slot| slot.agent_id == agent_id) + .expect("configured"); + slot.context_digest = context.digest(); + slot.context = context; + slot.telemetry = Some(result.telemetry.clone()); + self.admissions.set_remaining(&agent_id, result.telemetry.stimulus_remaining_ms); + agents.push((agent_id, result)); + } + self.transition(Phase::Ready(k))?; + self.audit.push(format!("rolled-back:{slot_id}@{k}:{epoch}")); + Ok(( + fly_session_types::trace::BoundaryAction { + kind: fly_session_types::trace::BoundaryActionKind::Rollback, + slot_id: slot_id.clone(), + state_digest: None, + }, + RollbackDetails { epoch, observation: restored, view_digests, agents }, + )) + } +} + impl Coordinator { /// Phase C's verification: batch identity, boundary, cadence, schema and required views. #[allow(clippy::too_many_arguments)] @@ -2429,7 +3564,8 @@ impl Coordinator { outcomes: &mut BTreeMap, next_contexts: &mut BTreeMap, views: &BTreeMap, - ) -> Outcome> { + ) -> Outcome<(Vec<(Id, AgentCommitResult)>, Vec<(Id, String, Vec)>)> { + let mut extracted: Vec<(Id, String, Vec)> = Vec::new(); let scope = self.scope(k); let attachments: Vec<(String, flybus::Artifact)> = views.iter().map(|(n, a)| (n.clone(), a.clone())).collect(); @@ -2481,6 +3617,7 @@ impl Coordinator { params, attachments: attachments.clone(), request_id, + want: self.commit_attachments.clone(), }); } self.last_commit_requests = bodies @@ -2519,7 +3656,7 @@ impl Coordinator { params, job_attachments, request_id, - &[], + &self.commit_attachments.clone(), ) .await { @@ -2569,6 +3706,29 @@ impl Coordinator { if let Err(e) = result.telemetry.validate() { return Err(self.fail_now(DomainError::invalid(e), method)); } + for name in self.commit_attachments.clone() { + let Some(artifact) = reply.artifacts.get(&name) else { + return Err(self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("Agent.Commit carried no {name}"), + MutationCertainty::Applied, + ), + method, + )); + }; + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("reading {name}: {}", e.message), + MutationCertainty::Applied, + ), + method, + ) + })?; + extracted.push((agent_id.clone(), name, bytes)); + } self.audit.push(format!("committed:{agent_id}@{k}")); self.stats.commits += 1; self.blame(None); @@ -2625,7 +3785,7 @@ impl Coordinator { } } commits.sort_by(|a, b| a.0.cmp(&b.0)); - Ok(commits) + Ok((commits, extracted)) } /// Records the `step-v1` section 8 trace for this transition. @@ -2645,6 +3805,7 @@ impl Coordinator { result: &StepResult, outcomes: &BTreeMap, event_ids: &[Id], + boundary_actions: &[fly_session_types::trace::BoundaryAction], ) { let mut agents = Vec::new(); let mut outcome_ids = Vec::new(); @@ -2695,8 +3856,9 @@ impl Coordinator { outcome_ids, event_ids: event_ids.to_vec(), published_boundary: k + 1, - // The synthetic composition takes no boundary actions (step-v1 section 8 amendment). - boundary_actions: Vec::new(), + // Saves first, each slot once, at most one rollback, last (step-v1 section 8 + // amendment). The synthetic composition takes none. + boundary_actions: boundary_actions.to_vec(), }; let operational = TraceOperational { // Wall time is for pacing, health and presentation only. @@ -3125,7 +4287,7 @@ impl Coordinator { /// The live composition's compatibility identities. pub fn compatibility(&self) -> Outcome { match &self.descriptor { - Some(descriptor) => Ok(crate::state::Compatibility::of(descriptor)), + Some(descriptor) => Ok(self.world_compatibility(descriptor)), None => Err(SessionFailure { error: DomainError::before( ErrorCode::InvalidPhase, @@ -3160,8 +4322,8 @@ impl Coordinator { &slot.agent_id, &slot.profile.digest, &graph.dataset_digest, - crate::agent::MODEL_VERSION, - crate::agent::PLASTICITY_VERSION, + &slot.model_version, + &slot.plasticity_version, slot.seed, &graph.index_digest, )) @@ -3393,8 +4555,8 @@ impl Coordinator { profile_digest: slot.profile.digest.clone(), dataset_digest: graph.dataset_digest, index_digest: graph.index_digest, - model_version: crate::agent::MODEL_VERSION.to_owned(), - plasticity_version: crate::agent::PLASTICITY_VERSION.to_owned(), + model_version: slot.model_version.clone(), + plasticity_version: slot.plasticity_version.clone(), seed: slot.seed, brain_ticks: slot.brain_ticks, remainder: slot.remainder, @@ -3409,6 +4571,22 @@ impl Coordinator { self.seal_own(crate::state::TASK_LEDGER_PAYLOAD, &ledger.to_json()) .await?, ); + let attachments = + self.task.capture_attachments().map_err(|e| self.fail_now(e, "capture"))?; + for (name, bytes) in attachments { + let name = crate::state::task_attachment_payload(&name); + let digest = digest_of_bytes(&bytes); + let artifact = match crate::state::seal_payload(&self.bus, &bytes, &digest).await { + Ok(artifact) => artifact, + Err(e) => return Err(self.fail_now(e, "capture")), + }; + payloads.push(crate::state::CapturedPayload { + name, + byte_length: bytes.len() as u64, + digest, + artifact, + }); + } let inspection = self .observation .as_ref() @@ -3693,8 +4871,13 @@ impl Coordinator { /// A replacement is the only way a fenced participant comes back: `step-v1` section 7's /// incarnation row says every live participant of a failed epoch belongs to an invalid /// one, so the reference is exchanged deliberately here and never repaired in place. + /// + /// A session that bootstrapped and has taken no transition may also replace a participant: + /// that is how a checkpoint of another format is installed as its start + /// ([`Coordinator::import`]) into a world that stages only on a fresh replacement. pub fn replace_participant(&mut self, worker_id: &Id, worker: WorkerRef) -> Outcome<()> { - if !self.fenced { + let unstarted = self.phases.phase() == Phase::Ready(0) && self.stats.advances == 0; + if !self.fenced && !unstarted { return Err(self.fail_now( DomainError::before( ErrorCode::InvalidPhase, @@ -3813,13 +4996,214 @@ impl Coordinator { } let boundary = manifest.source_scope.step; self.transition(Phase::Restoring(boundary))?; - let outcome = self.restore_group(&envelope, &manifest, new_epoch, boundary).await; + let outcome = self.restore_group(&envelope.payloads, &manifest, new_epoch, boundary).await; match outcome { Ok(report) => Ok(report), Err(e) => Err(e), } } + pub fn session_id(&self) -> &Id { + &self.session_id + } + + /// Installs a checkpoint of another format as this session's start (TASK-01: the legacy + /// composition's FLYSIM01 import). + /// + /// Only a session that bootstrapped and has taken no transition may import, and the install + /// is the ordinary group restore of `state-media-v1` section 6 -- stage every participant, + /// validate the coordinator's own state, activate, install, `Paused(k)` -- over payloads the + /// importer assembled in each participant's own capture format. The coordinator's own + /// payloads (executor state, prior inspection, the admission record) are written here, from + /// the live composition, exactly as a capture writes them. Nothing a participant stages is + /// trusted: each validates its payload as it would one of its own captures. + pub async fn import(&mut self, spec: ImportSpec, new_epoch: &Id) -> Outcome { + if self.fenced || self.phases.phase() != Phase::Ready(0) || self.stats.advances != 0 { + return Err(self.fail_now( + DomainError::before( + ErrorCode::InvalidPhase, + "a checkpoint is imported as the start of a session that has taken no transition", + ), + "import", + )); + } + if *new_epoch == self.epoch { + return Err(self.fail_now( + DomainError::before(ErrorCode::StaleEpoch, "an import installs a fresh epoch"), + "import", + )); + } + let descriptor = self.descriptor.clone().expect("bootstrapped"); + let boundary = spec.boundary; + if spec.source_scope.step != boundary || spec.source_scope.session_id != self.session_id { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + "an import's source scope is this session at the imported boundary", + ), + "import", + )); + } + let world_time = RationalNs::reduced( + u128::from(descriptor.step_duration.numerator) * u128::from(boundary), + u128::from(descriptor.step_duration.denominator), + ) + .map_err(|e| DomainError::invalid(e.0)); + let world_time = match world_time { + Ok(time) => time, + Err(e) => return Err(self.fail_now(e, "import")), + }; + let recorded: Vec = spec.agents.iter().map(|a| a.agent_id.clone()).collect(); + if recorded != self.agent_ids() { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + "the import's agents are not this composition's", + ), + "import", + )); + } + let compatibility = self.compatibility()?; + let canonical = |value: &Value| -> DomainResult> { + canonicalize(value) + .map(String::into_bytes) + .map_err(|e| DomainError::invalid(e.0)) + }; + let mut payloads: Vec<(String, Vec)> = Vec::new(); + payloads.push((crate::state::WORLD_PAYLOAD.to_owned(), spec.world_payload)); + let mut agent_rows = Vec::new(); + for imported in &spec.agents { + let slot = self.agent(&imported.agent_id).expect("checked"); + let Some(graph) = slot.graph.clone() else { + return Err(self.fail_now( + DomainError::before(ErrorCode::InvalidPhase, "an agent attested no graph"), + "import", + )); + }; + let name = crate::state::agent_payload(&imported.agent_id); + agent_rows.push(crate::state::AgentEntry { + agent_id: imported.agent_id.clone(), + profile_digest: slot.profile.digest.clone(), + dataset_digest: graph.dataset_digest, + index_digest: graph.index_digest, + model_version: slot.model_version.clone(), + plasticity_version: slot.plasticity_version.clone(), + seed: slot.seed, + brain_ticks: imported.brain_ticks, + remainder: imported.remainder, + payload: name.clone(), + }); + payloads.push((name, imported.payload.clone())); + } + let mut own = |name: &str, value: &Value| -> DomainResult<()> { + payloads.push((name.to_owned(), canonical(value)?)); + Ok(()) + }; + let mut executor_rows = Vec::new(); + let mut failure = None; + if let Err(e) = own(crate::state::TASK_LEDGER_PAYLOAD, &spec.task_ledger.to_json()) { + failure = Some(e); + } + let prior = self.observation.as_ref().map(|o| o.inspection.to_json()).expect("bootstrapped"); + if let Err(e) = own(crate::state::PRIOR_INSPECTION_PAYLOAD, &prior) { + failure = failure.or(Some(e)); + } + for agent_id in self.agent_ids() { + let name = crate::state::executor_payload(&agent_id); + match self.executors.get(&agent_id).map(|e| e.capture()) { + Some(Ok(state)) => { + if let Err(e) = own(&name, &state.to_json()) { + failure = failure.or(Some(e)); + } + } + Some(Err(e)) => failure = failure.or(Some(e)), + None => { + failure = failure.or(Some(DomainError::before( + ErrorCode::IdentityMismatch, + format!("{agent_id} has no configured action executor"), + ))) + } + } + executor_rows.push((agent_id, name)); + } + let record = json!({ + "payloadVersion": 1, + "kind": "coordinator", + "committedStep": boundary.to_string(), + "admission": {"audienceInput": "none-configured", "admitted": Value::Array(Vec::new())}, + "eventWatermarks": {"lastSourceStep": "0", "issued": "0"}, + "audioPositions": Value::Object( + spec.audio_positions + .iter() + .map(|(stream, sample)| (stream.clone(), Value::String(sample.to_string()))) + .collect(), + ), + "agents": Value::Array( + spec.agents + .iter() + .map(|imported| { + let slot = self.agent(&imported.agent_id).expect("checked"); + json!({ + "agentId": imported.agent_id.as_str(), + "portId": slot.port_id.as_str(), + "profile": slot.profile.to_json(), + "seed": slot.seed, + "workerThreads": slot.worker_threads.to_string(), + "committedStep": boundary.to_string(), + "brainTicks": imported.brain_ticks.to_string(), + "remainder": imported.remainder.to_json(), + "context": imported.context.to_json(), + }) + }) + .collect(), + ), + }); + if let Err(e) = own(crate::state::ADMISSION_PAYLOAD, &record) { + failure = failure.or(Some(e)); + } + for (name, bytes) in &spec.task_attachments { + payloads.push((crate::state::task_attachment_payload(name), bytes.clone())); + } + if let Some(e) = failure { + return Err(self.fail_now(e, "import")); + } + let manifest = crate::state::CheckpointManifest { + checkpoint_id: spec.checkpoint_id.clone(), + source_scope: spec.source_scope.clone(), + episode_id: self.episode_id.clone(), + world_time, + scheduler_id: "lockstep-v1".to_owned(), + composition_digest: self.composition_digest(), + port_map: self + .agents + .iter() + .map(|slot| (slot.port_id.clone(), slot.agent_id.clone())) + .collect(), + compatibility, + agents: agent_rows, + coordinator: crate::state::CoordinatorEntry { + task_ledger: crate::state::TASK_LEDGER_PAYLOAD.to_owned(), + prior_inspection: crate::state::PRIOR_INSPECTION_PAYLOAD.to_owned(), + executor_state: executor_rows, + admission_state: crate::state::ADMISSION_PAYLOAD.to_owned(), + event_watermarks: crate::state::EventWatermarks { last_source_step: 0, issued: 0 }, + }, + environment: crate::state::EnvironmentEntry { + worker_id: self.environment.worker_id.clone(), + payload: crate::state::WORLD_PAYLOAD.to_owned(), + }, + helper_state: Vec::new(), + payloads: payloads + .iter() + .map(|(name, bytes)| (name.clone(), bytes.len() as u64, digest_of_bytes(bytes))) + .collect(), + }; + self.transition(Phase::Restoring(boundary))?; + let report = self.restore_group(&payloads, &manifest, new_epoch, boundary).await?; + self.audit.push(format!("imported:{}@{boundary}", spec.checkpoint_id)); + Ok(report) + } + /// Marks every participant of an abandoned group install as one that must be replaced. /// /// A participant that staged holds a replacement state nothing installed; one that @@ -3866,7 +5250,7 @@ impl Coordinator { )); } let live = match &self.descriptor { - Some(descriptor) => crate::state::Compatibility::of(descriptor), + Some(descriptor) => self.world_compatibility(descriptor), None => { return Err(DomainError::before( ErrorCode::InvalidPhase, @@ -3921,7 +5305,7 @@ impl Coordinator { #[allow(clippy::too_many_lines)] async fn restore_group( &mut self, - envelope: &fly_session_types::checkpoint::Envelope, + envelope_payloads: &[(String, Vec)], manifest: &crate::state::CheckpointManifest, new_epoch: &Id, boundary: u64, @@ -3930,7 +5314,7 @@ impl Coordinator { // Step 3: import the payloads as *new* artifacts. Nothing the fence dropped is asked // to come back, and a router that restarted has none of the old roots anyway. let mut imported: BTreeMap = BTreeMap::new(); - for (name, bytes) in &envelope.payloads { + for (name, bytes) in envelope_payloads { let digest = digest_of_bytes(bytes); let artifact = match crate::state::seal_payload(&self.bus, bytes, &digest).await { Ok(artifact) => artifact, @@ -4043,8 +5427,7 @@ impl Coordinator { // coordinator** state validates". The coordinator's own staged ledgers are checked // here, before a single token is activated, so a checkpoint whose task ledger or // executor state is unreadable installs nothing anywhere. - let payloads: BTreeMap> = envelope - .payloads + let payloads: BTreeMap> = envelope_payloads .iter() .map(|(name, bytes)| (name.clone(), bytes.clone())) .collect(); @@ -4078,10 +5461,11 @@ impl Coordinator { let mut activated: Vec = Vec::new(); let mut restored_observation: Option<(WorldObservation, BTreeMap)> = None; + let mut restored_inspection: BTreeMap = BTreeMap::new(); for (who, worker, token) in &staged { let params = ActivateRestoreParams { restore_token: token.clone() }; let want = if *who == self.environment.worker_id { - self.media_names.clone() + self.wanted_media() } else { Vec::new() }; @@ -4129,7 +5513,9 @@ impl Coordinator { )); } if let Some(observation) = result.observation { - let (views, audio) = media::split_attachments(reply.artifacts); + let mut artifacts = reply.artifacts; + restored_inspection = self.take_inspection(&mut artifacts); + let (views, audio) = media::split_attachments(artifacts); if !audio.is_empty() { self.taint_group(&staged); return Err(self.fail_now( @@ -4172,6 +5558,69 @@ impl Coordinator { self.taint_group(&staged); return Err(self.fail_now(e, "restore")); } + // The restored boundary's inspection, and the task's own look at it: a task whose + // executor state is transient (`legacy-transient-reset`) re-observes the restored world + // here, and the contexts it derives must be the ones the checkpoint recorded -- the + // agents hold those, and a Prepare under another would be refused. + let restored_value = self + .observation + .as_ref() + .map(|o| o.inspection.clone()) + .expect("installed above"); + let inspection = match self.read_inspection(boundary, &restored_value, &restored_inspection).await + { + Ok(inspection) => inspection, + Err(e) => { + self.taint_group(&staged); + return Err(self.fail_now(e, "restore")); + } + }; + let clock = match self.agents.first() { + Some(slot) => RationalNs::reduced( + u128::from(slot.tick_duration.numerator) * u128::from(slot.brain_ticks), + u128::from(slot.tick_duration.denominator), + ) + .unwrap_or(RationalNs::ZERO), + None => RationalNs::ZERO, + }; + let restored_scope = scope_at(&self.session_id, new_epoch, boundary); + match self.task.restored(&restored_scope, &inspection, &clock) { + Ok(Some(contexts)) => { + let differing = self + .agents + .iter() + .find(|slot| { + contexts.get(&slot.agent_id).map(TypedValue::digest) + != Some(slot.context_digest.clone()) + }) + .map(|slot| slot.agent_id.clone()); + if let Some(agent_id) = differing { + { + self.taint_group(&staged); + return Err(self.fail_now( + DomainError::before( + ErrorCode::IncompatibleState, + format!( + "the restored world gives {} another decision context than the \ + checkpoint recorded", + agent_id + ), + ), + "restore", + )); + } + } + } + Ok(None) => {} + Err(e) => { + self.taint_group(&staged); + return Err(self.fail_now(e, "restore")); + } + } + self.inspection_held = restored_inspection; + self.current_inspection = Some(inspection); + // The pulse is unknown until the new epoch's first commit (`legacy-gameboy-v1` 15). + self.admissions.forget_remaining(); // Step 5: Paused(k), and only now is the fence lifted. self.epoch = new_epoch.clone(); @@ -4231,7 +5680,7 @@ impl Coordinator { &manifest.coordinator.task_ledger, )?) .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; - task.validate_restore(&ledger)?; + task.validate_restore_with(&ledger, &crate::state::task_attachments(payloads))?; for (agent_id, name) in &manifest.coordinator.executor_state { let state = TypedValue::from_json(&Coordinator::read_payload(payloads, name)?) .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; @@ -4332,7 +5781,8 @@ impl Coordinator { let ledger = TypedValue::from_json(&read(&manifest.coordinator.task_ledger)?) .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; - self.task.validate_restore(&ledger)?; + let task_attachments = crate::state::task_attachments(payloads); + self.task.validate_restore_with(&ledger, &task_attachments)?; for (agent_id, name) in &manifest.coordinator.executor_state { let state = TypedValue::from_json(&read(name)?) .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; @@ -4398,7 +5848,7 @@ impl Coordinator { audio_positions.insert(stream.clone(), sample); } // Everything above validated. From here the coordinator installs, in one pass. - self.task.install_restore(new_epoch, &ledger)?; + self.task.install_restore_with(new_epoch, &ledger, &task_attachments)?; for (agent_id, name) in &manifest.coordinator.executor_state { let state = TypedValue::from_json(&read(name)?) .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; @@ -4522,3 +5972,71 @@ impl Coordinator { }) } } + +#[cfg(test)] +mod admission_race_tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + + /// TASK-01 review R2-3: a sugar arriving while a commit ends the in-flight admission and + /// reports the pulse must never see "no pending admission" beside the old, over pulse. The + /// only state the hammer accepts in is exactly that torn one; the commit under test is + /// atomic, so it is never seen. + #[test] + fn no_sugar_is_admitted_between_a_commit_ending_and_its_pulse() { + let queue = AdmissionQueue::default(); + let agent = id("fly"); + let in_flight = Admission::Stimulus { + agent_id: agent.clone(), + interaction_id: id("sugar-1"), + kind_id: id("reward-pulse"), + duration_ms: 400.0, + }; + let stop = AtomicBool::new(false); + let torn = AtomicBool::new(false); + std::thread::scope(|scope| { + scope.spawn(|| { + while !stop.load(Ordering::Relaxed) { + let admitted = queue.admit_with(&agent, |remaining, pending| { + if remaining.unwrap_or(0.0).max(pending.unwrap_or(0.0)) > 0.0 { + Err(()) + } else { + Ok(Admission::Stimulus { + agent_id: agent.clone(), + interaction_id: id("sugar-x"), + kind_id: id("reward-pulse"), + duration_ms: 1.0, + }) + } + }); + if admitted.is_ok() { + torn.store(true, Ordering::Relaxed); + return; + } + } + }); + for _ in 0..200_000 { + if torn.load(Ordering::Relaxed) { + break; + } + // The state after a cut: the sugar is in flight and the last pulse is over. + { + let mut state = queue.lock(); + state.queued.clear(); + state.in_flight = vec![in_flight.clone()]; + state.set_remaining(&agent, Some(0.0)); + } + queue.commit( + vec![in_flight.clone()], + AdmissionEnd::Applied { boundary: 1 }, + &[(agent.clone(), Some(400.0))], + ); + } + stop.store(true, Ordering::Relaxed); + }); + assert!( + !torn.load(Ordering::Relaxed), + "a sugar was admitted into a live pulse in the commit's window" + ); + } +} diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index 3367247..b6fbd37 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -312,6 +312,43 @@ pub fn encode_payload( encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string()) } +/// A capture's inputs, copied at the boundary so the encoding can run off the endpoint's lock. +struct CaptureSnapshot { + state: AgentState, + agent_id: Id, + checkpoint_id: Id, + scope: Scope, + committed_step: u64, + profile: AssetRef, + seed: i32, + reinforcements: u64, + macro_channels: Vec, + accumulator: TickAccumulator, + context: TypedValue, +} + +impl CaptureSnapshot { + fn encode(&self) -> DomainResult> { + encode_payload( + &self.state, + &PayloadIdentity { + agent_id: &self.agent_id, + checkpoint_id: &self.checkpoint_id, + source_scope: &self.scope, + committed_step: self.committed_step, + profile: &self.profile, + seed: self.seed, + reinforcements: self.reinforcements, + macro_channels: &self.macro_channels, + }, + &self.accumulator, + &self.context, + None, + ) + .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None)) + } +} + /// The reinforcement calls a `FLYAGT01` capture payload records (`learning.updates`). pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result { let parts = decode_envelope(bytes, PAYLOAD_MAGIC) @@ -1005,7 +1042,9 @@ impl LegacyAgentWorker { let brain_ticks = accumulator.brain_ticks(); let remainder = accumulator.remainder(); self.transition_start_ms = agent.network.ms; + let ticks_span = crate::profile::span("agent.ticks"); agent.network.step(ticks); + drop(ticks_span); if agent.network.ms != brain_ticks as f64 { return Err(applied( ErrorCode::Internal, @@ -1110,7 +1149,9 @@ impl LegacyAgentWorker { } let context = self.read_context(¶ms.next_decision_context)?; // The complete request and its owned artifact are validated before anything applies. + let read_span = crate::profile::span("agent.read_lcd"); let frame = self.read_lcd(ctx, ¶ms.next_input).await?; + drop(read_span); self.status.set_state(WorkerState::Committing); let agent = self.agent.as_mut().expect("initialized"); @@ -1139,7 +1180,9 @@ impl LegacyAgentWorker { self.transient.location = Some(location); self.transient.blocked_since_ms = ms; } + let spikes_span = crate::profile::span("agent.spikes"); let spikes = spike_bitset(&agent.network.last_spike_ms, self.transition_start_ms, ms); + drop(spikes_span); // 4. Retain the next context and acknowledge k+1. let digest = context.digest.clone(); self.context = Some(context); @@ -1152,6 +1195,7 @@ impl LegacyAgentWorker { decision_context_digest: digest, telemetry: self.telemetry(), }; + let _seal_span = crate::profile::span("agent.seal_spikes"); let artifact = crate::media::seal_copy(ctx.client, SPIKES_CONTENT_TYPE.to_owned(), &spikes) .await .map_err(|e| applied(e.code, e.message))?; @@ -1273,7 +1317,8 @@ impl LegacyAgentWorker { /// 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> { + /// Everything a capture payload is encoded from, copied out of the live agent. + fn snapshot(&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"); @@ -1281,23 +1326,19 @@ impl LegacyAgentWorker { // The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`). state.remainder = rational_remainder_to_legacy(&accumulator.remainder()) .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?; - encode_payload( - &state, - &PayloadIdentity { - agent_id: &self.config.agent_id, - checkpoint_id, - source_scope: scope, - committed_step: k, - profile: &self.profile.asset, - seed: self.seed, - reinforcements: self.reinforcements, - macro_channels: &self.config.macro_channels, - }, - accumulator, - &context.typed, - None, - ) - .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None)) + Ok(CaptureSnapshot { + state, + agent_id: self.config.agent_id.clone(), + checkpoint_id: checkpoint_id.clone(), + scope: scope.clone(), + committed_step: k, + profile: self.profile.asset.clone(), + seed: self.seed, + reinforcements: self.reinforcements, + macro_channels: self.config.macro_channels.clone(), + accumulator: accumulator.clone(), + context: context.typed.clone(), + }) } async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { @@ -1323,36 +1364,50 @@ impl LegacyAgentWorker { )); } 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); - } + // The boundary's state, taken under the endpoint's lock: a copy, as the legacy loop's + // `export_state` is. Encoding, digesting and sealing it -- milliseconds on the full + // connectome -- run after the lock is released (`HandlerReply::deferred`), so the next + // Prepare does not wait for them (TASK-01 review N5). + let snapshot = { + let _span = crate::profile::span("agent.capture.snapshot"); + self.snapshot(¶ms.checkpoint_id, &scope, k)? }; - 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)], - )) + let compatibility = compatibility_digest( + &self.config.agent_id, + &self.profile.asset, + graph, + self.seed, + ); + let client = ctx.client.clone(); + Ok(HandlerReply::deferred(Box::pin(async move { + let bytes = tokio::task::spawn_blocking(move || { + let _span = crate::profile::span("agent.capture.encode"); + let bytes = snapshot.encode()?; + let digest = { + let _span = crate::profile::span("agent.capture.digest"); + digest_of_bytes(&bytes) + }; + Ok::<_, DomainError>((bytes, digest)) + }) + .await + .map_err(|e| DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None))?; + let (bytes, digest) = bytes?; + let artifact = { + let _span = crate::profile::span("agent.capture.seal"); + crate::state::seal_payload(&client, &bytes, &digest).await? + }; + let result = CaptureResult { + checkpoint_id: params.checkpoint_id, + boundary: k, + compatibility_digest: compatibility, + 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 { diff --git a/services/flysim/crates/fly-session/src/legacy_env.rs b/services/flysim/crates/fly-session/src/legacy_env.rs index a423c70..e70b996 100644 --- a/services/flysim/crates/fly-session/src/legacy_env.rs +++ b/services/flysim/crates/fly-session/src/legacy_env.rs @@ -857,10 +857,33 @@ impl LegacyGameboyEnvironment { client: &flybus::Client, audio: Option>, ) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> { - let frame = - media::seal_copy(client, FRAME_CONTENT_TYPE.to_owned(), &live.framebuffer).await?; - let image = memory_image(&mut live.emulator).map_err(backend_failure)?; - let memory = media::seal_copy(client, MEMORY_CONTENT_TYPE.to_owned(), &image).await?; + let image = { + let _span = crate::profile::span("env.image"); + memory_image(&mut live.emulator).map_err(backend_failure)? + }; + if let Some(raw) = &audio + && raw.len() % AUDIO_CHANNELS as usize != 0 + { + return Err(backend_failure("binjgb returned half a stereo frame")); + } + let audio_f32 = audio.as_deref().map(audio_f32le); + // The three artifacts are independent: they are sealed concurrently, so the boundary + // waits for the router's round trips once rather than three times. + let seal_span = crate::profile::span("env.seal"); + let (frame, memory, samples) = tokio::join!( + media::seal_copy(client, FRAME_CONTENT_TYPE.to_owned(), &live.framebuffer), + media::seal_copy(client, MEMORY_CONTENT_TYPE.to_owned(), &image), + async { + match &audio_f32 { + Some(bytes) => media::seal_copy(client, AUDIO_CONTENT_TYPE.to_owned(), bytes) + .await + .map(Some), + None => Ok(None), + } + } + ); + drop(seal_span); + let (frame, memory, samples) = (frame?, memory?, samples?); let view = ViewRef { view_id: gameboy::VIEW_ID.to_owned(), produced_step: live.boundary, @@ -876,13 +899,8 @@ impl LegacyGameboyEnvironment { (MEMORY_ATTACHMENT.to_owned(), memory), ]; let mut chunks = Vec::new(); - if let Some(raw) = audio { - if raw.len() % AUDIO_CHANNELS as usize != 0 { - return Err(backend_failure("binjgb returned half a stereo frame")); - } + if let (Some(raw), Some(samples)) = (audio, samples) { let frames = (raw.len() / AUDIO_CHANNELS as usize) as u64; - let samples = - media::seal_copy(client, AUDIO_CONTENT_TYPE.to_owned(), &audio_f32le(&raw)).await?; chunks.push(AudioRef { stream_id: id(AUDIO_STREAM_ID), first_sample: live.audio_next_sample, @@ -1030,6 +1048,7 @@ impl LegacyGameboyEnvironment { let applied_from = live.boundary; // `LegacyFrame::run` and `take_frame`: the joypad, one frame, the frame it drew, its audio. + let frame_span = crate::profile::span("env.frame"); live.buttons = mask; live.emulator.set_buttons(mask); live.emulator @@ -1039,6 +1058,7 @@ impl LegacyGameboyEnvironment { live.framebuffer .copy_from_slice(live.emulator.framebuffer()); let audio = live.emulator.take_audio_u8(); + drop(frame_span); live.boundary += 1; live.world_time = live .world_time diff --git a/services/flysim/crates/fly-session/src/lib.rs b/services/flysim/crates/fly-session/src/lib.rs index 63edd03..ad32a6c 100644 --- a/services/flysim/crates/fly-session/src/lib.rs +++ b/services/flysim/crates/fly-session/src/lib.rs @@ -38,6 +38,7 @@ pub mod measure; pub mod media; pub mod metrics; pub mod phase; +pub mod profile; pub mod publish; pub mod rpc; pub mod state; diff --git a/services/flysim/crates/fly-session/src/metrics.rs b/services/flysim/crates/fly-session/src/metrics.rs index fd5d1a3..a226ce8 100644 --- a/services/flysim/crates/fly-session/src/metrics.rs +++ b/services/flysim/crates/fly-session/src/metrics.rs @@ -79,6 +79,16 @@ impl Metrics { pub fn clear(&mut self) { self.samples.clear(); } + + /// Bounds every path to between `keep` and `2 * keep` of its newest samples (trimmed in + /// batches, so a long run does not shift the vector every step). + pub fn truncate(&mut self, keep: usize) { + for values in self.samples.values_mut() { + if values.len() > 2 * keep { + values.drain(..values.len() - keep); + } + } + } } /// This process's peak resident set, in KiB, from its own status file. diff --git a/services/flysim/crates/fly-session/src/phase.rs b/services/flysim/crates/fly-session/src/phase.rs index f528112..235576a 100644 --- a/services/flysim/crates/fly-session/src/phase.rs +++ b/services/flysim/crates/fly-session/src/phase.rs @@ -9,6 +9,8 @@ //! Ready(k) / Paused(k) -> Capturing(k) -> same boundary //! any unresolved partial failure -> Failed -> Restoring(new epoch) -> Paused(k) //! terminal episode -> Paused(k) -> Resetting(new epoch) -> Ready(0) +//! declared rollback: Ready(e, k) -> RollingBack(e', k) -> Ready(e', k) +//! checkpoint as the start: Ready(0), no transition taken -> Restoring(k) -> Paused(k) //! ``` //! //! A transition the table does not list is a bug, not a recoverable condition, so it returns @@ -34,6 +36,9 @@ pub enum Phase { Restoring(u64), /// `Resetting(k)`: leaving boundary `k` for a new epoch and episode at step 0. Resetting(u64), + /// A declared rollback policy running at a committed boundary (`step-v1` section 2 + /// amendment of 2026-09-23): same boundary, new epoch, no capture. + RollingBack(u64), } impl Phase { @@ -50,6 +55,7 @@ impl Phase { Phase::Failed => "Failed".to_owned(), Phase::Restoring(k) => format!("Restoring({k})"), Phase::Resetting(k) => format!("Resetting({k})"), + Phase::RollingBack(k) => format!("RollingBack({k})"), } } @@ -115,6 +121,14 @@ impl PhaseMachine { (Restoring(k), Paused(j)) => k == j, (Paused(k), Resetting(j)) => k == j, (Resetting(_), Ready(0)) => true, + // `step-v1` section 2, amendment of 2026-09-23: `Ready(e, k) -> RollingBack(e', k) + // -> Ready(e', k)`. The epoch changes, which is the coordinator's; the boundary + // does not. + (Ready(k), RollingBack(j)) | (RollingBack(k), Ready(j)) => k == j, + // A session that bootstrapped and has taken no transition may install a checkpoint + // as its start: the legacy composition's FLYSIM01 import (TASK-01). The install is + // the group restore of `state-media-v1` section 6 and ends `Paused(k)` like one. + (Ready(0), Restoring(_)) => true, _ => false, } } @@ -150,6 +164,21 @@ impl PhaseMachine { mod tests { use super::*; + #[test] + fn a_rollback_keeps_its_boundary_and_an_import_starts_from_an_unstepped_zero() { + let mut m = PhaseMachine::new(); + m.to(Phase::Ready(0)).unwrap(); + m.to(Phase::Restoring(40)).unwrap(); + m.to(Phase::Paused(40)).unwrap(); + m.to(Phase::Ready(40)).unwrap(); + assert!(m.to(Phase::RollingBack(41)).is_err(), "a rollback keeps the boundary"); + m.to(Phase::RollingBack(40)).unwrap(); + assert!(m.to(Phase::Capturing(40)).is_err(), "no capture inside a rollback"); + assert!(m.to(Phase::Preparing(40)).is_err(), "no Prepare before every reply"); + m.to(Phase::Ready(40)).unwrap(); + assert!(m.to(Phase::Restoring(3)).is_err(), "only boundary 0 may take a start"); + } + #[test] fn the_happy_path_walks_the_section_2_diagram() { let mut m = PhaseMachine::new(); diff --git a/services/flysim/crates/fly-session/src/profile.rs b/services/flysim/crates/fly-session/src/profile.rs new file mode 100644 index 0000000..2e68b18 --- /dev/null +++ b/services/flysim/crates/fly-session/src/profile.rs @@ -0,0 +1,60 @@ +//! A switchable per-phase timer for measuring the session runtime (TASK-01 review N5). +//! +//! Off unless `FLY_SESSION_PROFILE` is set when the process starts; off, a span is one relaxed +//! atomic load. On, every span adds its duration to a process-wide table that [`report`] reads. +//! In-process execution puts the coordinator and every worker in one table; a worker process +//! keeps its own. Not a service metric: a measurement tool. + +use std::collections::BTreeMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::time::{Duration, Instant}; + +static STATE: AtomicU8 = AtomicU8::new(0); // 0 unknown, 1 off, 2 on +static TABLE: Mutex> = Mutex::new(BTreeMap::new()); + +fn on() -> bool { + match STATE.load(Ordering::Relaxed) { + 1 => false, + 2 => true, + _ => { + let enabled = std::env::var_os("FLY_SESSION_PROFILE").is_some(); + STATE.store(if enabled { 2 } else { 1 }, Ordering::Relaxed); + enabled + } + } +} + +/// Times until dropped. +pub struct Span(Option<(&'static str, Instant)>); + +/// Starts timing `name`. +pub fn span(name: &'static str) -> Span { + Span(on().then(|| (name, Instant::now()))) +} + +impl Drop for Span { + fn drop(&mut self) { + if let Some((name, started)) = self.0.take() { + let mut table = TABLE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let entry = table.entry(name).or_insert((0, Duration::ZERO)); + entry.0 += 1; + entry.1 += started.elapsed(); + } + } +} + +/// `(name, count, mean)` for every span recorded, then clears the table. +pub fn report() -> Vec<(&'static str, u64, Duration)> { + let mut table = TABLE + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let out = table + .iter() + .map(|(name, (count, total))| (*name, *count, *total / (*count).max(1) as u32)) + .collect(); + table.clear(); + out +} diff --git a/services/flysim/crates/fly-session/src/rpc.rs b/services/flysim/crates/fly-session/src/rpc.rs index 11a4477..c5227d1 100644 --- a/services/flysim/crates/fly-session/src/rpc.rs +++ b/services/flysim/crates/fly-session/src/rpc.rs @@ -69,8 +69,35 @@ pub async fn call( request_id: DomainRequestId, want_artifacts: &[String], ) -> Result { + send(bus, target, method, scope, params, attachments, request_id, want_artifacts) + .await? + .finish() + .await +} + +/// A domain call that has been sent and not yet answered: the bus has it in order, so a call +/// sent after it to the same worker is dispatched after it. +pub struct SentCall { + method: String, + pending: flybus::PendingCall, + request_id: DomainRequestId, + want_artifacts: Vec, +} + +/// Sends one domain call without waiting for its reply ([`SentCall::finish`] waits). +#[allow(clippy::too_many_arguments)] +pub async fn send( + bus: &flybus::Client, + target: &WorkerRef, + method: &str, + scope: Option, + params: Map, + attachments: &[(&str, &flybus::Artifact)], + request_id: DomainRequestId, + want_artifacts: &[String], +) -> Result { let request = SessionRpcRequest { request_id: request_id.clone(), scope, params: Value::Object(params) }; - let mut pending = bus + let pending = bus .call( &target.service, Some(&target.bus_incarnation), @@ -80,26 +107,49 @@ pub async fn call( ) .await .map_err(|e| bus_error(method, &e))?; - let result = pending.result().await.map_err(|e| bus_error(method, &e))?; - let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone())) - .map_err(|e| DomainError::invalid(format!("{method}: {e}")))?; - let mut artifacts = BTreeMap::new(); - for name in want_artifacts { - if let Ok(artifact) = result.artifact(name) { - // An independent explicit hold, so the handle outlives this delivery and can be - // forwarded to several Commit calls and to publication. - match artifact.retain().await { - Ok(hold) => { - artifacts.insert(name.clone(), hold); - } - Err(_) => { - artifacts.insert(name.clone(), artifact); - } + Ok(SentCall { + method: method.to_owned(), + pending, + request_id, + want_artifacts: want_artifacts.to_vec(), + }) +} + +impl SentCall { + /// Waits for the terminal reply. + pub async fn finish(mut self) -> Result { + let method = self.method.as_str(); + let result = self.pending.result().await.map_err(|e| bus_error(method, &e))?; + let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone())) + .map_err(|e| DomainError::invalid(format!("{method}: {e}")))?; + // An independent explicit hold on each wanted attachment, so the handle outlives this + // delivery and can be forwarded to several Commit calls and to publication. The holds + // are independent router round trips, so they are taken concurrently. + let wanted: Vec<(String, flybus::Artifact)> = self + .want_artifacts + .iter() + .filter_map(|name| result.artifact(name).ok().map(|a| (name.clone(), a))) + .collect(); + let retains: Vec<_> = wanted + .into_iter() + .map(|(name, artifact)| { + tokio::spawn(async move { + match artifact.retain().await { + Ok(hold) => (name, hold), + Err(_) => (name, artifact), + } + }) + }) + .collect(); + let mut artifacts = BTreeMap::new(); + for retain in retains { + if let Ok((name, artifact)) = retain.await { + artifacts.insert(name, artifact); } } + drop(result); + Ok(DomainReply { outcome, request_id: self.request_id, artifacts }) } - drop(result); - Ok(DomainReply { outcome, request_id, artifacts }) } /// Maps a bus failure onto a domain error, preserving how certain the mutation is. diff --git a/services/flysim/crates/fly-session/src/state.rs b/services/flysim/crates/fly-session/src/state.rs index 220310f..92c0796 100644 --- a/services/flysim/crates/fly-session/src/state.rs +++ b/services/flysim/crates/fly-session/src/state.rs @@ -110,6 +110,28 @@ pub fn executor_payload(agent_id: &str) -> String { pub const WORLD_PAYLOAD: &str = "world"; /// The task ledger's payload name. pub const TASK_LEDGER_PAYLOAD: &str = "task-ledger"; +/// The prefix of the payloads that carry a task ledger's attachments: bytes beside its typed +/// value, for a ledger over the 32 KiB `TypedValue` bound (`workers-v1` section 1, "explicit +/// artifact-backed schema"; `Task::capture_attachments`). `task-ledger-`. +pub const TASK_ATTACHMENT_PREFIX: &str = "task-ledger-"; + +/// The payload name of one task ledger attachment. +pub fn task_attachment_payload(name: &str) -> String { + format!("{TASK_ATTACHMENT_PREFIX}{name}") +} + +/// The task ledger's attachments among a checkpoint's payloads, by attachment name. +pub fn task_attachments( + payloads: &std::collections::BTreeMap>, +) -> std::collections::BTreeMap> { + payloads + .iter() + .filter_map(|(name, bytes)| { + name.strip_prefix(TASK_ATTACHMENT_PREFIX).map(|n| (n.to_owned(), bytes.clone())) + }) + .collect() +} + /// The prior world inspection's payload name. pub const PRIOR_INSPECTION_PAYLOAD: &str = "prior-inspection"; /// The coordinator's admission state and event watermarks. diff --git a/services/flysim/crates/fly-session/src/task.rs b/services/flysim/crates/fly-session/src/task.rs index bbb2bf4..60873b9 100644 --- a/services/flysim/crates/fly-session/src/task.rs +++ b/services/flysim/crates/fly-session/src/task.rs @@ -7,6 +7,7 @@ //! writes a controller or neural state directly. use std::collections::BTreeMap; +use std::sync::Arc; use serde_json::{Map, Value, json}; @@ -53,6 +54,48 @@ pub fn controller_schema_ref() -> SchemaRef { synthetic_schema("arena.controller.v1", 1) } +/// One boundary's inspection as the task and the executor read it: the observation's typed +/// `inspection` value plus the bytes of the attachments the task declared +/// ([`Task::inspection_attachments`]). +/// +/// An artifact-backed inspection (`gameboy-memory-inspection-v1`: a 64 KiB image per boundary) +/// names its bytes by `ArtifactRef`; the coordinator holds the artifact until the transition +/// that reads it has been evaluated (`step-v1` section 3, Phase C amendment) and hands the task +/// the bytes, so neither the task nor the executor ever reads a live world. The synthetic +/// composition declares no attachment, and its inspection derefs to the typed value it always +/// was. +#[derive(Clone, Debug)] +pub struct Inspection { + /// The boundary the observation belongs to. + pub boundary: u64, + pub value: TypedValue, + /// Attachment name to bytes, for the names the task declared. + pub attachments: BTreeMap>>, +} + +impl Inspection { + /// An inspection with no attachment: the synthetic composition's. + pub fn plain(boundary: u64, value: TypedValue) -> Inspection { + Inspection { boundary, value, attachments: BTreeMap::new() } + } +} + +impl std::ops::Deref for Inspection { + type Target = TypedValue; + + fn deref(&self) -> &TypedValue { + &self.value + } +} + +/// What a task's part of a rollback produced (`step-v1` section 6 amendment, step 3): the next +/// decision contexts for the restored boundary, and any events it reports. +#[derive(Clone, Debug)] +pub struct RollbackEvaluation { + pub next_contexts: BTreeMap, + pub events: Vec, +} + /// What `Task.bootstrap` produced. #[derive(Clone, Debug)] pub struct Bootstrap { @@ -70,16 +113,27 @@ pub struct Evaluation { pub progress: TypedValue, pub events: Vec, pub episode: Option, + /// Slot saves the transition asks for at the boundary it reached, applied by the coordinator + /// after every Commit and before any capture or rollback there (`step-v1` section 3, Phase C + /// amendment; environment capability `gameboy-slots-v1`). Empty in every composition that + /// declares no slots. + pub slot_saves: Vec, } /// A checkpointable task ledger and the two evaluation entry points. pub trait Task: Send { fn schema(&self) -> SchemaRef; + /// The inspection attachments this task and its executor read, which the coordinator asks + /// the environment for, holds and hands over as bytes. None by default. + fn inspection_attachments(&self) -> Vec { + Vec::new() + } + /// Called once, at boundary 0, before any agent is initialized. fn bootstrap( &mut self, - initial_inspection: &TypedValue, + initial_inspection: &Inspection, bindings: &[PortBinding], ) -> DomainResult; @@ -87,11 +141,40 @@ pub trait Task: Send { fn evaluate_transition( &mut self, scope: &Scope, - old_inspection: &TypedValue, - new_inspection: &TypedValue, + old_inspection: &Inspection, + new_inspection: &Inspection, applied_controls: &[PortControl], ) -> DomainResult; + /// Step 3 of a declared rollback policy, coordinator-local (`step-v1` section 6 amendment): + /// the task clears its transient observations and the executor cancels any running action + /// and observes the restored boundary, which yields the next decision contexts. `scope` is + /// the new epoch at the restored boundary. A task that declares no rollback policy refuses. + fn rollback( + &mut self, + _scope: &Scope, + _restored: &Inspection, + ) -> DomainResult { + Err(DomainError::before( + ErrorCode::Unsupported, + "this task declares no rollback policy", + )) + } + + /// After a group restore installed this task's ledger: the restored boundary's inspection + /// and the agents' restored brain clock. A task whose executor state is transient + /// (`restore: legacy-transient-reset`) re-observes the world here and returns the decision + /// contexts it would hand the agents, which the coordinator holds against the ones the + /// checkpoint recorded. `None` (the default) means the recorded contexts stand unchecked. + fn restored( + &mut self, + _scope: &Scope, + _restored: &Inspection, + _clock: &RationalNs, + ) -> DomainResult>> { + Ok(None) + } + fn progress(&self) -> TypedValue; /// How many times `evaluate_transition` has run. A transition must evaluate once. @@ -100,6 +183,35 @@ pub trait Task: Send { /// The checkpointable ledger at a committed boundary (`workers-v1` section 4). fn capture(&self) -> DomainResult; + /// Bytes the ledger carries beside its typed value, by name: for a ledger over the 32 KiB + /// `TypedValue` bound, the "explicit artifact-backed schema" of `workers-v1` section 1. A + /// checkpoint files each as its own payload (`state::task_attachment_payload`). None by + /// default. + fn capture_attachments(&self) -> DomainResult>> { + Ok(BTreeMap::new()) + } + + /// [`Task::validate_restore`] with the ledger's attachments. + fn validate_restore_with( + &self, + state: &TypedValue, + attachments: &BTreeMap>, + ) -> DomainResult<()> { + let _ = attachments; + self.validate_restore(state) + } + + /// [`Task::install_restore`] with the ledger's attachments. + fn install_restore_with( + &mut self, + epoch: &Id, + state: &TypedValue, + attachments: &BTreeMap>, + ) -> DomainResult<()> { + let _ = attachments; + self.install_restore(epoch, state) + } + /// Validates a captured ledger without installing it, so a group install can fail before /// anything is changed. fn validate_restore(&self, state: &TypedValue) -> DomainResult<()>; @@ -127,7 +239,7 @@ pub trait ActionExecutor: Send { &mut self, scope: &Scope, decision: &TypedValue, - current_game_state: &TypedValue, + current_game_state: &Inspection, progress: &TypedValue, clock: &RationalNs, ) -> DomainResult<(ControllerIntent, Vec)>; @@ -151,7 +263,7 @@ impl ActionExecutor for IdentityExecutor { &mut self, _scope: &Scope, decision: &TypedValue, - _current_game_state: &TypedValue, + _current_game_state: &Inspection, _progress: &TypedValue, _clock: &RationalNs, ) -> DomainResult<(ControllerIntent, Vec)> { @@ -294,7 +406,7 @@ impl Task for CounterTask { fn bootstrap( &mut self, - initial_inspection: &TypedValue, + initial_inspection: &Inspection, bindings: &[PortBinding], ) -> DomainResult { if initial_inspection.schema != inspection_schema() { @@ -329,8 +441,8 @@ impl Task for CounterTask { fn evaluate_transition( &mut self, scope: &Scope, - old_inspection: &TypedValue, - new_inspection: &TypedValue, + old_inspection: &Inspection, + new_inspection: &Inspection, applied_controls: &[PortControl], ) -> DomainResult { let old = old_inspection.integer("counter").map_err(DomainError::invalid)?; @@ -445,6 +557,7 @@ impl Task for CounterTask { progress: self.progress_value(), events, episode, + slot_saves: Vec::new(), }) } diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index 4451900..e274025 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -113,24 +113,39 @@ impl StatusCell { } } +/// The rest of a reply a handler finishes outside the endpoint's lock. +pub type DeferredReply = + std::pin::Pin> + Send>>; + /// What a handler produced: a domain `result` object and the artifacts it attaches. pub struct HandlerReply { pub result: Map, pub artifacts: Vec<(String, flybus::Artifact)>, /// True when a failure left the endpoint mutated; the shell reports it as such. pub mutated: bool, + /// When set, the reply is this future's: the handler took what it needs from the endpoint + /// (a state snapshot at the committed boundary) and the rest -- encoding, digesting and + /// sealing a capture payload -- runs after the endpoint's lock is released, so the next + /// mutation (the next `Agent.Prepare`) does not wait for it. The bus call is answered + /// when it completes, and cached like any other reply. + pub deferred: Option, } impl HandlerReply { pub fn new(result: Map) -> HandlerReply { - HandlerReply { result, artifacts: Vec::new(), mutated: true } + HandlerReply { result, artifacts: Vec::new(), mutated: true, deferred: None } } pub fn with_artifacts( result: Map, artifacts: Vec<(String, flybus::Artifact)>, ) -> HandlerReply { - HandlerReply { result, artifacts, mutated: true } + HandlerReply { result, artifacts, mutated: true, deferred: None } + } + + /// A reply finished by `rest` outside the endpoint's lock ([`HandlerReply::deferred`]). + pub fn deferred(rest: DeferredReply) -> HandlerReply { + HandlerReply { result: Map::new(), artifacts: Vec::new(), mutated: true, deferred: Some(rest) } } /// The canonical JSON of one method result. @@ -304,6 +319,7 @@ async fn run( ) }; let mut running: Vec> = Vec::new(); + let order = Arc::new(LockOrder::default()); while let Some(incoming) = service.next().await { let method = incoming.method().to_owned(); let responder = incoming.responder(); @@ -491,9 +507,12 @@ async fn run( // original bus call still completes normally. The endpoint mutex, not this loop, // enforces one mutation at a time. running.retain(|task| !task.is_finished()); + let ticket = order.issue(); running.push(tokio::spawn(execute( client.clone(), endpoint.clone(), + order.clone(), + ticket, cache.clone(), status.clone(), worker_id.clone(), @@ -512,11 +531,73 @@ async fn run( } } +/// Admitted mutations take the endpoint's lock in the order they arrived. +/// +/// Each runs in a task of its own, so the shell keeps reading, and tasks are not scheduled in +/// spawn order: without this, a `State.Capture` followed on the wire by the next +/// `Agent.Prepare` could find the agent already prepared. A ticket per admitted mutation, taken +/// in arrival order, and the lock taken only on the ticket's turn keep the wire's order. +#[derive(Default)] +struct LockOrder { + issued: std::sync::atomic::AtomicU64, + turn: std::sync::atomic::AtomicU64, + changed: tokio::sync::Notify, +} + +impl LockOrder { + fn issue(&self) -> u64 { + self.issued.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + } + + async fn lock_in_turn<'a, E>( + &self, + ticket: u64, + endpoint: &'a tokio::sync::Mutex, + ) -> tokio::sync::MutexGuard<'a, E> { + loop { + let changed = self.changed.notified(); + if self.turn.load(std::sync::atomic::Ordering::SeqCst) == ticket { + break; + } + changed.await; + } + // Queue on the lock first, then hand the turn on: the next ticket queues behind this + // one on the (fair) mutex. + let lock = endpoint.lock(); + tokio::pin!(lock); + let guard = match futures_poll_once(lock.as_mut()).await { + Some(guard) => guard, + None => { + self.advance(); + return lock.await; + } + }; + self.advance(); + guard + } + + fn advance(&self) { + self.turn.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + self.changed.notify_waiters(); + } +} + +/// Polls a future once: its output if it is ready, else `None` with the future registered. +async fn futures_poll_once(mut f: F) -> Option { + std::future::poll_fn(|cx| match std::pin::Pin::new(&mut f).poll(cx) { + std::task::Poll::Ready(v) => std::task::Poll::Ready(Some(v)), + std::task::Poll::Pending => std::task::Poll::Ready(None), + }) + .await +} + /// Runs one admitted mutation, records its reply and answers the bus call. #[allow(clippy::too_many_arguments)] async fn execute( client: flybus::Client, endpoint: Arc>, + order: Arc, + ticket: u64, cache: Arc>, status: StatusCell, worker_id: Id, @@ -533,7 +614,7 @@ async fn execute( let outcome = { // One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is // never held across a bus round trip taken by anything else. - let mut e = endpoint.lock().await; + let mut e = order.lock_in_turn(ticket, &endpoint).await; let ctx = HandlerCtx { method: &method, request: &request, @@ -542,16 +623,34 @@ async fn execute( }; e.handle(ctx).await }; + // A deferred reply finishes here, with the endpoint's lock released. + let outcome = match outcome { + Ok(HandlerReply { deferred: Some(rest), .. }) => rest.await, + other => other, + }; match outcome { Ok(reply) => { let outcome = success(&request, &worker_id, &incarnation_id, reply.result.clone()); - let mut holds = Vec::with_capacity(reply.artifacts.len()); - for (name, artifact) in &reply.artifacts { - // The cache owns its own hold, so a replay survives the first caller - // consuming its delivery. - match artifact.retain().await { - Ok(hold) => holds.push((name.clone(), hold)), - Err(_) => holds.push((name.clone(), artifact.clone())), + // The cache owns its own hold on every artifact, so a replay survives the first + // caller consuming its delivery. The holds are independent router round trips, so + // they are taken concurrently. + let retains: Vec<_> = reply + .artifacts + .iter() + .map(|(name, artifact)| { + let (name, artifact) = (name.clone(), artifact.clone()); + tokio::spawn(async move { + match artifact.retain().await { + Ok(hold) => (name, hold), + Err(_) => (name, artifact), + } + }) + }) + .collect(); + let mut holds = Vec::with_capacity(retains.len()); + for retain in retains { + if let Ok(pair) = retain.await { + holds.push(pair); } } let cached = CachedReply::with_artifacts(outcome.clone(), holds); diff --git a/services/flysim/crates/fly-session/tests/session.rs b/services/flysim/crates/fly-session/tests/session.rs index fcce346..1c40fe5 100644 --- a/services/flysim/crates/fly-session/tests/session.rs +++ b/services/flysim/crates/fly-session/tests/session.rs @@ -25,7 +25,7 @@ both_transports!( the_committed_snapshot_names_the_boundary_that_just_ended, a_terminal_episode_pauses_at_its_own_boundary, a_rollback_request_without_a_declared_policy_fails_the_epoch, - a_declared_rollback_policy_holds_the_session_at_its_boundary, + a_declared_rollback_policy_needs_participants_that_apply_it, status_answers_with_the_committed_boundary, a_worker_refuses_a_second_initialize, a_single_agent_composition_runs_the_same_transaction, @@ -329,9 +329,13 @@ async fn a_rollback_request_without_a_declared_policy_fails_the_epoch(via: Via) f.shutdown().await; } -/// With `legacy-ratchet-rollback-v1` declared the request is accepted: the transition commits and -/// the session holds at its boundary with the request recorded, for the policy to run. -async fn a_declared_rollback_policy_holds_the_session_at_its_boundary(via: Via) { +/// With `legacy-ratchet-rollback-v1` declared the coordinator runs the policy itself +/// (`step-v1` section 6 amendment; TASK-01), so a composition may only declare it over +/// participants that can apply it: agents that answer `Agent.Rollback` and a world with +/// `gameboy-slots-v1`. The synthetic agents answer neither, so the session never starts -- +/// rather than accepting a rollback request it cannot apply. (Until TASK-01 the declared request +/// paused the session at its boundary.) +async fn a_declared_rollback_policy_needs_participants_that_apply_it(via: Via) { let config = HarnessConfig { terminal: fly_session::task::Terminal::RollbackAfterTransitions(2), ..HarnessConfig::default() @@ -342,13 +346,11 @@ async fn a_declared_rollback_policy_holds_the_session_at_its_boundary(via: Via) .declare_rollback_policy("legacy-ratchet-rollback-v1") .unwrap(); assert!(f.harness.coordinator.declare_rollback_policy("reset-everything").is_err()); - within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap(); - let reports = within("run", f.harness.coordinator.run(4)).await.unwrap(); - assert_eq!(reports.len(), 2); - assert!(!f.harness.coordinator.is_fenced()); - assert_eq!(f.harness.coordinator.phase(), Phase::Paused(2)); - let request = f.harness.coordinator.episode_request().unwrap(); - assert_eq!(request.kind, EpisodeRequestKind::Rollback); + let err = within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap_err(); + assert_eq!(err.error.code, ErrorCode::Unsupported, "{}", err.error.message); + assert!(err.error.message.contains("Agent.Rollback"), "{}", err.error.message); + assert!(f.harness.coordinator.is_fenced()); + assert!(f.harness.coordinator.episode_request().is_none()); f.shutdown().await; }