Merge port/task-01 (TASK-01 review fixes) into port/serve-01

Takes the artifact-backed task ledger (B1), the pending pulse (N1), the
palette seed (N3), queue_save/completed_saves (N4) and the bounded history
and concurrent seals (N5). The service host now queues its saves through
TASK-01's queue_save; SERVE-01's save_queued is gone.
This commit is contained in:
acamilo 2026-09-29 21:29:31 +00:00
commit 5cf40c3148
19 changed files with 1044 additions and 194 deletions

View file

@ -575,7 +575,7 @@ until `fly-runtime session` is run on a container.
startup durable save, then per frame the command drain, `Coordinator::step`, the task's macro startup durable save, then per frame the command drain, `Coordinator::step`, the task's macro
and reward events, the rank and its milestone archive, the deferred ratchet rollback with its and reward events, the rank and its milestone archive, the deferred ratchet rollback with its
recovery event and durable save, the 30 Hz publish, the hot (5 s) and durable (300 s) wall-clock recovery event and durable save, the 30 Hz publish, the hot (5 s) and durable (300 s) wall-clock
saves, the event log fsync and flysim's `Pacer`. Saves are queued (`save_queued`) so the saves, the event log fsync and flysim's `Pacer`. Saves are queued (`queue_save`, TASK-01) so the
encoding and the fsyncs stay off the loop, as the legacy writer thread keeps them. encoding and the fsyncs stay off the loop, as the legacy writer thread keeps them.
- **Where each header field comes from.** The frame is the committed `lcd` view; the audio is - **Where each header field comes from.** The frame is the committed `lcd` view; the audio is
each transition's `apu` chunk through the legacy DC blocker (`DcBlocker::process_f32_into`, each transition's `apu` chunk through the legacy DC blocker (`DcBlocker::process_f32_into`,

View file

@ -6,6 +6,9 @@
//! changed is the pulse they read: the agent's `stimulusRemainingMs` from the **last completed //! 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 //! 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. //! 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 //! 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 //! operator turns `control.allow_reward` on (it is off in every shipped configuration); the new
@ -77,7 +80,15 @@ impl LegacyAdmission {
retry_after_ms: UNKNOWN_PULSE_RETRY_MS, retry_after_ms: UNKNOWN_PULSE_RETRY_MS,
}); });
}; };
self.limiter.admit(now_ms, remaining)?; // 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 (TASK-01 review N1).
let pending = self
.queue
.pending_stimulus_ms(&self.agent_id)
.unwrap_or(0.0);
self.limiter.admit(now_ms, remaining.max(pending))?;
let duration = duration_ms let duration = duration_ms
.unwrap_or(self.default_ms) .unwrap_or(self.default_ms)
.clamp(1.0, self.max_ms) .clamp(1.0, self.max_ms)

View file

@ -38,6 +38,9 @@ fn grants(f: impl FnOnce(&mut Grants)) -> Grants {
g g
} }
/// The transitions a service session keeps in memory for diagnosis (about a minute at 60 Hz).
const HISTORY: usize = 4096;
const COORDINATOR_CLIENT: &str = "coordinator"; const COORDINATOR_CLIENT: &str = "coordinator";
const ENV_CLIENT: &str = "legacy-world"; const ENV_CLIENT: &str = "legacy-world";
const ENV_SERVICE: &str = "env.world"; const ENV_SERVICE: &str = "env.world";
@ -88,6 +91,8 @@ pub struct LegacySession {
/// The legacy store policy, once attached ([`LegacySession::attach_store`]). /// The legacy store policy, once attached ([`LegacySession::attach_store`]).
checkpointer: Option<LegacyCheckpointer>, checkpointer: Option<LegacyCheckpointer>,
saves: u64, saves: u64,
/// Saves on the writer thread whose outcome has not been collected.
pending_saves: Vec<SaveTicket>,
/// The feed event log's watermark the saves record: the restored file's, carried over (the /// 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). /// session runtime has no feed event log of its own before EDGE-01).
last_event_id: u64, last_event_id: u64,
@ -251,6 +256,14 @@ pub async fn boot_unsaved(
Ok((session, boot)) 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<u32>,
}
/// One transition as a parity run sees it. /// One transition as a parity run sees it.
pub struct Step { pub struct Step {
pub report: StepReport, pub report: StepReport,
@ -410,6 +423,9 @@ impl LegacySession {
// itself; a parity run is a measurement. // itself; a parity run is a measurement.
if config.record { if config.record {
coordinator.request_commit_attachments(&[SPIKES_ATTACHMENT]); coordinator.request_commit_attachments(&[SPIKES_ATTACHMENT]);
} else {
// A service session runs indefinitely: its in-memory history stays bounded.
coordinator.bound_history(HISTORY);
} }
Ok(LegacySession { Ok(LegacySession {
coordinator, coordinator,
@ -422,6 +438,7 @@ impl LegacySession {
world_generation: 1, world_generation: 1,
checkpointer: None, checkpointer: None,
saves: 0, saves: 0,
pending_saves: Vec::new(),
last_event_id: 0, last_event_id: 0,
}) })
} }
@ -560,11 +577,22 @@ impl LegacySession {
self.last_event_id = last_event_id; self.last_event_id = last_event_id;
} }
/// One save of the committed boundary, queued on the checkpointer's writer thread without /// One save of the committed boundary, written by the checkpointer's writer thread; waits for
/// waiting for it: the capture is taken now (so it is this boundary), the encoding and the /// the commit, so a caller that goes on to read the store finds it. For the startup and
/// fsyncs happen off the loop, and the ticket resolves when the writer committed it. This is /// shutdown saves, which the legacy loop takes blocking too.
/// the legacy loop's `checkpoint` (SERVE-01); [`LegacySession::save`] waits. pub async fn save(&mut self, kind: SaveKind) -> Result<SaveReport, String> {
pub async fn save_queued(&mut self, kind: SaveKind) -> Result<SaveTicket, String> { 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<SaveTicket, String> {
self.saves += 1; self.saves += 1;
let (boundary, world, agents) = self let (boundary, world, agents) = self
.coordinator .coordinator
@ -585,21 +613,36 @@ impl LegacySession {
checkpointer.save(kind, capture, last_event_id, now_wall_ms()) checkpointer.save(kind, capture, last_event_id, now_wall_ms())
} }
/// One save of the committed boundary, written by the checkpointer's writer thread; waits for /// The saves queued so far that have committed (or failed), without waiting; with `wait`,
/// the commit, so a caller that goes on to read the store finds it. /// every queued save's outcome. A failed save is an error: the caller decides.
pub async fn save(&mut self, kind: SaveKind) -> Result<SaveReport, String> { pub async fn completed_saves(&mut self, wait: bool) -> Result<Vec<SaveReport>, String> {
let ticket = self.save_queued(kind).await?; let mut done = Vec::new();
ticket let mut still = Vec::new();
.reply for mut ticket in std::mem::take(&mut self.pending_saves) {
.await let outcome = if wait {
.map_err(|_| "the checkpoint writer stopped".to_owned())? Some((&mut ticket.reply).await.map_err(|_| ()))
} else {
match ticket.reply.try_recv() {
Ok(result) => Some(Ok(result)),
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => None,
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => Some(Err(())),
}
};
match outcome {
None => still.push(ticket),
Some(Ok(result)) => done.push(result?),
Some(Err(())) => return Err("the checkpoint writer stopped".to_owned()),
}
}
self.pending_saves = still;
Ok(done)
} }
/// One transition and what the legacy loop does at the boundary it reaches, in the declared /// 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 /// 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 /// milestone archive when the rank climbed (`Sim::track_rank`), the rollback, a durable save
/// after it, then the interval saves (`checkpoint_if_due`). /// after it, then the interval saves (`checkpoint_if_due`).
pub async fn advance(&mut self) -> Result<(Step, Vec<SaveReport>), String> { pub async fn advance(&mut self) -> Result<(Step, Vec<SaveQueued>), String> {
let report = self let report = self
.coordinator .coordinator
.step() .step()
@ -615,7 +658,13 @@ impl LegacySession {
.expect("attached") .expect("attached")
.observe_rank(rank, ms); .observe_rank(rank, ms);
if let Some(RankChange::Climbed(rank)) = change { if let Some(RankChange::Climbed(rank)) = change {
saves.push(self.save(SaveKind::Milestone(rank)).await?); let ticket = self.queue_save(SaveKind::Milestone(rank)).await?;
saves.push(SaveQueued {
generation: ticket.generation,
durable: ticket.durable,
archive_rank: ticket.archive_rank,
});
self.pending_saves.push(ticket);
} }
} }
let rolled_back = self let rolled_back = self
@ -630,7 +679,13 @@ impl LegacySession {
})?; })?;
if self.checkpointer.is_some() { if self.checkpointer.is_some() {
if rolled_back { if rolled_back {
saves.push(self.save(SaveKind::Durable).await?); let ticket = self.queue_save(SaveKind::Durable).await?;
saves.push(SaveQueued {
generation: ticket.generation,
durable: ticket.durable,
archive_rank: ticket.archive_rank,
});
self.pending_saves.push(ticket);
} }
let due = self let due = self
.checkpointer .checkpointer
@ -638,7 +693,13 @@ impl LegacySession {
.expect("attached") .expect("attached")
.due(Instant::now()); .due(Instant::now());
if let Some(kind) = due { if let Some(kind) = due {
saves.push(self.save(kind).await?); let ticket = self.queue_save(kind).await?;
saves.push(SaveQueued {
generation: ticket.generation,
durable: ticket.durable,
archive_rank: ticket.archive_rank,
});
self.pending_saves.push(ticket);
} }
} }
Ok(( Ok((
@ -663,6 +724,7 @@ impl LegacySession {
return Ok(None); return Ok(None);
} }
let report = self.save(SaveKind::Durable).await?; let report = self.save(SaveKind::Durable).await?;
self.completed_saves(true).await?;
if let Some(checkpointer) = self.checkpointer.as_mut() { if let Some(checkpointer) = self.checkpointer.as_mut() {
checkpointer.close(); checkpointer.close();
} }

View file

@ -82,10 +82,14 @@ pub async fn import_flysim01(
); );
// The task's ledger, and from it and the restored image the context the agent resumes with. // The task's ledger, and from it and the restored image the context the agent resumes with.
let ledger = PokeredTask::ledger_of(&halves.task, !checkpoint.runtime.ratchet_game.is_empty()); 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; 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 image = image_of(rom, &halves.world.emulator)?;
let context = task.preview_context(&ledger, &image, brain_ms)?; let context = task.preview_context(&ledger, &task_attachments, &image, brain_ms)?;
let payload = agent_payload( let payload = agent_payload(
&halves.agent, &halves.agent,
halves.reinforcements, halves.reinforcements,
@ -115,6 +119,7 @@ pub async fn import_flysim01(
context, context,
}], }],
task_ledger: ledger, task_ledger: ledger,
task_attachments,
audio_positions, audio_positions,
}; };
coordinator coordinator

View file

@ -15,7 +15,7 @@
//! | `drain_commands`: stimulate, reward, chat, checkpoint, pause, resume, shutdown | [`SessionHost::drain_commands`]; sugar by `RateLimiter` over the last commit's pulse, admitted at the next Prepare | //! | `drain_commands`: stimulate, reward, chat, checkpoint, pause, resume, shutdown | [`SessionHost::drain_commands`]; sugar by `RateLimiter` over the last commit's pulse, admitted at the next Prepare |
//! | `step_frame`: the frame, macro/reward events, `track_rank` + milestone archive, ratchet rollback + recovery | [`SessionHost::step_frame`]: `Coordinator::step`, the task's [`crate::task::FeedRecord`], the checkpointer's rank, `apply_pending_rollback` | //! | `step_frame`: the frame, macro/reward events, `track_rank` + milestone archive, ratchet rollback + recovery | [`SessionHost::step_frame`]: `Coordinator::step`, the task's [`crate::task::FeedRecord`], the checkpointer's rank, `apply_pending_rollback` |
//! | `publish`: the header from the network, the adapter and the macro layer | [`SessionHost::publish`]: the agent's `Legacy.FeedStatus`, the task's parts, the committed view, the step's audio and spikes, through flysim's own `feed_*` builders | //! | `publish`: the header from the network, the adapter and the macro layer | [`SessionHost::publish`]: the agent's `Legacy.FeedStatus`, the task's parts, the committed view, the step's audio and spikes, through flysim's own `feed_*` builders |
//! | `checkpoint_if_due` (hot 5 s, durable 300 s, wall clock), pause, forced, shutdown | the same, through [`crate::composition::LegacySession::save_queued`] and STATE-02's `LegacyCheckpointer` | //! | `checkpoint_if_due` (hot 5 s, durable 300 s, wall clock), pause, forced, shutdown | the same, through [`crate::composition::LegacySession::queue_save`] and STATE-02's `LegacyCheckpointer` |
//! | the sugar journal (`crate::journal` of flysim) | the same journal, `runtime: fly-session` | //! | the sugar journal (`crate::journal` of flysim) | the same journal, `runtime: fly-session` |
//! //!
//! Declared differences from the legacy service (SERVE-01, `implementation.md`): //! Declared differences from the legacy service (SERVE-01, `implementation.md`):
@ -1099,7 +1099,7 @@ impl SessionHost {
self.session self.session
.set_last_event_id(self.log.next_id().saturating_sub(1)); .set_last_event_id(self.log.next_id().saturating_sub(1));
let wall_ms = now_wall_ms(); let wall_ms = now_wall_ms();
let ticket = match self.session.save_queued(kind).await { let ticket = match self.session.queue_save(kind).await {
Ok(ticket) => ticket, Ok(ticket) => ticket,
Err(error) => { Err(error) => {
Metrics::incr(&self.shared.metrics.checkpoint_failures_total); Metrics::incr(&self.shared.metrics.checkpoint_failures_total);

View file

@ -51,9 +51,13 @@ pub const MEMORY_ATTACHMENT: &str = fly_session::legacy_env::MEMORY_ATTACHMENT;
pub const SLOT: &str = fly_session::legacy_env::DEFAULT_SLOT; pub const SLOT: &str = fly_session::legacy_env::DEFAULT_SLOT;
/// The game id the adapter and the palette are chosen by. /// The game id the adapter and the palette are chosen by.
pub const GAME: &str = "pokemon-red"; pub const GAME: &str = "pokemon-red";
/// The palette seed. `flybrain_gb::palette_for` carries it for a macro with a random component /// The palette seed of a fresh start. The legacy loop seeds the palette from the brain's RNG
/// and no macro has one (`MacroMachine`'s generator is never read; `macros/tests.rs` proves two /// state after the warm-up (`Sim::boot`: `rng_state() as u32`), which the task cannot read: the
/// seeds press the same buttons), so the legacy loop's `rng_state()` seed is not needed here. /// 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; pub const PALETTE_SEED: u32 = 0;
fn schema(name: &str) -> SchemaRef { fn schema(name: &str) -> SchemaRef {
@ -68,6 +72,9 @@ fn schema(name: &str) -> SchemaRef {
pub fn ledger_schema() -> SchemaRef { pub fn ledger_schema() -> SchemaRef {
schema("pokered-task-ledger-v1") 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"). /// The executor's capture: a marker only, because its state is transient (section 10, "Capture").
pub fn executor_schema() -> SchemaRef { pub fn executor_schema() -> SchemaRef {
schema("pokered.executor.v1") schema("pokered.executor.v1")
@ -210,6 +217,9 @@ struct Inner {
mask: u32, mask: u32,
/// Whether the rollback asked for at the last boundary was a game over (else a stall). /// Whether the rollback asked for at the last boundary was a game over (else a stall).
rollback_game_over: bool, rollback_game_over: bool,
/// 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 /// The one object. [`PokeredTask::task`] and [`PokeredTask::executor`] are its two faces; the
@ -231,7 +241,7 @@ impl PokeredTask {
let cartridge = Cartridge::verified(rom, rom_digest).map_err(|e| e.to_string())?; let cartridge = Cartridge::verified(rom, rom_digest).map_err(|e| e.to_string())?;
let adapter = PokemonRedReward::new(); let adapter = PokemonRedReward::new();
let ratchet = Ratchet::with_policy(adapter.recovery_policy()); let ratchet = Ratchet::with_policy(adapter.recovery_policy());
let macros = fresh_layer(&config); let macros = fresh_layer(&config, PALETTE_SEED);
Ok(Self { Ok(Self {
inner: Arc::new(Mutex::new(Inner { inner: Arc::new(Mutex::new(Inner {
config, config,
@ -252,6 +262,7 @@ impl PokeredTask {
feed: FeedRecord::default(), feed: FeedRecord::default(),
mask: 0, mask: 0,
rollback_game_over: false, rollback_game_over: false,
palette_seed: PALETTE_SEED,
})), })),
}) })
} }
@ -316,6 +327,12 @@ impl PokeredTask {
inner.adapter.rom_allowed(&inner.cartridge.sha256_hex()) inner.adapter.rom_allowed(&inner.cartridge.sha256_hex())
} }
/// 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. /// The records since the last call.
pub fn take_records(&self) -> Vec<TaskRecord> { pub fn take_records(&self) -> Vec<TaskRecord> {
std::mem::take(&mut self.lock().records) std::mem::take(&mut self.lock().records)
@ -329,9 +346,29 @@ impl PokeredTask {
/// The ledger of a task half (STATE-02's `TaskHalf`, FLYSIM01's `reward` and `ratchet`), with /// 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). /// whether the ratchet holds a snapshot (which the environment's slot `best` now holds).
pub fn ledger_of(half: &TaskHalf, slot_filled: bool) -> TypedValue { ///
TypedValue::new(ledger_schema(), half.to_ledger(slot_filled)) /// The adapter's lifetime ledger grows with play and is past the 32 KiB `TypedValue` bound on
.expect("a ledger fits the contract") /// 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<String, Vec<u8>>)> {
// 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 /// The task's half of a FLYSIM01 export at the committed boundary, and whether the slot is
@ -363,12 +400,14 @@ impl PokeredTask {
pub fn preview_context( pub fn preview_context(
&self, &self,
ledger: &TypedValue, ledger: &TypedValue,
attachments: &BTreeMap<String, Vec<u8>>,
image: &MemoryImage, image: &MemoryImage,
ms: f64, ms: f64,
) -> Result<TypedValue, String> { ) -> Result<TypedValue, String> {
let inner = self.lock(); let inner = self.lock();
let (adapter, _ratchet) = parse_ledger(&inner, ledger).map_err(|e| e.message)?; let (adapter, _ratchet) =
let mut layer = fresh_layer(&inner.config); 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() { if let Some(layer) = layer.as_mut() {
let mut reader = ImageReader::new(image, &inner.cartridge); let mut reader = ImageReader::new(image, &inner.cartridge);
let _ = layer.observe(&mut reader, &AdapterLedger(&adapter), ms); let _ = layer.observe(&mut reader, &AdapterLedger(&adapter), ms);
@ -393,11 +432,11 @@ impl PokeredTask {
} }
/// `Sim::boot`'s layer: the configuration's palette at the macro group's hold. /// `Sim::boot`'s layer: the configuration's palette at the macro group's hold.
fn fresh_layer(config: &PokeredConfig) -> Option<MacroLayer> { fn fresh_layer(config: &PokeredConfig, seed: u32) -> Option<MacroLayer> {
let mut service = Config::default(); let mut service = Config::default();
service.loop_.game = GAME.to_owned(); service.loop_.game = GAME.to_owned();
service.macros.mode = config.mode; service.macros.mode = config.mode;
macro_layer(&service, config.hold_ms, PALETTE_SEED) macro_layer(&service, config.hold_ms, seed)
} }
/// The image reader the engine is handed: `ImageReader`, plus a record of any address it was asked /// The image reader the engine is handed: `ImageReader`, plus a record of any address it was asked
@ -793,23 +832,43 @@ impl Task for TaskFace {
fn capture(&self) -> DomainResult<TypedValue> { fn capture(&self) -> DomainResult<TypedValue> {
let (half, slot_filled) = self.0.task_half(); let (half, slot_filled) = self.0.task_half();
Ok(PokeredTask::ledger_of(&half, slot_filled)) PokeredTask::ledger_of(&half, slot_filled).map(|(typed, _)| typed)
}
fn capture_attachments(&self) -> DomainResult<BTreeMap<String, Vec<u8>>> {
let (half, slot_filled) = self.0.task_half();
PokeredTask::ledger_of(&half, slot_filled).map(|(_, attachments)| attachments)
} }
fn validate_restore(&self, state: &TypedValue) -> DomainResult<()> { fn validate_restore(&self, state: &TypedValue) -> DomainResult<()> {
self.validate_restore_with(state, &BTreeMap::new())
}
fn validate_restore_with(
&self,
state: &TypedValue,
attachments: &BTreeMap<String, Vec<u8>>,
) -> DomainResult<()> {
let inner = self.0.lock(); let inner = self.0.lock();
let (adapter, ratchet) = parse_ledger(&inner, state)?; parse_ledger(&inner, state, attachments).map(|_| ())
drop((adapter, ratchet));
Ok(())
} }
fn install_restore(&mut self, epoch: &Id, state: &TypedValue) -> DomainResult<()> { 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<String, Vec<u8>>,
) -> DomainResult<()> {
let mut inner = self.0.lock(); let mut inner = self.0.lock();
let (adapter, ratchet) = parse_ledger(&inner, state)?; let (adapter, ratchet) = parse_ledger(&inner, state, attachments)?;
inner.adapter = adapter; inner.adapter = adapter;
inner.ratchet = ratchet; inner.ratchet = ratchet;
// `legacy-transient-reset`: a fresh executor, nothing running, empty ledgers. // `legacy-transient-reset`: a fresh executor, nothing running, empty ledgers.
inner.macros = fresh_layer(&inner.config); inner.macros = fresh_layer(&inner.config, inner.palette_seed);
inner.current = None; inner.current = None;
inner.open = None; inner.open = None;
inner.feed = FeedRecord::default(); inner.feed = FeedRecord::default();
@ -833,13 +892,32 @@ impl Task for TaskFace {
} }
} }
fn parse_ledger(inner: &Inner, state: &TypedValue) -> DomainResult<(PokemonRedReward, Ratchet)> { fn parse_ledger(
inner: &Inner,
state: &TypedValue,
attachments: &BTreeMap<String, Vec<u8>>,
) -> DomainResult<(PokemonRedReward, Ratchet)> {
if state.schema != ledger_schema() { if state.schema != ledger_schema() {
return Err(state_error( return Err(state_error(
"the captured ledger is not a pokered-macros-v1 ledger", "the captured ledger is not a pokered-macros-v1 ledger",
)); ));
} }
let half = TaskHalf::from_ledger(&state.value).map_err(state_error)?; 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 let slot_filled = state
.value .value
.get("slotFilled") .get("slotFilled")

View file

@ -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<Value> = (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
);
}
}

View file

@ -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");
}

View file

@ -18,7 +18,7 @@ use serde_json::json;
use flybus::{Grants, Pattern, Policy, RouterConfig}; use flybus::{Grants, Pattern, Policy, RouterConfig};
use fly_session::coordinator::{Admission, AdmissionEnd, AgentSlot, Coordinator}; use fly_session::coordinator::{AdmissionEnd, AgentSlot, Coordinator};
use fly_session::fly_session_types::extensions::ROLLBACK_POLICY; use fly_session::fly_session_types::extensions::ROLLBACK_POLICY;
use fly_session::fly_session_types::gameboy::{ use fly_session::fly_session_types::gameboy::{
self, ChannelsDecision, ReadoutContext, RollbackRequest, self, ChannelsDecision, ReadoutContext, RollbackRequest,
@ -377,12 +377,34 @@ async fn run(mode: ExecutionMode) {
let mut actions = Vec::new(); let mut actions = Vec::new();
for k in 0..9u64 { for k in 0..9u64 {
if k == 2 { if k == 2 {
admissions.admit(Admission::Stimulus { // Two sugars before the next commit: the legacy drain admits the first and refuses
agent_id: id("fly"), // the second (its pulse is already active), and so does the session's admission.
interaction_id: id("sugar-1"), let mut legacy = flysim::ratelimit::RateLimiter::new(6);
kind_id: id(gameboy::STIMULUS_REWARD_PULSE), let mut remaining = admissions
duration_ms: 300.0, .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| { let report = coordinator.step().await.unwrap_or_else(|e| {
panic!( panic!(
@ -482,6 +504,11 @@ async fn run(mode: ExecutionMode) {
let ended = admissions.take_ended(); let ended = admissions.take_ended();
assert_eq!(ended.len(), 1); assert_eq!(ended.len(), 1);
assert_eq!(ended[0].1, AdmissionEnd::Applied { boundary: 3 }); 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()); assert!(admissions.stimulus_remaining_ms(&id("fly")).is_some());
let audit = coordinator.audit.join(" "); let audit = coordinator.audit.join(" ");
for needle in [ for needle in [

View file

@ -482,7 +482,7 @@ async fn fafb_service_trace_checkpoints() {
async fn run_booted( async fn run_booted(
session: &mut LegacySession, session: &mut LegacySession,
frames: usize, frames: usize,
) -> (Run, Vec<fly_session::legacy_checkpoint::SaveReport>) { ) -> (Run, Vec<fly_legacy_session::composition::SaveQueued>) {
let mut run = Run { let mut run = Run {
behaviours: Vec::new(), behaviours: Vec::new(),
ledgers: Vec::new(), ledgers: Vec::new(),
@ -525,22 +525,53 @@ async fn run_booted(
async fn fafb_boot_run_save_restore() { async fn fafb_boot_run_save_restore() {
let Some(rom_path) = rom_path() else { return }; let Some(rom_path) = rom_path() else { return };
let Some(dataset) = fafb() else { return }; let Some(dataset) = fafb() else { return };
let source = std::env::var_os("FLY_ENV01_TRACE_DIR") // The rollback file (a ratchet rollback on the first boundary), and the live fly's largest
.map(|dir| PathBuf::from(dir).join("rollback.checkpoint")) // task ledgers: row 64 (42 KB) and the row 65 yard (46 KB), past the 32 KiB TypedValue bound
.filter(|p| p.is_file()) // (TASK-01 review B1). `FLY_TASK01_BOOT_SOURCES` picks others (`name=path,...`).
.or_else(|| std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from)); let sources: Vec<(String, PathBuf)> = match std::env::var("FLY_TASK01_BOOT_SOURCES") {
let Some(source) = source else { 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"); eprintln!("skipping: no source checkpoint");
return; return;
}; }
let rom = std::fs::read(&rom_path).expect("the cartridge"); let rom = std::fs::read(&rom_path).expect("the cartridge");
let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset")); let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset"));
let frames = env_usize("FLY_TASK01_BOOT_FRAMES", 900); let frames = env_usize("FLY_TASK01_BOOT_FRAMES", 900);
for (name, source) in sources {
let original = std::fs::read(&source).expect("the checkpoint"); let original = std::fs::read(&source).expect("the checkpoint");
let generation = flysim::store::decode(&original) let decoded = flysim::store::decode(&original).expect("FLYSIM01");
.expect("FLYSIM01") let generation = decoded.runtime.generation;
.runtime eprintln!(
.generation; "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() { for mode in modes() {
let root = tempfile::tempdir().expect("tmp"); let root = tempfile::tempdir().expect("tmp");
let store = fly_legacy_session::composition::StoreConfig { let store = fly_legacy_session::composition::StoreConfig {
@ -569,8 +600,11 @@ async fn fafb_boot_run_save_restore() {
// Process one. // Process one.
let started = std::time::Instant::now(); let started = std::time::Instant::now();
let (mut one, boot) = let (mut one, boot) = fly_legacy_session::composition::boot(
fly_legacy_session::composition::boot(&root.path().join("p1"), config(mode), &store) &root.path().join("p1"),
config(mode),
&store,
)
.await .await
.unwrap_or_else(|e| panic!("{}: boot one: {e}", mode.label())); .unwrap_or_else(|e| panic!("{}: boot one: {e}", mode.label()));
match &boot { match &boot {
@ -610,7 +644,7 @@ async fn fafb_boot_run_save_restore() {
.unwrap_or_else(|e| panic!("{} segment one: {e}", mode.label())); .unwrap_or_else(|e| panic!("{} segment one: {e}", mode.label()));
compare_ledgers(&legacy_one.ledgers, &run_one.ledgers); compare_ledgers(&legacy_one.ledgers, &run_one.ledgers);
report( report(
&format!("boot segment one, {}", mode.label()), &format!("boot {name} segment one, {}", mode.label()),
&agreement, &agreement,
started.elapsed(), started.elapsed(),
); );
@ -631,8 +665,11 @@ async fn fafb_boot_run_save_restore() {
// Process two: restores process one's shutdown save. // Process two: restores process one's shutdown save.
let started = std::time::Instant::now(); let started = std::time::Instant::now();
let (mut two, boot) = let (mut two, boot) = fly_legacy_session::composition::boot(
fly_legacy_session::composition::boot(&root.path().join("p2"), config(mode), &store) &root.path().join("p2"),
config(mode),
&store,
)
.await .await
.unwrap_or_else(|e| panic!("{}: boot two: {e}", mode.label())); .unwrap_or_else(|e| panic!("{}: boot two: {e}", mode.label()));
let restored_path = match &boot { let restored_path = match &boot {
@ -663,11 +700,12 @@ async fn fafb_boot_run_save_restore() {
.unwrap_or_else(|e| panic!("{} segment two: {e}", mode.label())); .unwrap_or_else(|e| panic!("{} segment two: {e}", mode.label()));
compare_ledgers(&legacy_two.ledgers, &run_two.ledgers); compare_ledgers(&legacy_two.ledgers, &run_two.ledgers);
report( report(
&format!("boot segment two, {}", mode.label()), &format!("boot {name} segment two, {}", mode.label()),
&agreement, &agreement,
started.elapsed(), started.elapsed(),
); );
} }
}
} }
/// Thins a checkpoint's adapter ledger so the fly earns rewards: the current map is unvisited /// Thins a checkpoint's adapter ledger so the fly earns rewards: the current map is unvisited

View file

@ -0,0 +1,183 @@
//! 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;
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;
for n in 0..warmup + frames {
let started = Instant::now();
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 ()).unwrap();
frame
.boundary(&mut parts, &transition.evaluated.progress, transition.ms)
.unwrap();
if n >= warmup {
legacy_ms += started.elapsed().as_secs_f64() * 1000.0;
}
}
drop(agent);
let legacy_per = legacy_ms / frames as f64;
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;
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;
}
}
}

View file

@ -382,6 +382,8 @@ pub struct Coordinator {
/// Leave a requested rollback for the host to apply (`apply_pending_rollback`). /// Leave a requested rollback for the host to apply (`apply_pending_rollback`).
defer_rollbacks: bool, defer_rollbacks: bool,
pending_rollback: Option<(u64, EpisodeRequest)>, pending_rollback: Option<(u64, EpisodeRequest)>,
/// [`Coordinator::bound_history`].
history_limit: Option<usize>,
lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>, lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>,
stats: Stats, stats: Stats,
/// The ordered actions this session took, for the ordering assertions. /// The ordered actions this session took, for the ordering assertions.
@ -502,6 +504,7 @@ impl Coordinator {
state_format_id: None, state_format_id: None,
defer_rollbacks: false, defer_rollbacks: false,
pending_rollback: None, pending_rollback: None,
history_limit: None,
lifecycle_acks: Vec::new(), lifecycle_acks: Vec::new(),
stats: Stats::default(), stats: Stats::default(),
audit: Vec::new(), audit: Vec::new(),
@ -704,6 +707,27 @@ impl Coordinator {
self.state_format_id = Some(id(state_format_id)); 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);
}
fn trim_history(&mut self) {
let Some(keep) = self.history_limit else { return };
fn trim<T>(items: &mut Vec<T>, 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 /// 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 /// [`Coordinator::apply_pending_rollback`] after its own captures there. No transition starts
/// while one is pending. /// while one is pending.
@ -1545,6 +1569,8 @@ pub enum AdmissionEnd {
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct AdmissionState { struct AdmissionState {
queued: Vec<Admission>, queued: Vec<Admission>,
/// Cut into a Prepare whose transition has not committed yet.
in_flight: Vec<Admission>,
remaining: BTreeMap<Id, f64>, remaining: BTreeMap<Id, f64>,
ended: Vec<(Admission, AdmissionEnd)>, ended: Vec<(Admission, AdmissionEnd)>,
} }
@ -1576,18 +1602,41 @@ impl AdmissionQueue {
self.lock().queued.len() 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<f64> {
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. /// Every admission that has ended since the last call, in the order they ended.
pub fn take_ended(&self) -> Vec<(Admission, AdmissionEnd)> { pub fn take_ended(&self) -> Vec<(Admission, AdmissionEnd)> {
std::mem::take(&mut self.lock().ended) std::mem::take(&mut self.lock().ended)
} }
fn cut(&self) -> Vec<Admission> { fn cut(&self) -> Vec<Admission> {
std::mem::take(&mut self.lock().queued) 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<Admission>, end: AdmissionEnd) { fn end(&self, admissions: Vec<Admission>, end: AdmissionEnd) {
let mut state = self.lock(); let mut state = self.lock();
for admission in admissions { for admission in admissions {
state
.in_flight
.retain(|a| a.interaction_id() != admission.interaction_id());
state.ended.push((admission, end.clone())); state.ended.push((admission, end.clone()));
} }
} }
@ -1657,6 +1706,8 @@ pub struct ImportSpec {
/// Every agent, in sorted agent-id order. /// Every agent, in sorted agent-id order.
pub agents: Vec<ImportedAgent>, pub agents: Vec<ImportedAgent>,
pub task_ledger: TypedValue, pub task_ledger: TypedValue,
/// The ledger's attachments (`Task::capture_attachments`), by name.
pub task_attachments: BTreeMap<String, Vec<u8>>,
/// Each declared audio stream's next sample. /// Each declared audio stream's next sample.
pub audio_positions: BTreeMap<String, u64>, pub audio_positions: BTreeMap<String, u64>,
} }
@ -2254,13 +2305,20 @@ impl Coordinator {
// ---- Phase A: prepare all agents concurrently // ---- Phase A: prepare all agents concurrently
self.transition(Phase::Preparing(k))?; self.transition(Phase::Preparing(k))?;
let span = crate::profile::span("coord.prepare");
let prepared = self.prepare_all(k, descriptor.step_duration).await?; let prepared = self.prepare_all(k, descriptor.step_duration).await?;
drop(span);
// ---- Phase B: build and apply one complete batch // ---- Phase B: build and apply one complete batch
self.transition(Phase::Applying(k))?; self.transition(Phase::Applying(k))?;
let span = crate::profile::span("coord.executor");
let controls = self.build_batch(k, &descriptor, &old_observation)?; let controls = self.build_batch(k, &descriptor, &old_observation)?;
drop(span);
let batch_id = self.batch_id(k); let batch_id = self.batch_id(k);
let span = crate::profile::span("coord.advance");
let step_result = self.advance(k, &batch_id, &controls).await?; 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 // ---- Phase C: observe and evaluate the task once
self.transition(Phase::Observing(k + 1))?; self.transition(Phase::Observing(k + 1))?;
@ -2275,6 +2333,8 @@ impl Coordinator {
.current_inspection .current_inspection
.clone() .clone()
.expect("a bootstrapped session holds O[k]'s inspection"); .expect("a bootstrapped session holds O[k]'s inspection");
drop(span);
let span = crate::profile::span("coord.evaluate");
let evaluation = self let evaluation = self
.task .task
.evaluate_transition(&scope, &old_inspection, &new_inspection, &controls) .evaluate_transition(&scope, &old_inspection, &new_inspection, &controls)
@ -2314,8 +2374,10 @@ impl Coordinator {
} }
} }
drop(span);
// ---- Phase D: commit all agent outcomes concurrently // ---- Phase D: commit all agent outcomes concurrently
self.transition(Phase::Committing(k))?; self.transition(Phase::Committing(k))?;
let commit_span = crate::profile::span("coord.commit");
let new_views: BTreeMap<String, flybus::Artifact> = step_result let new_views: BTreeMap<String, flybus::Artifact> = step_result
.observation .observation
.sensory_views .sensory_views
@ -2338,6 +2400,8 @@ impl Coordinator {
.commit_all(k, &step_result.observation, &mut outcomes, &mut next_contexts, &new_views) .commit_all(k, &step_result.observation, &mut outcomes, &mut next_contexts, &new_views)
.await?; .await?;
drop(commit_span);
let span = crate::profile::span("coord.boundary");
// Only once every commit succeeded does the committed boundary move. // Only once every commit succeeded does the committed boundary move.
self.transition(Phase::Ready(k + 1))?; self.transition(Phase::Ready(k + 1))?;
for index in 0..self.agents.len() { for index in 0..self.agents.len() {
@ -2416,6 +2480,8 @@ impl Coordinator {
} }
} }
drop(span);
let span = crate::profile::span("coord.trace_publish");
let event_ids: Vec<Id> = evaluation.events.iter().map(|e| e.id.clone()).collect(); let event_ids: Vec<Id> = evaluation.events.iter().map(|e| e.id.clone()).collect();
let decisions: BTreeMap<Id, TypedValue> = prepared let decisions: BTreeMap<Id, TypedValue> = prepared
.iter() .iter()
@ -2475,8 +2541,10 @@ impl Coordinator {
self.pause.store(false, std::sync::atomic::Ordering::SeqCst); self.pause.store(false, std::sync::atomic::Ordering::SeqCst);
self.audit.push(format!("pause:{}", k + 1)); self.audit.push(format!("pause:{}", k + 1));
} }
drop(span);
// The critical path: one whole transition, pacing sleep included. // The critical path: one whole transition, pacing sleep included.
self.metrics.record("step", step_started.elapsed()); self.metrics.record("step", step_started.elapsed());
self.trim_history();
Ok(StepReport { boundary: k + 1, paused, terminal }) Ok(StepReport { boundary: k + 1, paused, terminal })
} }
@ -4452,6 +4520,22 @@ impl Coordinator {
self.seal_own(crate::state::TASK_LEDGER_PAYLOAD, &ledger.to_json()) self.seal_own(crate::state::TASK_LEDGER_PAYLOAD, &ledger.to_json())
.await?, .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 let inspection = self
.observation .observation
.as_ref() .as_ref()
@ -5026,6 +5110,9 @@ impl Coordinator {
if let Err(e) = own(crate::state::ADMISSION_PAYLOAD, &record) { if let Err(e) = own(crate::state::ADMISSION_PAYLOAD, &record) {
failure = failure.or(Some(e)); 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 { if let Some(e) = failure {
return Err(self.fail_now(e, "import")); return Err(self.fail_now(e, "import"));
} }
@ -5542,7 +5629,7 @@ impl Coordinator {
&manifest.coordinator.task_ledger, &manifest.coordinator.task_ledger,
)?) )?)
.map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; .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 { for (agent_id, name) in &manifest.coordinator.executor_state {
let state = TypedValue::from_json(&Coordinator::read_payload(payloads, name)?) let state = TypedValue::from_json(&Coordinator::read_payload(payloads, name)?)
.map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?;
@ -5643,7 +5730,8 @@ impl Coordinator {
let ledger = TypedValue::from_json(&read(&manifest.coordinator.task_ledger)?) let ledger = TypedValue::from_json(&read(&manifest.coordinator.task_ledger)?)
.map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; .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 { for (agent_id, name) in &manifest.coordinator.executor_state {
let state = TypedValue::from_json(&read(name)?) let state = TypedValue::from_json(&read(name)?)
.map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?;
@ -5709,7 +5797,7 @@ impl Coordinator {
audio_positions.insert(stream.clone(), sample); audio_positions.insert(stream.clone(), sample);
} }
// Everything above validated. From here the coordinator installs, in one pass. // 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 { for (agent_id, name) in &manifest.coordinator.executor_state {
let state = TypedValue::from_json(&read(name)?) let state = TypedValue::from_json(&read(name)?)
.map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?; .map_err(|e| DomainError::before(ErrorCode::IncompatibleState, e.0))?;

View file

@ -1100,7 +1100,9 @@ impl LegacyAgentWorker {
let brain_ticks = accumulator.brain_ticks(); let brain_ticks = accumulator.brain_ticks();
let remainder = accumulator.remainder(); let remainder = accumulator.remainder();
self.transition_start_ms = agent.network.ms; self.transition_start_ms = agent.network.ms;
let ticks_span = crate::profile::span("agent.ticks");
agent.network.step(ticks); agent.network.step(ticks);
drop(ticks_span);
if agent.network.ms != brain_ticks as f64 { if agent.network.ms != brain_ticks as f64 {
return Err(applied( return Err(applied(
ErrorCode::Internal, ErrorCode::Internal,
@ -1205,7 +1207,9 @@ impl LegacyAgentWorker {
} }
let context = self.read_context(&params.next_decision_context)?; let context = self.read_context(&params.next_decision_context)?;
// The complete request and its owned artifact are validated before anything applies. // 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, &params.next_input).await?; let frame = self.read_lcd(ctx, &params.next_input).await?;
drop(read_span);
self.status.set_state(WorkerState::Committing); self.status.set_state(WorkerState::Committing);
let agent = self.agent.as_mut().expect("initialized"); let agent = self.agent.as_mut().expect("initialized");
@ -1234,7 +1238,9 @@ impl LegacyAgentWorker {
self.transient.location = Some(location); self.transient.location = Some(location);
self.transient.blocked_since_ms = ms; 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); 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. // 4. Retain the next context and acknowledge k+1.
let digest = context.digest.clone(); let digest = context.digest.clone();
self.context = Some(context); self.context = Some(context);
@ -1247,6 +1253,7 @@ impl LegacyAgentWorker {
decision_context_digest: digest, decision_context_digest: digest,
telemetry: self.telemetry(), 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) let artifact = crate::media::seal_copy(ctx.client, SPIKES_CONTENT_TYPE.to_owned(), &spikes)
.await .await
.map_err(|e| applied(e.code, e.message))?; .map_err(|e| applied(e.code, e.message))?;

View file

@ -857,10 +857,33 @@ impl LegacyGameboyEnvironment {
client: &flybus::Client, client: &flybus::Client,
audio: Option<Vec<u8>>, audio: Option<Vec<u8>>,
) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> { ) -> DomainResult<(WorldObservation, Vec<(String, flybus::Artifact)>)> {
let frame = let image = {
media::seal_copy(client, FRAME_CONTENT_TYPE.to_owned(), &live.framebuffer).await?; let _span = crate::profile::span("env.image");
let image = memory_image(&mut live.emulator).map_err(backend_failure)?; memory_image(&mut live.emulator).map_err(backend_failure)?
let memory = media::seal_copy(client, MEMORY_CONTENT_TYPE.to_owned(), &image).await?; };
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 { let view = ViewRef {
view_id: gameboy::VIEW_ID.to_owned(), view_id: gameboy::VIEW_ID.to_owned(),
produced_step: live.boundary, produced_step: live.boundary,
@ -876,13 +899,8 @@ impl LegacyGameboyEnvironment {
(MEMORY_ATTACHMENT.to_owned(), memory), (MEMORY_ATTACHMENT.to_owned(), memory),
]; ];
let mut chunks = Vec::new(); let mut chunks = Vec::new();
if let Some(raw) = audio { if let (Some(raw), Some(samples)) = (audio, samples) {
if raw.len() % AUDIO_CHANNELS as usize != 0 {
return Err(backend_failure("binjgb returned half a stereo frame"));
}
let frames = (raw.len() / AUDIO_CHANNELS as usize) as u64; let 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 { chunks.push(AudioRef {
stream_id: id(AUDIO_STREAM_ID), stream_id: id(AUDIO_STREAM_ID),
first_sample: live.audio_next_sample, first_sample: live.audio_next_sample,
@ -1030,6 +1048,7 @@ impl LegacyGameboyEnvironment {
let applied_from = live.boundary; let applied_from = live.boundary;
// `LegacyFrame::run` and `take_frame`: the joypad, one frame, the frame it drew, its audio. // `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.buttons = mask;
live.emulator.set_buttons(mask); live.emulator.set_buttons(mask);
live.emulator live.emulator
@ -1039,6 +1058,7 @@ impl LegacyGameboyEnvironment {
live.framebuffer live.framebuffer
.copy_from_slice(live.emulator.framebuffer()); .copy_from_slice(live.emulator.framebuffer());
let audio = live.emulator.take_audio_u8(); let audio = live.emulator.take_audio_u8();
drop(frame_span);
live.boundary += 1; live.boundary += 1;
live.world_time = live live.world_time = live
.world_time .world_time

View file

@ -38,6 +38,7 @@ pub mod measure;
pub mod media; pub mod media;
pub mod metrics; pub mod metrics;
pub mod phase; pub mod phase;
pub mod profile;
pub mod publish; pub mod publish;
pub mod rpc; pub mod rpc;
pub mod state; pub mod state;

View file

@ -79,6 +79,16 @@ impl Metrics {
pub fn clear(&mut self) { pub fn clear(&mut self) {
self.samples.clear(); 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. /// This process's peak resident set, in KiB, from its own status file.

View file

@ -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<BTreeMap<&'static str, (u64, Duration)>> = 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
}

View file

@ -110,6 +110,28 @@ pub fn executor_payload(agent_id: &str) -> String {
pub const WORLD_PAYLOAD: &str = "world"; pub const WORLD_PAYLOAD: &str = "world";
/// The task ledger's payload name. /// The task ledger's payload name.
pub const TASK_LEDGER_PAYLOAD: &str = "task-ledger"; 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-<name>`.
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<String, Vec<u8>>,
) -> std::collections::BTreeMap<String, Vec<u8>> {
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. /// The prior world inspection's payload name.
pub const PRIOR_INSPECTION_PAYLOAD: &str = "prior-inspection"; pub const PRIOR_INSPECTION_PAYLOAD: &str = "prior-inspection";
/// The coordinator's admission state and event watermarks. /// The coordinator's admission state and event watermarks.

View file

@ -183,6 +183,35 @@ pub trait Task: Send {
/// The checkpointable ledger at a committed boundary (`workers-v1` section 4). /// The checkpointable ledger at a committed boundary (`workers-v1` section 4).
fn capture(&self) -> DomainResult<TypedValue>; fn capture(&self) -> DomainResult<TypedValue>;
/// 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<BTreeMap<String, Vec<u8>>> {
Ok(BTreeMap::new())
}
/// [`Task::validate_restore`] with the ledger's attachments.
fn validate_restore_with(
&self,
state: &TypedValue,
attachments: &BTreeMap<String, Vec<u8>>,
) -> 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<String, Vec<u8>>,
) -> DomainResult<()> {
let _ = attachments;
self.install_restore(epoch, state)
}
/// Validates a captured ledger without installing it, so a group install can fail before /// Validates a captured ledger without installing it, so a group install can fail before
/// anything is changed. /// anything is changed.
fn validate_restore(&self, state: &TypedValue) -> DomainResult<()>; fn validate_restore(&self, state: &TypedValue) -> DomainResult<()>;