Merge port/env-01 (unreviewed, integration base)
Both slices add a worker to the same launcher and CLI; the resolution keeps both: the legacy-agent and legacy-environment subcommands, launch structs, flags, flag round-trip rows and the flybrain-core/flybrain-gb/flate2 dependencies. Cargo.lock regenerated by cargo.
This commit is contained in:
commit
ae878ede41
15 changed files with 9328 additions and 9 deletions
|
|
@ -242,6 +242,60 @@ the frame order maps one to one (section 4), the legacy clock equals the rationa
|
|||
(section 3), and the fingerprint and compatibility string are embedded unchanged (sections 2
|
||||
and 12). The acceptance criteria below stand.
|
||||
|
||||
**2026-09-29: built on `port/env-01` (off main `9f2345d`).** `fly-session::legacy_env` is the
|
||||
environment worker (`LegacyGameboyEnvironment`), launched by `Launcher::launch_legacy_environment`
|
||||
and the `legacy-environment` subcommand in all three execution modes. It makes exactly the emulator
|
||||
calls flysim's `LegacyFrame` makes, in the same order: `Environment.Initialize` runs the one-frame
|
||||
setup scaffold with no button down (O[0] has `engineFrame` "1", no audio chunk);
|
||||
`Environment.Advance` takes one complete `gameboy-joypad-v1` batch for the one port, runs one frame
|
||||
and returns the `lcd` view, the `apu` chunk as `f32le` (`sample / 255`, unfiltered) and the
|
||||
`gameboy-memory-inspection-v1` image; `Environment.SaveSlot` / `RestoreSlot` are
|
||||
`gameboy-slots-v1` (a restore imports, releases the pad, shows the slot's frame, runs no frame and
|
||||
moves to the new epoch at the same boundary); `State.Capture` / `StageRestore` / `ActivateRestore`
|
||||
carry every slot and stage on a stopped replacement emulator. The joypad is the only write into a
|
||||
running game. The coordinator now refuses `episodeRequest.kind = "rollback"` (task failure, epoch
|
||||
fenced) unless the composition declares `legacy-ratchet-rollback-v1`
|
||||
(`Coordinator::declare_rollback_policy`); with the policy declared it still pauses at the boundary,
|
||||
because the rollback sequence is TASK-01's. Parity (`tests/legacy_env.rs`, harness
|
||||
`legacy_env_parity`): records equal to the emulator driven directly, frame by frame (view, 64 KiB
|
||||
image, WRAM, audio chunk, slot and capture state digests), in-process, thread and process, on a
|
||||
toy cartridge the harness assembles (committed golden `fixtures/legacy-env/toy-cart.golden.json`)
|
||||
and, with rom-env, on the real cartridge from the row-58 checkpoint; and the service's own
|
||||
`FLY_TRACE`s (FND-01's harness; `FLY_ENV01_TRACE_DIR`) replayed through the worker reproduce every
|
||||
recorded frame, WRAM and slot-state digest, including a ratchet slot save and a rollback. Not in
|
||||
this slice: the shim's bulk read (MEM-01, behind the one seam `legacy_env::memory_image`), the
|
||||
coordinator's save/rollback/`Agent.Rollback` sequence and the executor (TASK-01), and assembling
|
||||
the FLYSIM01 export from the three halves (STATE-02; the world's half is
|
||||
`Flysim01World::{manifest_entries, chunks}`).
|
||||
|
||||
**Amendment, 2026-09-29 (ENV-01).** Four readings the contract left open, fixed by this slice:
|
||||
|
||||
- *The image read is not state-neutral, so it is guarded.* `emulator_read_mem` of OAM, VRAM,
|
||||
`FF01`/`FF02`, `FF04`-`FF06`, `IF`, `STAT` or `LY` runs binjgb's lazy synchronisation, and
|
||||
`export_state` afterwards differs (never, over 17,398 replayed frames, a frame or WRAM). The
|
||||
legacy loop reads none of these between a frame and the ratchet's capture, so an unguarded image
|
||||
would make every slot and capture differ from the service's bytes. The worker reads the image
|
||||
between `export_state` and `import_state` of the same bytes, which leaves the emulator exactly as
|
||||
the frame left it; `legacy-gameboy-v1` section 8's proof ("export before and after, compare")
|
||||
therefore fails for a plain 65,536-read loop and holds for the guarded one. MEM-01's bulk read
|
||||
must keep that guard (or equivalent).
|
||||
- *A `FLYSIM01` world starts at `k = emulatorFrame - setupFrames`.* The legacy file has no
|
||||
boundary, world clock or audio position. The frame counter advances once per transition and
|
||||
never across a rollback, so `engineFrame = k + 1` from a fresh start on; `worldTime` is
|
||||
`k x stepDuration` and the audio position is that time's sample at the configured rate, rounded
|
||||
down. The first chunk after the restore marks the discontinuity. The ratchet's one slot is the
|
||||
composition's first declared slot (`best`).
|
||||
- *Names.* The image travels as the attachment `inspection.memory`; the audio stream is `apu`;
|
||||
the port is `p1`. `backendConfig` is the canonical JSON of `gameboy-backend-config-v1`
|
||||
`{form, romDigest, portId, slots, audio {sampleRate, channels, bufferFrames}, setupFrames, view,
|
||||
controllerSchema, inspectionSchema}`; `Environment.Initialize` naming any other document, and a
|
||||
cartridge on disk that is not `romDigest`, are refused `INCOMPATIBLE_STATE` with nothing mutated.
|
||||
The capture payload is flybrain-core's envelope with magic `FLYENV01`, and its participant
|
||||
compatibility uses the state format `fly-gb-env-v1`.
|
||||
- *`legacy-transient-reset` for the world is empty.* Everything the environment holds is restored:
|
||||
emulator, frame on screen, joypad, frame counter, slots, clock and audio position. The reset
|
||||
applies to the executor, the agent's readout transient and the task's transient observations.
|
||||
|
||||
**Implement:** binjgb environment, task-local memory inspector and identity/existing action
|
||||
adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash semantics.
|
||||
|
||||
|
|
|
|||
|
|
@ -248,6 +248,15 @@ is not the environment's `contentDigest`. The emulator answers its own bank read
|
|||
FLYSIM01's `ratchet_game` and `ratchet_frame` are today. A slot save due at a boundary
|
||||
completes before any `State.Capture` or FLYSIM01 export at that boundary (section 16).
|
||||
|
||||
**Amendment, 2026-09-29 (ENV-01).** Two consequences of building this section, recorded in the
|
||||
[implementation guide](implementation.md) ENV-01 entry: the memory image cannot be taken with a
|
||||
plain loop of `emulator_read_mem`, because reading OAM, VRAM, the serial and timer registers,
|
||||
`IF`, `STAT` or `LY` advances binjgb's lazy synchronisation and changes what `export_state` writes
|
||||
-- the environment reads it between an export and an import of the same bytes, so slots and
|
||||
captures stay byte for byte the legacy loop's; and a `FLYSIM01` world is restored at boundary
|
||||
`emulatorFrame - 1`, its world time and audio position derived from that boundary, with the
|
||||
ratchet's snapshot as the slot `best`.
|
||||
|
||||
## 10. Executor `pokered-macros-v1`
|
||||
|
||||
The Pokémon Red task (reward adapter, ladder, ratchet ledger) and its action executor (the
|
||||
|
|
|
|||
1
services/flysim/Cargo.lock
generated
1
services/flysim/Cargo.lock
generated
|
|
@ -442,6 +442,7 @@ dependencies = [
|
|||
"flate2",
|
||||
"fly-session-types",
|
||||
"flybrain-core",
|
||||
"flybrain-gb",
|
||||
"flybus",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
|
|
|
|||
|
|
@ -25,7 +25,11 @@ fly-session-types = { path = "../fly-session-types" }
|
|||
flybus = { path = "../flybus" }
|
||||
# AGENT-01: the legacy agent worker is an adapter over the existing neural core (LIF kernel,
|
||||
# plasticity, retina, fixed readout, checkpoint chunks). Pure Rust, no emulator.
|
||||
# ENV-01: the legacy Game Boy environment worker drives the binjgb emulator through
|
||||
# flybrain-gb's safe wrapper, and flybrain-core's frozen envelope layout reads and writes the
|
||||
# world's half of a FLYSIM01 checkpoint.
|
||||
flybrain-core = { path = "../flybrain-core" }
|
||||
flybrain-gb = { path = "../flybrain-gb" }
|
||||
# The toy connectome fixture is written as gzipped `.binz` arrays, the dataset loader's format.
|
||||
flate2 = { workspace = true }
|
||||
|
||||
|
|
|
|||
|
|
@ -47,6 +47,8 @@ Ready(k) ─ Prepare all agents concurrently ───────────
|
|||
| `cli` | The binary's subcommands: `agent`, `environment`, `measure` |
|
||||
| `state` | The durable checkpoint store over `FLYSESS1`: compatibility, generations, the bounded writer |
|
||||
| `harness` | The runnable composition: router, the flies, one arena, one coordinator |
|
||||
| `legacy_env` | ENV-01: the legacy Game Boy environment worker over binjgb -- the one-frame setup scaffold, the joypad batch, `f32le` audio, the per-boundary memory image, `gameboy-slots-v1`, the capture payload and the world's half of `FLYSIM01` |
|
||||
| `legacy_env_parity` | ENV-01's parity harness: the toy cartridge, recorded scripts, the emulator driven directly in `LegacyFrame` order, the worker driven over the bus, and the replay of the service's own `FLY_TRACE` |
|
||||
|
||||
## Execution modes and the launcher
|
||||
|
||||
|
|
@ -88,6 +90,7 @@ A separate-process participant is a subcommand of this crate's one binary, which
|
|||
```sh
|
||||
fly-session agent --socket S --store-root D --client-id C --service N --threads T ...
|
||||
fly-session environment --socket S --store-root D --client-id C --service N --threads T ...
|
||||
fly-session legacy-environment ... --worker ID --port p1 --rom PATH --rom-digest SHA256 --slots best
|
||||
fly-session measure --steps 300 --agents 1,2,4
|
||||
```
|
||||
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -22,9 +22,11 @@ use std::process::ExitCode;
|
|||
use crate::agent::AgentFaults;
|
||||
use crate::environment::EnvironmentFaults;
|
||||
use crate::launcher::{
|
||||
AgentLaunch, EnvironmentLaunch, ExecutionMode, LegacyAgentLaunch, Started, flags, serve_one,
|
||||
AgentLaunch, EnvironmentLaunch, ExecutionMode, LegacyAgentLaunch, LegacyEnvironmentLaunch,
|
||||
Started, flags, serve_one,
|
||||
};
|
||||
use crate::legacy_agent::LegacyProfileKind;
|
||||
use crate::legacy_env::BackendConfig;
|
||||
use crate::types::*;
|
||||
|
||||
const USAGE: &str = "\
|
||||
|
|
@ -33,6 +35,8 @@ fly-session <command> [options]
|
|||
agent serve one agent worker on a launcher-created endpoint
|
||||
legacy-agent serve one legacy Game Boy agent worker (AGENT-01) on a launcher endpoint
|
||||
environment serve the environment worker on a launcher-created endpoint
|
||||
legacy-environment
|
||||
serve the legacy Game Boy environment (ENV-01) on a launcher endpoint
|
||||
measure compare the execution modes and print the measurement table
|
||||
measure-row measure one row and print it as JSON (one child per row)
|
||||
|
||||
|
|
@ -54,6 +58,9 @@ Worker options (agent and environment):
|
|||
environment: --worker ID --ports p1,p2 --step-numerator N --step-denominator N
|
||||
[--advance-delay-ms N] [--omit-view-at-boundary N]
|
||||
[--fail-stage-restore 0|1] [--fail-activate-restore 0|1]
|
||||
legacy-environment:
|
||||
--worker ID --port ID --rom PATH --rom-digest SHA256 --slots best
|
||||
--audio-rate 48000 --audio-buffer-frames 4096 --setup-frames 1
|
||||
|
||||
Measure options:
|
||||
--steps N transitions per run (default 200)
|
||||
|
|
@ -83,6 +90,10 @@ pub fn main() -> ExitCode {
|
|||
.and_then(|o| serve(&command, &o)),
|
||||
"environment" => Options::parse(&rest, &[flags::COMMON, flags::ENVIRONMENT_ONLY])
|
||||
.and_then(|o| serve(&command, &o)),
|
||||
"legacy-environment" => {
|
||||
Options::parse(&rest, &[flags::COMMON, flags::LEGACY_ENVIRONMENT_ONLY])
|
||||
.and_then(|o| serve(&command, &o))
|
||||
}
|
||||
"measure" => Options::parse(&rest, &[flags::MEASURE]).and_then(|o| measure(&o)),
|
||||
"measure-row" => Options::parse(&rest, &[flags::MEASURE]).and_then(|o| measure_row(&o)),
|
||||
"--help" | "-h" | "help" => {
|
||||
|
|
@ -238,6 +249,23 @@ fn serve(role: &str, options: &Options) -> Result<(), String> {
|
|||
client_id: client_id.clone(),
|
||||
service: service.clone(),
|
||||
}),
|
||||
"legacy-environment" => Started::LegacyEnvironment(LegacyEnvironmentLaunch {
|
||||
session_id,
|
||||
worker_id: options.id(flags::WORKER)?,
|
||||
incarnation_id,
|
||||
worker_threads: threads,
|
||||
rom_path: options.path(flags::ROM)?,
|
||||
backend: BackendConfig {
|
||||
rom_digest: options.required(flags::ROM_DIGEST)?.to_owned(),
|
||||
port_id: options.id(flags::PORT)?,
|
||||
slots: parse_ids(options.required(flags::SLOTS)?, flags::SLOTS)?,
|
||||
audio_sample_rate: options.u64(flags::AUDIO_RATE, 0)?,
|
||||
audio_buffer_frames: options.u64(flags::AUDIO_BUFFER_FRAMES, 0)?,
|
||||
setup_frames: options.u64(flags::SETUP_FRAMES, 0)?,
|
||||
},
|
||||
client_id: client_id.clone(),
|
||||
service: service.clone(),
|
||||
}),
|
||||
_ => Started::Environment(EnvironmentLaunch {
|
||||
session_id,
|
||||
worker_id: options.id(flags::WORKER)?,
|
||||
|
|
@ -292,10 +320,14 @@ fn parse_channels(value: &str) -> Result<Vec<String>, String> {
|
|||
}
|
||||
|
||||
fn parse_ports(value: &str) -> Result<Vec<Id>, String> {
|
||||
parse_ids(value, flags::PORTS)
|
||||
}
|
||||
|
||||
fn parse_ids(value: &str, flag: &str) -> Result<Vec<Id>, String> {
|
||||
value
|
||||
.split(',')
|
||||
.filter(|part| !part.is_empty())
|
||||
.map(|part| parse_id(part).map_err(|e| format!("--ports: {e}")))
|
||||
.map(|part| parse_id(part).map_err(|e| format!("--{flag}: {e}")))
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -336,6 +336,9 @@ pub struct Coordinator {
|
|||
/// Set by whoever asks for a normal pause, possibly while a transition is in flight.
|
||||
pause: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
episode: Option<EpisodeRequest>,
|
||||
/// The rollback policy the composition declares, if any (`legacy-ratchet-rollback-v1` is
|
||||
/// the only one defined). Without one, a task's rollback request is a task failure.
|
||||
rollback_policy: Option<Id>,
|
||||
lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>,
|
||||
stats: Stats,
|
||||
/// The ordered actions this session took, for the ordering assertions.
|
||||
|
|
@ -431,6 +434,7 @@ impl Coordinator {
|
|||
pacing: None,
|
||||
pause: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
|
||||
episode: None,
|
||||
rollback_policy: None,
|
||||
lifecycle_acks: Vec::new(),
|
||||
stats: Stats::default(),
|
||||
audit: Vec::new(),
|
||||
|
|
@ -526,6 +530,22 @@ impl Coordinator {
|
|||
self.timelines.positions()
|
||||
}
|
||||
|
||||
/// Declares the composition's rollback policy (`workers-v1` section 4 and `step-v1` section 6,
|
||||
/// both amended 2026-09-23). Only `legacy-ratchet-rollback-v1` is defined. Until the rollback
|
||||
/// sequence is wired (TASK-01), a declared rollback request pauses the session at its boundary
|
||||
/// like a terminal one, which is safe; an undeclared one fails the epoch.
|
||||
pub fn declare_rollback_policy(&mut self, policy: &str) -> Result<(), DomainError> {
|
||||
if policy != fly_session_types::extensions::ROLLBACK_POLICY {
|
||||
return Err(DomainError::invalid(format!("{policy} is not a defined rollback policy")));
|
||||
}
|
||||
self.rollback_policy = Some(id(policy));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn rollback_policy(&self) -> Option<&Id> {
|
||||
self.rollback_policy.as_ref()
|
||||
}
|
||||
|
||||
pub fn episode_request(&self) -> Option<&EpisodeRequest> {
|
||||
self.episode.as_ref()
|
||||
}
|
||||
|
|
@ -1676,6 +1696,22 @@ impl Coordinator {
|
|||
self.fail_now(e, "task-evaluate")
|
||||
})?;
|
||||
self.audit.push(format!("evaluate:{k}"));
|
||||
if let Some(request) = &evaluation.episode
|
||||
&& request.kind == EpisodeRequestKind::Rollback
|
||||
&& self.rollback_policy.is_none()
|
||||
{
|
||||
// `workers-v1` section 4 (2026-09-23): a composition that declares no rollback policy
|
||||
// treats the request as a task failure. The brains and the world already moved, so
|
||||
// the epoch fails rather than committing a transition whose outcome it cannot apply.
|
||||
return Err(self.fail_now(
|
||||
DomainError::new(
|
||||
ErrorCode::Unsupported,
|
||||
"the task asked for a rollback and this composition declares no rollback policy",
|
||||
MutationCertainty::Applied,
|
||||
),
|
||||
"task-evaluate",
|
||||
));
|
||||
}
|
||||
let mut outcomes = evaluation.outcomes.clone();
|
||||
let mut next_contexts = evaluation.next_contexts.clone();
|
||||
for agent in self.agent_ids() {
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ use flybus::{Client, ClientConfig, Router, ServiceConfig, Transport, UnixListene
|
|||
use crate::agent::{AgentConfig, AgentFaults, FakeAgentWorker};
|
||||
use crate::environment::{CounterEnvironment, EnvironmentConfig, EnvironmentFaults};
|
||||
use crate::legacy_agent::{LegacyAgentConfig, LegacyAgentWorker, LegacyProfileKind};
|
||||
use crate::legacy_env::{BackendConfig, LegacyEnvironmentConfig, LegacyGameboyEnvironment};
|
||||
use crate::rpc::WorkerRef;
|
||||
use crate::types::*;
|
||||
use crate::worker::{StatusCell, WorkerHandle, serve};
|
||||
|
|
@ -278,6 +279,24 @@ pub struct LegacyAgentLaunch {
|
|||
pub service: String,
|
||||
}
|
||||
|
||||
/// What the legacy Game Boy environment participant (ENV-01) is started with.
|
||||
///
|
||||
/// Everything crosses a process boundary as argv: the cartridge's path (read-only, outside the
|
||||
/// checkout, never identity) and the backend configuration it must be -- the cartridge digest,
|
||||
/// the port, the declared slots and the audio configuration. `Environment.Initialize` must name
|
||||
/// exactly that configuration's `AssetRef`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LegacyEnvironmentLaunch {
|
||||
pub session_id: Id,
|
||||
pub worker_id: Id,
|
||||
pub incarnation_id: Id,
|
||||
pub worker_threads: usize,
|
||||
pub rom_path: PathBuf,
|
||||
pub backend: BackendConfig,
|
||||
pub client_id: String,
|
||||
pub service: String,
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------
|
||||
// A launched participant
|
||||
|
||||
|
|
@ -666,6 +685,39 @@ impl Launcher {
|
|||
}
|
||||
}
|
||||
|
||||
/// Starts the legacy Game Boy environment (ENV-01), in the launcher's configured mode, and
|
||||
/// identifies it.
|
||||
pub async fn launch_legacy_environment(
|
||||
&mut self,
|
||||
spec: LegacyEnvironmentLaunch,
|
||||
) -> Result<WorkerIdentity, DomainError> {
|
||||
let threads = self.budget.allocate(&spec.worker_id, spec.worker_threads)?;
|
||||
let identity = WorkerIdentity {
|
||||
session_id: spec.session_id.clone(),
|
||||
client_id: spec.client_id.clone(),
|
||||
service: spec.service.clone(),
|
||||
worker_id: spec.worker_id.clone(),
|
||||
incarnation_id: spec.incarnation_id.clone(),
|
||||
role: Role::Environment,
|
||||
port_id: None,
|
||||
worker_threads: threads,
|
||||
};
|
||||
let started = self
|
||||
.start_participant(&identity, Started::LegacyEnvironment(spec.clone()), threads)
|
||||
.await;
|
||||
match started {
|
||||
Ok(worker) => {
|
||||
let identity = worker.identity.clone();
|
||||
self.workers.insert(spec.worker_id.clone(), worker);
|
||||
Ok(identity)
|
||||
}
|
||||
Err(e) => {
|
||||
self.budget.release(&spec.worker_id);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_participant(
|
||||
&mut self,
|
||||
identity: &WorkerIdentity,
|
||||
|
|
@ -754,6 +806,14 @@ impl Launcher {
|
|||
let status = endpoint.status();
|
||||
(serve(client, service, endpoint), status)
|
||||
}
|
||||
Started::LegacyEnvironment(spec) => {
|
||||
let endpoint = LegacyGameboyEnvironment::new(legacy_environment_config(
|
||||
spec,
|
||||
identity.worker_threads,
|
||||
));
|
||||
let status = endpoint.status();
|
||||
(serve(client, service, endpoint), status)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -1313,6 +1373,13 @@ pub(crate) mod flags {
|
|||
pub const PROFILE: &str = "profile";
|
||||
pub const MACRO_CHANNELS: &str = "macro-channels";
|
||||
|
||||
pub const ROM: &str = "rom";
|
||||
pub const ROM_DIGEST: &str = "rom-digest";
|
||||
pub const SLOTS: &str = "slots";
|
||||
pub const AUDIO_RATE: &str = "audio-rate";
|
||||
pub const AUDIO_BUFFER_FRAMES: &str = "audio-buffer-frames";
|
||||
pub const SETUP_FRAMES: &str = "setup-frames";
|
||||
|
||||
pub const MODE: &str = "mode";
|
||||
pub const AGENTS: &str = "agents";
|
||||
pub const STEPS: &str = "steps";
|
||||
|
|
@ -1362,6 +1429,17 @@ pub(crate) mod flags {
|
|||
FAIL_STAGE_RESTORE,
|
||||
FAIL_ACTIVATE_RESTORE,
|
||||
];
|
||||
/// What only the legacy Game Boy environment (ENV-01) is given.
|
||||
pub const LEGACY_ENVIRONMENT_ONLY: &[&str] = &[
|
||||
WORKER,
|
||||
PORT,
|
||||
ROM,
|
||||
ROM_DIGEST,
|
||||
SLOTS,
|
||||
AUDIO_RATE,
|
||||
AUDIO_BUFFER_FRAMES,
|
||||
SETUP_FRAMES,
|
||||
];
|
||||
/// What a measurement run or one of its row children is given.
|
||||
pub const MEASURE: &[&str] = &[MODE, AGENTS, STEPS, WARMUP_STEPS, WORKER_THREADS, MODES];
|
||||
}
|
||||
|
|
@ -1380,6 +1458,7 @@ pub(crate) enum Started {
|
|||
Agent(AgentLaunch),
|
||||
LegacyAgent(LegacyAgentLaunch),
|
||||
Environment(EnvironmentLaunch),
|
||||
LegacyEnvironment(LegacyEnvironmentLaunch),
|
||||
}
|
||||
|
||||
impl Started {
|
||||
|
|
@ -1388,6 +1467,7 @@ impl Started {
|
|||
Started::Agent(_) => "agent",
|
||||
Started::LegacyAgent(_) => "legacy-agent",
|
||||
Started::Environment(_) => "environment",
|
||||
Started::LegacyEnvironment(_) => "legacy-environment",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1465,6 +1545,18 @@ impl Started {
|
|||
}
|
||||
args
|
||||
}
|
||||
Started::LegacyEnvironment(spec) => vec![
|
||||
arg(flags::SESSION, &spec.session_id),
|
||||
arg(flags::WORKER, &spec.worker_id),
|
||||
arg(flags::INCARNATION, &spec.incarnation_id),
|
||||
arg(flags::PORT, &spec.backend.port_id),
|
||||
arg(flags::ROM, spec.rom_path.display()),
|
||||
arg(flags::ROM_DIGEST, &spec.backend.rom_digest),
|
||||
arg(flags::SLOTS, spec.backend.slots.join(",")),
|
||||
arg(flags::AUDIO_RATE, spec.backend.audio_sample_rate),
|
||||
arg(flags::AUDIO_BUFFER_FRAMES, spec.backend.audio_buffer_frames),
|
||||
arg(flags::SETUP_FRAMES, spec.backend.setup_frames),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1509,6 +1601,20 @@ pub(crate) fn environment_config(spec: &EnvironmentLaunch) -> EnvironmentConfig
|
|||
}
|
||||
}
|
||||
|
||||
pub(crate) fn legacy_environment_config(
|
||||
spec: &LegacyEnvironmentLaunch,
|
||||
worker_threads: usize,
|
||||
) -> LegacyEnvironmentConfig {
|
||||
LegacyEnvironmentConfig {
|
||||
session_id: spec.session_id.clone(),
|
||||
worker_id: spec.worker_id.clone(),
|
||||
incarnation_id: spec.incarnation_id.clone(),
|
||||
worker_threads,
|
||||
rom_path: spec.rom_path.clone(),
|
||||
backend: spec.backend.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects, registers and serves one participant. Used by a thread with its own runtime and,
|
||||
/// through the worker subcommand, by a separate process.
|
||||
pub(crate) async fn serve_one(
|
||||
|
|
@ -1539,6 +1645,11 @@ pub(crate) async fn serve_one(
|
|||
Started::Environment(spec) => {
|
||||
serve(client, service, CounterEnvironment::new(environment_config(spec)))
|
||||
}
|
||||
Started::LegacyEnvironment(spec) => serve(
|
||||
client,
|
||||
service,
|
||||
LegacyGameboyEnvironment::new(legacy_environment_config(spec, worker_threads)),
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -1638,6 +1749,21 @@ mod flag_tests {
|
|||
}
|
||||
}
|
||||
|
||||
fn legacy_environment_launch() -> LegacyEnvironmentLaunch {
|
||||
let mut backend = BackendConfig::legacy(&"ab".repeat(32));
|
||||
backend.slots = vec![id("best"), id("spare")];
|
||||
LegacyEnvironmentLaunch {
|
||||
session_id: id("demo"),
|
||||
worker_id: id("world"),
|
||||
incarnation_id: id("world-inc-1"),
|
||||
worker_threads: 1,
|
||||
rom_path: PathBuf::from("/nonexistent/cartridge"),
|
||||
backend,
|
||||
client_id: "environment".to_owned(),
|
||||
service: "env.world".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Both halves of the command line name the same constants, and this proves it for every
|
||||
/// argument a launch can produce: a flag the launcher writes that the parser does not
|
||||
/// accept would be a silently ignored option, which is what the parser now refuses.
|
||||
|
|
@ -1653,6 +1779,10 @@ mod flag_tests {
|
|||
Started::LegacyAgent(legacy_agent_launch()),
|
||||
[flags::COMMON, flags::LEGACY_AGENT_ONLY],
|
||||
),
|
||||
(
|
||||
Started::LegacyEnvironment(legacy_environment_launch()),
|
||||
[flags::COMMON, flags::LEGACY_ENVIRONMENT_ONLY],
|
||||
),
|
||||
] {
|
||||
let arguments = started.arguments();
|
||||
assert!(!arguments.is_empty());
|
||||
|
|
|
|||
1627
services/flysim/crates/fly-session/src/legacy_env.rs
Normal file
1627
services/flysim/crates/fly-session/src/legacy_env.rs
Normal file
File diff suppressed because it is too large
Load diff
1544
services/flysim/crates/fly-session/src/legacy_env_parity.rs
Normal file
1544
services/flysim/crates/fly-session/src/legacy_env_parity.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -30,6 +30,8 @@ pub mod environment;
|
|||
pub mod harness;
|
||||
pub mod launcher;
|
||||
pub mod legacy_agent;
|
||||
pub mod legacy_env;
|
||||
pub mod legacy_env_parity;
|
||||
pub mod legacy_parity;
|
||||
pub mod measure;
|
||||
pub mod media;
|
||||
|
|
|
|||
|
|
@ -208,6 +208,10 @@ pub enum Terminal {
|
|||
Counter(i64),
|
||||
/// This many transitions were evaluated.
|
||||
AfterTransitions(u64),
|
||||
/// After this many transitions, ask for a *rollback* instead: the request a composition with
|
||||
/// a declared rollback policy may make, and one without it must treat as a task failure
|
||||
/// (`workers-v1` section 4, 2026-09-23). Only a test asks the counter task for this.
|
||||
RollbackAfterTransitions(u64),
|
||||
}
|
||||
|
||||
/// The deterministic counter task: rewards come from the arena counter each agent moved.
|
||||
|
|
@ -404,15 +408,36 @@ impl Task for CounterTask {
|
|||
let terminal = match self.terminal {
|
||||
Terminal::Never => false,
|
||||
Terminal::Counter(target) => new >= target,
|
||||
Terminal::AfterTransitions(n) => self.transitions >= n,
|
||||
Terminal::AfterTransitions(n) | Terminal::RollbackAfterTransitions(n) => {
|
||||
self.transitions >= n
|
||||
}
|
||||
};
|
||||
// The synthetic task only ever asks for the end of the episode; `rollback` belongs to a
|
||||
// composition that declares a rollback policy (workers-v1 section 4, 2026-09-23).
|
||||
let episode = terminal.then(|| EpisodeRequest {
|
||||
let rollback = matches!(self.terminal, Terminal::RollbackAfterTransitions(_));
|
||||
// The synthetic task asks for the end of the episode; `rollback` belongs to a composition
|
||||
// that declares a rollback policy (workers-v1 section 4, 2026-09-23), and the synthetic
|
||||
// composition declares none, so asking for one is how a test meets the refusal.
|
||||
let episode = terminal.then(|| {
|
||||
if rollback {
|
||||
EpisodeRequest {
|
||||
kind: EpisodeRequestKind::Rollback,
|
||||
reason: id("stall"),
|
||||
outcome: fly_session_types::gameboy::RollbackRequest {
|
||||
slot_id: "best".to_owned(),
|
||||
trigger: "stall".to_owned(),
|
||||
}
|
||||
.to_typed(),
|
||||
}
|
||||
} else {
|
||||
EpisodeRequest {
|
||||
kind: EpisodeRequestKind::Terminal,
|
||||
reason: id("counter-target"),
|
||||
outcome: TypedValue::new(episode_schema(), json!({"counter": new, "transitions": self.transitions}))
|
||||
outcome: TypedValue::new(
|
||||
episode_schema(),
|
||||
json!({"counter": new, "transitions": self.transitions}),
|
||||
)
|
||||
.expect("a synthetic typed value fits the contract"),
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(Evaluation {
|
||||
outcomes,
|
||||
|
|
|
|||
634
services/flysim/crates/fly-session/tests/legacy_env.rs
Normal file
634
services/flysim/crates/fly-session/tests/legacy_env.rs
Normal file
|
|
@ -0,0 +1,634 @@
|
|||
//! ENV-01: the Game Boy compatibility environment worker against the emulator driven directly the
|
||||
//! way flysim drives it, in every execution mode, plus its refusals.
|
||||
//!
|
||||
//! Without a cartridge the toy cartridge runs (our own program, assembled by the harness), and
|
||||
//! its records are the committed goldens. With `FLY_ROM` (rom-env) the real cartridge runs from a
|
||||
//! `FLYSIM01` checkpoint; with `FLY_ENV01_TRACE_DIR` the service's own `FLY_TRACE`s are replayed.
|
||||
//! Each ROM job prints `skipped: ...` and passes when its inputs are not installed.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use fly_session::launcher::ExecutionMode;
|
||||
use fly_session::legacy_env::{self, BackendConfig, WorldState};
|
||||
use fly_session::legacy_env_parity::{
|
||||
self as parity, EnvRig, EnvScript, EnvStart, FlyTrace, button_walk, compare, golden_json,
|
||||
run_direct, run_on_worker, scripted, toy_cart, toy_script,
|
||||
};
|
||||
use fly_session::types::*;
|
||||
use fly_session_types::extensions::{
|
||||
METHOD_RESTORE_SLOT, METHOD_SAVE_SLOT, RestoreSlotParams, SLOTS_CAPABILITY, SaveSlotParams,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
macro_rules! all_modes {
|
||||
($($name:ident),* $(,)?) => {
|
||||
mod in_process {
|
||||
$(
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn $name() {
|
||||
super::$name(fly_session::launcher::ExecutionMode::InProcess).await
|
||||
}
|
||||
)*
|
||||
}
|
||||
mod thread {
|
||||
$(
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn $name() {
|
||||
super::$name(fly_session::launcher::ExecutionMode::Thread).await
|
||||
}
|
||||
)*
|
||||
}
|
||||
mod process {
|
||||
$(
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn $name() {
|
||||
super::$name(fly_session::launcher::ExecutionMode::Process).await
|
||||
}
|
||||
)*
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
struct Toy {
|
||||
_dir: tempfile::TempDir,
|
||||
path: PathBuf,
|
||||
rom: Arc<Vec<u8>>,
|
||||
backend: BackendConfig,
|
||||
}
|
||||
|
||||
/// The toy cartridge in a temporary file (outside the checkout), with its backend configuration.
|
||||
fn toy(variant: u8) -> Toy {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let rom = toy_cart::rom(variant);
|
||||
let path = dir.path().join("toy.cart");
|
||||
std::fs::write(&path, &rom).expect("write the toy cartridge");
|
||||
let backend = BackendConfig::legacy(&digest_of_bytes(&rom));
|
||||
Toy {
|
||||
_dir: dir,
|
||||
path,
|
||||
rom: Arc::new(rom),
|
||||
backend,
|
||||
}
|
||||
}
|
||||
|
||||
async fn rig(
|
||||
mode: ExecutionMode,
|
||||
path: &Path,
|
||||
backend: &BackendConfig,
|
||||
) -> (tempfile::TempDir, EnvRig) {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let rig = EnvRig::start(dir.path(), mode, path, backend.clone())
|
||||
.await
|
||||
.expect("the rig starts");
|
||||
(dir, rig)
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------
|
||||
// The toy cartridge: the harness's own inputs reach frames, memory and audio
|
||||
|
||||
#[test]
|
||||
fn the_toy_cartridge_turns_every_input_into_frames_memory_and_audio() {
|
||||
let toy = toy(0);
|
||||
let script = |mask: u8| EnvScript {
|
||||
name: "one".into(),
|
||||
start: EnvStart::Fresh,
|
||||
ops: (0..30).map(|_| parity::EnvOp::Advance(mask)).collect(),
|
||||
};
|
||||
let quiet = run_direct(toy.rom.clone(), &toy.backend, &script(0)).unwrap();
|
||||
let pressed = run_direct(
|
||||
toy.rom.clone(),
|
||||
&toy.backend,
|
||||
&script(flybrain_gb::emulator::buttons::A),
|
||||
)
|
||||
.unwrap();
|
||||
let last = |r: &[parity::EnvRecord]| r.last().unwrap().clone();
|
||||
assert_ne!(
|
||||
last(&quiet).frame,
|
||||
last(&pressed).frame,
|
||||
"the pad reaches the screen"
|
||||
);
|
||||
assert_ne!(
|
||||
last(&quiet).memory,
|
||||
last(&pressed).memory,
|
||||
"the pad reaches memory"
|
||||
);
|
||||
assert_ne!(
|
||||
last(&quiet).audio.unwrap().digest,
|
||||
last(&pressed).audio.unwrap().digest,
|
||||
"and the APU"
|
||||
);
|
||||
// Frames move with no input at all (the scroll follows the frame count).
|
||||
assert_ne!(quiet[5].frame, quiet[6].frame);
|
||||
// O[0] is after the one-frame scaffold, and carries no audio.
|
||||
assert_eq!(quiet[0].engine_frame, 1);
|
||||
assert_eq!(quiet[0].boundary, 0);
|
||||
assert!(quiet[0].audio.is_none());
|
||||
// ~804 stereo frames per Game Boy frame at 48 kHz, contiguous.
|
||||
let a = quiet[1].audio.clone().unwrap();
|
||||
let b = quiet[2].audio.clone().unwrap();
|
||||
assert!((790..=820).contains(&a.frames), "{}", a.frames);
|
||||
assert_eq!(b.first_sample, a.first_sample + a.frames);
|
||||
// A variant is another cartridge.
|
||||
assert_ne!(toy_cart::rom(0), toy_cart::rom(1));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------
|
||||
// Goldens and parity in every mode
|
||||
|
||||
async fn the_toy_golden_holds(mode: ExecutionMode) {
|
||||
let toy = toy(0);
|
||||
let script = toy_script();
|
||||
let direct =
|
||||
run_direct(toy.rom.clone(), &toy.backend, &script).expect("the direct reference runs");
|
||||
let (_dir, mut rig) = rig(mode, &toy.path, &toy.backend).await;
|
||||
let worker = run_on_worker(&mut rig, &script)
|
||||
.await
|
||||
.expect("the worker runs the script");
|
||||
rig.stop().await;
|
||||
compare(&direct, &worker).expect("the worker is the emulator driven directly");
|
||||
|
||||
let golden = golden_json(&script, &worker);
|
||||
let path = parity::toy_golden_path();
|
||||
if std::env::var_os("FLY_UPDATE_FIXTURES").is_some() && mode == ExecutionMode::InProcess {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let text = serde_json::to_string_pretty(&golden).unwrap() + "\n";
|
||||
std::fs::write(&path, text).unwrap();
|
||||
}
|
||||
let committed: Value =
|
||||
serde_json::from_str(&std::fs::read_to_string(&path).expect("the golden is committed"))
|
||||
.unwrap();
|
||||
let (want, got) = (
|
||||
committed["records"].as_array().unwrap(),
|
||||
golden["records"].as_array().unwrap(),
|
||||
);
|
||||
for (i, (w, g)) in want.iter().zip(got).enumerate() {
|
||||
assert_eq!(
|
||||
w,
|
||||
g,
|
||||
"{}: record {i} differs from the golden (FLY_UPDATE_FIXTURES=1 rewrites it)",
|
||||
mode.label()
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
committed,
|
||||
golden,
|
||||
"{} differs from the golden",
|
||||
mode.label()
|
||||
);
|
||||
|
||||
// The script exercised every path, and the records show them.
|
||||
let ops: Vec<&str> = worker.iter().map(|r| r.op).collect();
|
||||
for op in [
|
||||
"initialize",
|
||||
"advance",
|
||||
"save-slot",
|
||||
"rollback",
|
||||
"capture",
|
||||
"restore",
|
||||
] {
|
||||
assert!(ops.contains(&op), "no {op}");
|
||||
}
|
||||
// A rollback lands on the slot's frame and memory, at the same boundary, with the next chunk a
|
||||
// discontinuity; a restore lands on the captured world.
|
||||
for (i, r) in worker.iter().enumerate() {
|
||||
match r.op {
|
||||
"rollback" => {
|
||||
assert_eq!(r.boundary, worker[i - 1].boundary);
|
||||
assert!(r.audio.is_none());
|
||||
let next = worker[i + 1..].iter().find(|n| n.op == "advance").unwrap();
|
||||
assert!(next.audio.as_ref().unwrap().discontinuity);
|
||||
}
|
||||
"restore" => {
|
||||
let capture = &worker[i - 1];
|
||||
assert_eq!(capture.op, "capture");
|
||||
assert_eq!(
|
||||
(r.frame.as_str(), r.memory.as_str()),
|
||||
(capture.frame.as_str(), capture.memory.as_str())
|
||||
);
|
||||
}
|
||||
"advance" => assert_eq!(r.engine_frame, r.boundary + 1),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------
|
||||
// Refusals
|
||||
|
||||
fn code(result: Result<fly_session::rpc::DomainReply, DomainError>) -> ErrorCode {
|
||||
match result {
|
||||
Ok(reply) => reply.result().expect_err("the worker refused").code,
|
||||
Err(e) => e.code,
|
||||
}
|
||||
}
|
||||
|
||||
async fn refusals(mode: ExecutionMode) {
|
||||
let other = toy(1);
|
||||
let toy = toy(0);
|
||||
let (_dir, rig) = rig(mode, &toy.path, &toy.backend).await;
|
||||
|
||||
let mut driver = rig.driver();
|
||||
// Another backend configuration -- another scaffold, another slot set -- is another profile.
|
||||
for tweak in [
|
||||
|b: &mut BackendConfig| b.setup_frames = 0,
|
||||
|b: &mut BackendConfig| b.slots = vec![id("best"), id("spare")],
|
||||
|b: &mut BackendConfig| b.audio_sample_rate = 44_100,
|
||||
] {
|
||||
let mut params = driver.initialize_params();
|
||||
let mut backend = toy.backend.clone();
|
||||
tweak(&mut backend);
|
||||
params.backend_config = backend.asset_ref();
|
||||
let refused = driver
|
||||
.call_raw(
|
||||
"Environment.Initialize",
|
||||
Some(driver.scope()),
|
||||
params.to_json(),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(code(refused), ErrorCode::IncompatibleState);
|
||||
}
|
||||
// Two ports, or a port the composition does not declare.
|
||||
let mut params = driver.initialize_params();
|
||||
params.port_bindings = vec![(id("p2"), id("fly"))];
|
||||
assert_eq!(
|
||||
code(
|
||||
driver
|
||||
.call_raw(
|
||||
"Environment.Initialize",
|
||||
Some(driver.scope()),
|
||||
params.to_json(),
|
||||
&[]
|
||||
)
|
||||
.await
|
||||
),
|
||||
ErrorCode::IdentityMismatch
|
||||
);
|
||||
// Nothing moved: the right configuration still initializes.
|
||||
let first = driver
|
||||
.initialize()
|
||||
.await
|
||||
.expect("the declared configuration initializes");
|
||||
assert_eq!(first.engine_frame, 1);
|
||||
|
||||
// An incomplete joypad batch, a batch for another port, an axis.
|
||||
let scope = driver.scope();
|
||||
let mut bad = driver.advance_params(0);
|
||||
bad.controls[0].buttons.pop();
|
||||
assert_eq!(
|
||||
code(
|
||||
driver
|
||||
.call_raw(
|
||||
"Environment.Advance",
|
||||
Some(scope.clone()),
|
||||
bad.to_json(),
|
||||
&[]
|
||||
)
|
||||
.await
|
||||
),
|
||||
ErrorCode::InvalidArgument
|
||||
);
|
||||
let mut bad = driver.advance_params(0);
|
||||
bad.controls[0].port_id = id("p2");
|
||||
assert_eq!(
|
||||
code(
|
||||
driver
|
||||
.call_raw(
|
||||
"Environment.Advance",
|
||||
Some(scope.clone()),
|
||||
bad.to_json(),
|
||||
&[]
|
||||
)
|
||||
.await
|
||||
),
|
||||
ErrorCode::InvalidArgument
|
||||
);
|
||||
driver.advance(0).await.expect("a complete batch advances");
|
||||
|
||||
// A slot the composition does not declare; a slot never saved.
|
||||
let save = SaveSlotParams {
|
||||
slot_id: id("spare"),
|
||||
};
|
||||
assert_eq!(
|
||||
code(
|
||||
driver
|
||||
.call_raw(METHOD_SAVE_SLOT, Some(driver.scope()), save.to_json(), &[])
|
||||
.await
|
||||
),
|
||||
ErrorCode::InvalidArgument
|
||||
);
|
||||
let mut next = driver.scope();
|
||||
next.epoch = id("e9");
|
||||
let restore = driver.restore_slot_params(&id("best"));
|
||||
assert_eq!(
|
||||
code(
|
||||
driver
|
||||
.call_raw(
|
||||
METHOD_RESTORE_SLOT,
|
||||
Some(next.clone()),
|
||||
restore.to_json(),
|
||||
&[]
|
||||
)
|
||||
.await
|
||||
),
|
||||
ErrorCode::InvalidPhase
|
||||
);
|
||||
// A rollback that does not change epoch.
|
||||
assert_eq!(
|
||||
code(
|
||||
driver
|
||||
.call_raw(
|
||||
METHOD_RESTORE_SLOT,
|
||||
Some(driver.scope()),
|
||||
restore.to_json(),
|
||||
&[]
|
||||
)
|
||||
.await
|
||||
),
|
||||
ErrorCode::InvalidArgument
|
||||
);
|
||||
|
||||
// A duplicate RestoreSlot replays the cached reply; it does not roll back twice.
|
||||
driver.save_slot(&id("best")).await.unwrap();
|
||||
driver
|
||||
.advance(flybrain_gb::emulator::buttons::A)
|
||||
.await
|
||||
.unwrap();
|
||||
let request = RestoreSlotParams {
|
||||
slot_id: id("best"),
|
||||
prior_epoch: id("e1"),
|
||||
policy: "legacy-ratchet-rollback-v1".into(),
|
||||
};
|
||||
let scope_e2 = scope_at("legacy", "e2", driver.boundary());
|
||||
let once = driver
|
||||
.call_raw(
|
||||
METHOD_RESTORE_SLOT,
|
||||
Some(scope_e2.clone()),
|
||||
request.to_json(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let again = driver
|
||||
.retry_raw(
|
||||
once.request_id.clone(),
|
||||
METHOD_RESTORE_SLOT,
|
||||
Some(scope_e2.clone()),
|
||||
request.to_json(),
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
once.result().unwrap(),
|
||||
again.result().unwrap(),
|
||||
"the duplicate replays"
|
||||
);
|
||||
// The old epoch is gone.
|
||||
let stale = driver.advance_params(0);
|
||||
assert_eq!(
|
||||
code(
|
||||
driver
|
||||
.call_raw(
|
||||
"Environment.Advance",
|
||||
Some(driver.scope()),
|
||||
stale.to_json(),
|
||||
&[]
|
||||
)
|
||||
.await
|
||||
),
|
||||
ErrorCode::StaleEpoch
|
||||
);
|
||||
|
||||
// The rolled-back world is the driver's once it moves to the new epoch.
|
||||
driver.bump_epoch();
|
||||
driver
|
||||
.capture()
|
||||
.await
|
||||
.expect("the world captures at (e2, k)");
|
||||
rig.stop().await;
|
||||
|
||||
// The cartridge on disk is not the one the configuration names: wrong ROM.
|
||||
let (_dir2, rig) = rig_with(mode, &other.path, &toy.backend).await;
|
||||
let mut driver = rig.driver();
|
||||
let refused = driver
|
||||
.call_raw(
|
||||
"Environment.Initialize",
|
||||
Some(driver.scope()),
|
||||
driver.initialize_params().to_json(),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(code(refused), ErrorCode::IncompatibleState);
|
||||
// And a legacy checkpoint of another cartridge does not stage.
|
||||
let mut state = world_of(&toy).await;
|
||||
state.rom_digest = other.backend.rom_digest.clone();
|
||||
let source = scope_at("legacy", "legacy", state.boundary);
|
||||
let payload = driver.payload_of(&state, source.clone()).await.unwrap();
|
||||
let staged = driver
|
||||
.call_raw(
|
||||
"State.StageRestore",
|
||||
Some(scope_at("legacy", "e2", state.boundary)),
|
||||
json!({
|
||||
"checkpointId": payload.result.checkpoint_id,
|
||||
"sourceScope": source.to_json(),
|
||||
"compatibilityDigest": payload.result.compatibility_digest,
|
||||
"payload": payload.artifact.reference().to_json(),
|
||||
}),
|
||||
&[("payload", &payload.artifact)],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(code(staged), ErrorCode::IncompatibleState);
|
||||
let _ = rig.stop().await;
|
||||
|
||||
// A launch configuration that is not the legacy scaffold refuses to initialize at all.
|
||||
let mut two = toy.backend.clone();
|
||||
two.setup_frames = 2;
|
||||
let (_dir3, rig) = rig_with(mode, &toy.path, &two).await;
|
||||
let mut driver = rig.driver();
|
||||
let refused = driver
|
||||
.call_raw(
|
||||
"Environment.Initialize",
|
||||
Some(driver.scope()),
|
||||
driver.initialize_params().to_json(),
|
||||
&[],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(code(refused), ErrorCode::IncompatibleState);
|
||||
rig.stop().await;
|
||||
}
|
||||
|
||||
async fn rig_with(
|
||||
mode: ExecutionMode,
|
||||
path: &Path,
|
||||
backend: &BackendConfig,
|
||||
) -> (tempfile::TempDir, EnvRig) {
|
||||
rig(mode, path, backend).await
|
||||
}
|
||||
|
||||
/// A world of the toy cartridge at a few frames in, as data.
|
||||
async fn world_of(toy: &Toy) -> WorldState {
|
||||
let script = EnvScript {
|
||||
name: "w".into(),
|
||||
start: EnvStart::Fresh,
|
||||
ops: vec![parity::EnvOp::Advance(0); 3],
|
||||
};
|
||||
let (mut direct, _) =
|
||||
parity::DirectEmulator::fresh(toy.rom.clone(), toy.backend.clone()).unwrap();
|
||||
for op in &script.ops {
|
||||
if let parity::EnvOp::Advance(m) = op {
|
||||
direct.advance(*m).unwrap();
|
||||
}
|
||||
}
|
||||
direct.state().unwrap()
|
||||
}
|
||||
|
||||
/// The image read leaves the emulator exactly as the frame left it: the exported state after the
|
||||
/// read is byte for byte the state before it, and the next frame is the frame an unread emulator
|
||||
/// draws. An unguarded 64K read changes the export (binjgb syncs OAM/VRAM/timer/STAT/LY on read),
|
||||
/// which this also shows, so the guard is not vacuous.
|
||||
#[test]
|
||||
fn the_memory_image_leaves_the_emulator_as_it_found_it() {
|
||||
use flybrain_gb::emulator::Emulator;
|
||||
let rom = toy_cart::rom(0);
|
||||
let boot = || {
|
||||
let mut e = Emulator::new(&rom, 48_000, 4_096).unwrap();
|
||||
for m in [0u8, 1, 1, 16, 0] {
|
||||
e.set_buttons(m);
|
||||
e.run_frame().unwrap();
|
||||
let _ = e.take_audio_u8();
|
||||
}
|
||||
e
|
||||
};
|
||||
let mut read = boot();
|
||||
let unread = boot();
|
||||
let before = read.export_state().unwrap();
|
||||
let image = legacy_env::memory_image(&mut read).unwrap();
|
||||
assert_eq!(image.len(), 65_536);
|
||||
assert_eq!(
|
||||
read.export_state().unwrap(),
|
||||
before,
|
||||
"the guarded read is neutral"
|
||||
);
|
||||
for (address, byte) in image.iter().enumerate() {
|
||||
assert_eq!(
|
||||
*byte,
|
||||
unread.read_uncached(address as u16),
|
||||
"byte {address:04x} is fly_gb_read_mem's"
|
||||
);
|
||||
}
|
||||
let mut fresh = boot();
|
||||
let _: Vec<u8> = (0..=u16::MAX).map(|a| fresh.read_uncached(a)).collect();
|
||||
assert_ne!(
|
||||
fresh.export_state().unwrap(),
|
||||
before,
|
||||
"an unguarded read is not neutral"
|
||||
);
|
||||
let mut unread = boot();
|
||||
for e in [&mut read, &mut unread] {
|
||||
e.set_buttons(32);
|
||||
e.run_frame().unwrap();
|
||||
}
|
||||
assert_eq!(read.framebuffer(), unread.framebuffer());
|
||||
assert_eq!(read.export_state().unwrap(), unread.export_state().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_worker_advertises_the_slots_extension() {
|
||||
assert!(legacy_env::capabilities().contains(&id(SLOTS_CAPABILITY)));
|
||||
assert!(legacy_env::capabilities().contains(&id("checkpoint-v1")));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------
|
||||
// The real cartridge (rom-env)
|
||||
|
||||
fn rom_inputs() -> Option<(PathBuf, Arc<Vec<u8>>, BackendConfig)> {
|
||||
let path = PathBuf::from(std::env::var_os("FLY_ROM")?);
|
||||
let rom = std::fs::read(&path).ok()?;
|
||||
let backend = BackendConfig::legacy(&digest_of_bytes(&rom));
|
||||
Some((path, Arc::new(rom), backend))
|
||||
}
|
||||
|
||||
/// The real cartridge from the row-58 checkpoint (`FLY_DOOR_CHECKPOINT`): a 480-frame button walk
|
||||
/// with slot saves, rollbacks (the first onto the checkpoint's own ratchet slot's successor) and
|
||||
/// a restart, direct against the worker, frame by frame.
|
||||
async fn rom_checkpoint_parity(mode: ExecutionMode) {
|
||||
let (Some((path, rom, backend)), Some(checkpoint)) =
|
||||
(rom_inputs(), std::env::var_os("FLY_DOOR_CHECKPOINT"))
|
||||
else {
|
||||
eprintln!("skipped: FLY_ROM or FLY_DOOR_CHECKPOINT is not set");
|
||||
return;
|
||||
};
|
||||
let bytes = Arc::new(std::fs::read(checkpoint).expect("the checkpoint reads"));
|
||||
let mut script = scripted(
|
||||
"rom-row58-480",
|
||||
EnvStart::Flysim01(bytes),
|
||||
&button_walk(480, 58),
|
||||
);
|
||||
// The checkpoint's ratchet slot is restored with the world: roll back onto it first.
|
||||
script
|
||||
.ops
|
||||
.insert(3, parity::EnvOp::Rollback(id(legacy_env::DEFAULT_SLOT)));
|
||||
let direct = run_direct(rom.clone(), &backend, &script).expect("direct");
|
||||
let (_dir, mut rig) = rig(mode, &path, &backend).await;
|
||||
let worker = run_on_worker(&mut rig, &script).await.expect("worker");
|
||||
rig.stop().await;
|
||||
compare(&direct, &worker).expect("the worker is the emulator driven directly");
|
||||
eprintln!(
|
||||
"{}: {} records identical, last {}",
|
||||
mode.label(),
|
||||
worker.len(),
|
||||
worker.last().unwrap().row()
|
||||
);
|
||||
}
|
||||
|
||||
/// FND-01's traces of the running service (`FLY_ENV01_TRACE_DIR`: `<name>.trace.jsonl` with its
|
||||
/// start `<name>.checkpoint`, or the row-58 checkpoint for `r58`): every transition's frame and
|
||||
/// WRAM digest, and every slot save's state digest, reproduced by the worker.
|
||||
async fn service_trace_replay(mode: ExecutionMode) {
|
||||
let (Some((path, rom, backend)), Some(dir)) =
|
||||
(rom_inputs(), std::env::var_os("FLY_ENV01_TRACE_DIR"))
|
||||
else {
|
||||
eprintln!("skipped: FLY_ROM or FLY_ENV01_TRACE_DIR is not set");
|
||||
return;
|
||||
};
|
||||
let dir = PathBuf::from(dir);
|
||||
let limit = std::env::var("FLY_ENV01_TRACE_LIMIT")
|
||||
.ok()
|
||||
.and_then(|n| n.parse().ok());
|
||||
for name in ["rollback", "climb", "r58"] {
|
||||
let trace_path = dir.join(format!("{name}.trace.jsonl"));
|
||||
let checkpoint = if name == "r58" {
|
||||
std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from)
|
||||
} else {
|
||||
Some(dir.join(format!("{name}.checkpoint")))
|
||||
};
|
||||
let Some(checkpoint) = checkpoint.filter(|c| c.is_file() && trace_path.is_file()) else {
|
||||
eprintln!("skipped: {name} trace or checkpoint missing");
|
||||
continue;
|
||||
};
|
||||
let trace = FlyTrace::read(&trace_path, limit).expect("the trace reads");
|
||||
let script = trace.script(name, Arc::new(std::fs::read(&checkpoint).unwrap()));
|
||||
let (_dir, mut rig) = rig(mode, &path, &backend).await;
|
||||
let worker = run_on_worker(&mut rig, &script).await.expect("worker");
|
||||
rig.stop().await;
|
||||
let compared = trace
|
||||
.check(&worker)
|
||||
.unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
let actions: usize = trace.frames.iter().map(|f| f.actions.len()).sum();
|
||||
eprintln!(
|
||||
"{}: {name}: {} transitions, {actions} boundary actions, {compared} values equal the service's",
|
||||
mode.label(),
|
||||
trace.frames.len()
|
||||
);
|
||||
let _ = &rom;
|
||||
}
|
||||
}
|
||||
|
||||
all_modes!(
|
||||
the_toy_golden_holds,
|
||||
refusals,
|
||||
rom_checkpoint_parity,
|
||||
service_trace_replay
|
||||
);
|
||||
|
|
@ -24,6 +24,8 @@ both_transports!(
|
|||
bootstrap_cannot_advance_the_world_or_produce_a_reward,
|
||||
the_committed_snapshot_names_the_boundary_that_just_ended,
|
||||
a_terminal_episode_pauses_at_its_own_boundary,
|
||||
a_rollback_request_without_a_declared_policy_fails_the_epoch,
|
||||
a_declared_rollback_policy_holds_the_session_at_its_boundary,
|
||||
status_answers_with_the_committed_boundary,
|
||||
a_worker_refuses_a_second_initialize,
|
||||
a_single_agent_composition_runs_the_same_transaction,
|
||||
|
|
@ -308,6 +310,48 @@ async fn a_terminal_episode_pauses_at_its_own_boundary(via: Via) {
|
|||
f.shutdown().await;
|
||||
}
|
||||
|
||||
/// `workers-v1` section 4 (2026-09-23): a composition that declares no rollback policy treats a
|
||||
/// rollback request as a task failure. The transition does not commit and the epoch is fenced.
|
||||
async fn a_rollback_request_without_a_declared_policy_fails_the_epoch(via: Via) {
|
||||
let config = HarnessConfig {
|
||||
terminal: fly_session::task::Terminal::RollbackAfterTransitions(2),
|
||||
..HarnessConfig::default()
|
||||
};
|
||||
let mut f = fixture(via, config).await;
|
||||
within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap();
|
||||
assert!(f.harness.coordinator.rollback_policy().is_none());
|
||||
within("step 1", f.harness.coordinator.step()).await.unwrap();
|
||||
let err = within("step 2", f.harness.coordinator.step()).await.expect_err("refused");
|
||||
assert_eq!(err.error.code, ErrorCode::Unsupported);
|
||||
assert!(err.error.message.contains("no rollback policy"), "{}", err.error.message);
|
||||
assert!(f.harness.coordinator.is_fenced());
|
||||
assert_eq!(f.harness.coordinator.stats().commits, 2, "two agents committed transition 1; transition 2 committed nothing");
|
||||
f.shutdown().await;
|
||||
}
|
||||
|
||||
/// With `legacy-ratchet-rollback-v1` declared the request is accepted: the transition commits and
|
||||
/// the session holds at its boundary with the request recorded, for the policy to run.
|
||||
async fn a_declared_rollback_policy_holds_the_session_at_its_boundary(via: Via) {
|
||||
let config = HarnessConfig {
|
||||
terminal: fly_session::task::Terminal::RollbackAfterTransitions(2),
|
||||
..HarnessConfig::default()
|
||||
};
|
||||
let mut f = fixture(via, config).await;
|
||||
f.harness
|
||||
.coordinator
|
||||
.declare_rollback_policy("legacy-ratchet-rollback-v1")
|
||||
.unwrap();
|
||||
assert!(f.harness.coordinator.declare_rollback_policy("reset-everything").is_err());
|
||||
within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap();
|
||||
let reports = within("run", f.harness.coordinator.run(4)).await.unwrap();
|
||||
assert_eq!(reports.len(), 2);
|
||||
assert!(!f.harness.coordinator.is_fenced());
|
||||
assert_eq!(f.harness.coordinator.phase(), Phase::Paused(2));
|
||||
let request = f.harness.coordinator.episode_request().unwrap();
|
||||
assert_eq!(request.kind, EpisodeRequestKind::Rollback);
|
||||
f.shutdown().await;
|
||||
}
|
||||
|
||||
/// `Worker.Status` answers with the worker's own committed boundary and progress.
|
||||
async fn status_answers_with_the_committed_boundary(via: Via) {
|
||||
let mut f = default_fixture(via).await;
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue