TASK-01 review fixes: an artifact-backed task ledger, the pending pulse, the palette seed, queued saves

- B1: the pokered ledger's adapter state travels as an attachment
  ('reward', its JSON) beside a small typed value {reward: {digest,
  byteLength}, ratchet, slotFilled}; Task gains capture_attachments /
  validate_restore_with / install_restore_with, and the coordinator files
  them as task-ledger-<name> payloads in captures and imports. Every
  failure is an IncompatibleState error, so boot falls to the next
  candidate. Tests: ledger_size (past 64 KB, and malformed ones).
- N1: a sugar admitted and not yet reported on by a commit is an active
  pulse (AdmissionQueue::pending_stimulus_ms): two sugars between two
  commits are one admission and one PulseActive, as the legacy drain.
- N3: a restore seeds the palette with the restored brain's RNG state,
  as Sim::boot does; palette_seed holds on the cartridge that two seeds
  press the same buttons (a fresh start's constant is therefore exact).
- N4: interval, milestone and after-rollback saves are queued to the
  checkpointer's writer thread; startup and shutdown saves block.
- Boot parity adds row64 and the row65 yard (the largest ledgers); the
  segments add them too. tests/speed.rs measures N5.
This commit is contained in:
acamilo 2026-09-29 20:47:19 +00:00
parent 7ef16be317
commit 7a61877e78
12 changed files with 880 additions and 175 deletions

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

@ -27,7 +27,7 @@ use flysim::snapshot::MacroMode;
use crate::task::{PokeredConfig, PokeredTask, TaskRecord}; use crate::task::{PokeredConfig, PokeredTask, TaskRecord};
use fly_session::legacy_checkpoint::{ use fly_session::legacy_checkpoint::{
AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind, AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind,
SaveReport, now_wall_ms, SaveReport, SaveTicket, now_wall_ms,
}; };
use flysim::store::Checkpoint; use flysim::store::Checkpoint;
use std::time::Instant; use std::time::Instant;
@ -88,6 +88,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,
@ -238,6 +240,14 @@ pub async fn boot(
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,
@ -409,6 +419,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,
}) })
} }
@ -536,8 +547,21 @@ impl LegacySession {
} }
/// One save of the committed boundary, written by the checkpointer's writer thread; waits for /// One save of the committed boundary, written by the checkpointer's writer thread; waits for
/// the commit, so a caller that goes on to read the store finds it. /// the commit, so a caller that goes on to read the store finds it. For the startup and
/// shutdown saves, which the legacy loop takes blocking too.
pub async fn save(&mut self, kind: SaveKind) -> Result<SaveReport, String> { pub async fn save(&mut self, kind: SaveKind) -> Result<SaveReport, 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
@ -555,18 +579,39 @@ impl LegacySession {
}; };
let last_event_id = self.last_event_id; let last_event_id = self.last_event_id;
let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?; let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?;
let ticket = checkpointer.save(kind, capture, last_event_id, now_wall_ms())?; checkpointer.save(kind, capture, last_event_id, now_wall_ms())
ticket }
.reply
.await /// The saves queued so far that have committed (or failed), without waiting; with `wait`,
.map_err(|_| "the checkpoint writer stopped".to_owned())? /// every queued save's outcome. A failed save is an error: the caller decides.
pub async fn completed_saves(&mut self, wait: bool) -> Result<Vec<SaveReport>, String> {
let mut done = Vec::new();
let mut still = Vec::new();
for mut ticket in std::mem::take(&mut self.pending_saves) {
let outcome = if wait {
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()
@ -582,7 +627,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
@ -597,7 +648,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
@ -605,7 +662,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((
@ -630,6 +693,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

@ -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")
@ -190,6 +197,9 @@ struct Inner {
driver: Option<Box<dyn crate::driver::DecisionDriver>>, driver: Option<Box<dyn crate::driver::DecisionDriver>>,
/// Addresses the engine read that the image does not capture ([`Watched`]). /// Addresses the engine read that the image does not capture ([`Watched`]).
uncaptured: std::collections::BTreeSet<u16>, uncaptured: std::collections::BTreeSet<u16>,
/// 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
@ -211,7 +221,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,
@ -229,6 +239,7 @@ impl PokeredTask {
records: Vec::new(), records: Vec::new(),
driver: None, driver: None,
uncaptured: std::collections::BTreeSet::new(), uncaptured: std::collections::BTreeSet::new(),
palette_seed: PALETTE_SEED,
})), })),
}) })
} }
@ -261,6 +272,12 @@ impl PokeredTask {
self.lock().uncaptured.iter().copied().collect() self.lock().uncaptured.iter().copied().collect()
} }
/// Seeds the next restore's fresh macro layer as the legacy loop does after a restore: with
/// the restored brain's RNG state (`rng_state() as u32`).
pub fn set_palette_seed(&self, seed: u32) {
self.lock().palette_seed = seed;
}
/// The records since the last call. /// 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)
@ -274,9 +291,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
@ -308,12 +345,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);
@ -338,11 +377,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
@ -731,23 +770,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.epoch = epoch.clone(); inner.epoch = epoch.clone();
@ -770,13 +829,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,175 @@
//! 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::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 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 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

@ -1464,6 +1464,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)>,
} }
@ -1495,18 +1497,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()));
} }
} }
@ -1576,6 +1601,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>,
} }
@ -4369,6 +4396,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()
@ -4943,6 +4986,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"));
} }
@ -5459,7 +5505,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))?;
@ -5560,7 +5606,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))?;
@ -5626,7 +5673,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

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