diff --git a/docs/design/session-framework/implementation.md b/docs/design/session-framework/implementation.md index 88bb4d8..85c0baa 100644 --- a/docs/design/session-framework/implementation.md +++ b/docs/design/session-framework/implementation.md @@ -407,6 +407,40 @@ order. Where the legacy side runs in the test, the ledgers are compared after ev well: adapter export, ratchet state, and the executor's scene, bound channels, running macro, counts and "nearer". Results: see the TASK-01 run report and the amendment below. +**Amendment, 2026-09-29 (TASK-01 review fix round).** The review blocked on B1 and noted +N1 to N5. All are fixed here; the dated amendments to legacy-gameboy-v1 section 10 and 15 cover +B1, N1 and N3. + +- **B1: the task ledger is artifact-backed.** On the live fly the adapter ledger is 42-46 KB, + past the 32 KiB `TypedValue` bound. + - `Task` gains `capture_attachments`, `validate_restore_with` and `install_restore_with`. + - The coordinator files those attachments as `task-ledger-` payloads in captures and + imports. + - A bad ledger is an error, never a panic, so a boot falls to the next candidate. + - Boot parity now covers row 64 (42 KB) and the row 65 yard (46 KB). +- **N1: a sugar admitted before the next commit is an active pulse.** +- **N3: a restore seeds the palette as `Sim::boot` does.** `tests/palette_seed.rs` shows that the + seed is never read. +- **N4: saves are queued to the writer thread.** +- **N5: speed.** The profile is below. Changes: + - The world seals its three artifacts concurrently. + - Cache and caller holds are taken concurrently. + - In-process participants use the in-memory transport. + - A service session publishes every other boundary (the feed's 30 Hz) and keeps a bounded + history. + - `State.Capture` is off the loop. The worker shell lets a handler finish its reply outside + the endpoint's lock, and takes mutations in arrival order. The legacy agent copies its state + under the lock, then encodes, digests and seals it off the lock. The coordinator's + `begin_capture` / `finish_capture` let the session step on while the payload is written. +- **Measured** (`tests/speed.rs`, `tests/speed_ab.rs`): + - The brain is the same: the legacy `ticks` phase and the agent's `ticks` span agree within a + few percent. + - What remains is a fixed per-frame overhead of the process boundary. It is about 3-5 ms on a + quiet 8-core build box: roughly 0.7-1 ms per RPC round trip for Prepare, Advance and Commit, + plus the world's and the agent's artifact seals and reads. + - Against it, the legacy loop spends about 0.7 ms per frame outside the ticks. + - The report `claude-task-01` has the per-phase table and what would close the rest. + ### STATE-01 — Coherent all-participant checkpoint/recovery **Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01. diff --git a/docs/design/session-framework/legacy-gameboy-v1.md b/docs/design/session-framework/legacy-gameboy-v1.md index 8cc6e8a..281079c 100644 --- a/docs/design/session-framework/legacy-gameboy-v1.md +++ b/docs/design/session-framework/legacy-gameboy-v1.md @@ -293,12 +293,22 @@ signal. The object serves exactly one agent on one port. - *The ratchet's slot.* The ratchet ledger stays in the task. Its snapshot lives in the environment as the slot `best`. The ratchet only asks whether one exists: its budget test is "no snapshot". - So the task holds a marker snapshot in its place, and a task ledger records `slot: bool`. A slot + So the task holds a marker snapshot in its place, and a task ledger records `slotFilled`. A slot save is asked for exactly when the legacy capture closure runs: safe, and rank above best. -- *The palette seed.* The legacy loop seeds the palette from the brain's RNG state after boot. - `MacroMachine` never reads its generator: no macro has a random step, and flybrain-gb's macro - tests show two seeds press the same buttons. The executor therefore uses a constant, and nothing - about it crosses to the agent. +- *The task ledger is artifact-backed* (amended 2026-09-29, TASK-01 review B1). The adapter's + lifetime ledger grows with play: it is 42-46 KB on the live fly at rungs 12-15, which is past + the 32 KiB `TypedValue` bound. So the typed ledger is `{reward: {digest, byteLength}, ratchet, + slotFilled}`, and the adapter state's JSON travels as the ledger attachment `reward`. A + checkpoint files it as the payload `task-ledger-reward` ([workers-v1](workers-v1.md) section 1's + explicit artifact-backed schema; `Task::capture_attachments`). A missing, altered or unreadable + attachment is `INCOMPATIBLE_STATE`, never a panic, so a boot falls to the next candidate. +- *The palette seed* (amended 2026-09-29, TASK-01 review N3). The legacy loop seeds the palette + from the brain's RNG state after boot. A restore does the same: it seeds with the restored + agent state's RNG, which it holds. A fresh start cannot see the agent's RNG after the warm-up, + so it uses a constant. That is exact because `MacroMachine` never reads its generator: no macro + has a random step. `fly-legacy-session` `tests/palette_seed.rs` holds this on the cartridge: + two seeds, driven by the same decisions, press the same buttons for 3000 frames. A future + macro that draws from the generator fails there. - *The clock of the first observation.* A fresh start's layer observes O[0] at the end of the warm-up, `warmupMs` = 2500 ms, which the profile pins. That is the same time the legacy loop's `Sim::boot` observes at, although the agent is initialized after the task bootstraps. After a @@ -580,6 +590,15 @@ bridge's fulfil path and refund path both get tests in the slice that wires them fails first. The legacy rules run on the edge side, unchanged: flysim's `RateLimiter` and the clamp. They read `stimulusRemainingMs` from the last `Agent.Commit` or `Agent.Rollback` reply. After a restore the pulse is unknown and a request is refused with a retry of one frame. + *Amended 2026-09-29 (TASK-01 review N1):* a sugar admitted but not yet reported on by a commit + counts as an active pulse, at its full duration (`AdmissionQueue::pending_stimulus_ms`). The + legacy `stimulate` activates the pulse the moment it admits, so this matches: + - two sugars between two commits get one admission and one `PulseActive`, as the legacy drain + gives them; + - the rate-limit slot is not spent on the refused one. + + The retry advice may differ by less than a frame. Legacy reports the pulse decayed by the + ticks between drains; here it is undecayed until the commit reports it. - *The operator's `POST /reward` pulse is refused (declared).* In the legacy loop it is off unless an operator sets `control.allow_reward`. Every shipped configuration leaves it off, and the API answers 403. The session runtime has no counterpart to turn on, because a reinforcement outside diff --git a/services/flysim/crates/fly-legacy-session/src/admission.rs b/services/flysim/crates/fly-legacy-session/src/admission.rs index c3be6cc..c17ebeb 100644 --- a/services/flysim/crates/fly-legacy-session/src/admission.rs +++ b/services/flysim/crates/fly-legacy-session/src/admission.rs @@ -75,31 +75,34 @@ impl LegacyAdmission { /// `POST /stimulate`: the legacy rule over the last commit's pulse. On admission the sugar is /// queued for the next Prepare; the result is its interaction id and the clamped duration. pub fn sugar(&mut self, now_ms: u64, duration_ms: Option) -> Result<(Id, f64), Refusal> { - let Some(remaining) = self.queue.stimulus_remaining_ms(&self.agent_id) else { - return Err(Refusal::PulseActive { - retry_after_ms: UNKNOWN_PULSE_RETRY_MS, - }); - }; - // 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 - .unwrap_or(self.default_ms) - .clamp(1.0, self.max_ms) - .min(self.max_ms); + // Read the pulse, decide and queue under one lock, so a commit cannot land between the + // reads and the push (TASK-01 review R2-3). A sugar admitted and not yet reported on by + // a commit is an active pulse, as it is in the legacy loop the moment `stimulate` runs: + // a second request before the next commit is refused (`PulseActive`), not admitted + // into a pulse that would take the max and add nothing (review N1). + let agent_id = self.agent_id.clone(); let interaction_id = self.next_id("sugar"); - self.queue.admit(Admission::Stimulus { - agent_id: self.agent_id.clone(), - interaction_id: interaction_id.clone(), - kind_id: id(STIMULUS_REWARD_PULSE), - duration_ms: duration, + let (limiter, default_ms, max_ms) = (&mut self.limiter, self.default_ms, self.max_ms); + let admission = self.queue.admit_with(&agent_id, |remaining, pending| { + let Some(remaining) = remaining else { + return Err(Refusal::PulseActive { + retry_after_ms: UNKNOWN_PULSE_RETRY_MS, + }); + }; + limiter.admit(now_ms, remaining.max(pending.unwrap_or(0.0)))?; + let duration = duration_ms.unwrap_or(default_ms).clamp(1.0, max_ms).min(max_ms); + Ok(Admission::Stimulus { + agent_id: agent_id.clone(), + interaction_id: interaction_id.clone(), + kind_id: id(STIMULUS_REWARD_PULSE), + duration_ms: duration, + }) }); + if admission.is_err() { + // A refusal spends no id. + self.serial -= 1; + } + let Admission::Stimulus { duration_ms: duration, .. } = admission?; Ok((interaction_id, duration)) } diff --git a/services/flysim/crates/fly-legacy-session/src/composition.rs b/services/flysim/crates/fly-legacy-session/src/composition.rs index 51679b4..11d414b 100644 --- a/services/flysim/crates/fly-legacy-session/src/composition.rs +++ b/services/flysim/crates/fly-legacy-session/src/composition.rs @@ -27,7 +27,7 @@ use flysim::snapshot::MacroMode; use crate::task::{PokeredConfig, PokeredTask, TaskRecord}; use fly_session::legacy_checkpoint::{ AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind, - SaveReport, SaveTicket, now_wall_ms, + SaveReport, SaveTicket, TaskHalf, now_wall_ms, }; use flysim::store::Checkpoint; use std::time::Instant; @@ -41,6 +41,9 @@ fn grants(f: impl FnOnce(&mut Grants)) -> Grants { /// The transitions a service session keeps in memory for diagnosis (about a minute at 60 Hz). const HISTORY: usize = 4096; +/// Every other boundary's snapshot: the legacy feed's `snapshot_hz` (30 Hz) at 60 Hz. +const SNAPSHOT_EVERY: u64 = 2; + const COORDINATOR_CLIENT: &str = "coordinator"; const ENV_CLIENT: &str = "legacy-world"; const ENV_SERVICE: &str = "env.world"; @@ -93,6 +96,8 @@ pub struct LegacySession { saves: u64, /// Saves on the writer thread whose outcome has not been collected. pending_saves: Vec, + /// Captures sent and not yet collected ([`LegacySession::begin_save`]). + pending_captures: Vec<(fly_session::coordinator::PendingCapture, SaveKind, TaskHalf)>, /// The feed event log's watermark the saves record: the restored file's, carried over (the /// session runtime has no feed event log of its own before EDGE-01). last_event_id: u64, @@ -318,7 +323,9 @@ impl LegacySession { let mut launcher = Launcher::start( router, config.mode, - Via::Unix, + // In-process participants reach the router in memory: no socket between two tasks + // of one process (a separate process always uses the socket). + Via::Memory, &store_root, &sockets, budget, @@ -426,6 +433,8 @@ impl LegacySession { } else { // A service session runs indefinitely: its in-memory history stays bounded. coordinator.bound_history(HISTORY); + // The legacy feed publishes at `snapshot_hz` (30 Hz) from a 60 Hz loop. + coordinator.snapshot_every(SNAPSHOT_EVERY); } Ok(LegacySession { coordinator, @@ -439,6 +448,7 @@ impl LegacySession { checkpointer: None, saves: 0, pending_saves: Vec::new(), + pending_captures: Vec::new(), last_event_id: 0, }) } @@ -593,49 +603,94 @@ impl LegacySession { /// goes on, as the legacy loop hands its saves to its writer thread (TASK-01 review N4). The /// outcome is collected by [`LegacySession::completed_saves`]. pub async fn queue_save(&mut self, kind: SaveKind) -> Result { + self.begin_save(kind).await?; + let mut tickets = self.finish_captures().await?; + let last = tickets + .pop() + .ok_or_else(|| "no save was begun".to_owned())?; + self.pending_saves.extend(tickets); + Ok(last) + } + + /// Begins one save of the committed boundary: every participant's `State.Capture` is sent + /// (each takes its state now) and the task's half is taken now; the session may step on + /// while the agent encodes and seals its payload off its lock + /// (`Coordinator::begin_capture`, TASK-01 review N5). [`LegacySession::finish_captures`] + /// hands it to the writer. + pub async fn begin_save(&mut self, kind: SaveKind) -> Result<(), String> { self.saves += 1; - let (boundary, world, agents) = self + let capture = self .coordinator - .capture_payloads(&parse_id(&format!("legacy-save-{}", self.saves))?) + .begin_capture(&parse_id(&format!("legacy-save-{}", self.saves))?) .await .map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?; - let [(_, agent)] = <[(Id, Vec); 1]>::try_from(agents) - .map_err(|_| "the legacy composition has exactly one agent".to_owned())?; let (task, _slot_filled) = self.task.task_half(); - let capture = LegacyCapture { - boundary, - agent_payload: agent, - world_payload: world, - task, - }; - let last_event_id = self.last_event_id; - let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?; - checkpointer.save(kind, capture, last_event_id, now_wall_ms()) + self.pending_captures.push((capture, kind, task)); + Ok(()) + } + + /// Collects every begun capture, in order, and queues it to the checkpointer's writer. + pub async fn finish_captures(&mut self) -> Result, String> { + let mut tickets = Vec::new(); + for (capture, kind, task) in std::mem::take(&mut self.pending_captures) { + let (boundary, world, agents) = self + .coordinator + .finish_capture(capture) + .await + .map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?; + let [(_, agent)] = <[(Id, Vec); 1]>::try_from(agents) + .map_err(|_| "the legacy composition has exactly one agent".to_owned())?; + let capture = LegacyCapture { + boundary, + agent_payload: agent, + world_payload: world, + task, + }; + let last_event_id = self.last_event_id; + let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?; + tickets.push(checkpointer.save(kind, capture, last_event_id, now_wall_ms())?); + } + Ok(tickets) } /// The saves queued so far that have committed (or failed), without waiting; with `wait`, - /// every queued save's outcome. A failed save is an error: the caller decides. - pub async fn completed_saves(&mut self, wait: bool) -> Result, String> { + /// every queued save's outcome. Every outcome is reported, a failed save as its own `Err` + /// beside the others (TASK-01 review R2-2): the caller decides. + pub async fn completed_saves(&mut self, wait: bool) -> Vec> { let mut done = Vec::new(); let mut still = Vec::new(); for mut ticket in std::mem::take(&mut self.pending_saves) { - let outcome = if wait { - Some((&mut ticket.reply).await.map_err(|_| ())) + let stopped = || Err("the checkpoint writer stopped".to_owned()); + if wait { + done.push((&mut ticket.reply).await.unwrap_or_else(|_| stopped())); } else { match ticket.reply.try_recv() { - Ok(result) => Some(Ok(result)), - Err(tokio::sync::oneshot::error::TryRecvError::Empty) => None, - Err(tokio::sync::oneshot::error::TryRecvError::Closed) => Some(Err(())), + Ok(result) => done.push(result), + Err(tokio::sync::oneshot::error::TryRecvError::Empty) => still.push(ticket), + Err(tokio::sync::oneshot::error::TryRecvError::Closed) => done.push(stopped()), } - }; - 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) + done + } + + /// Hands every begun capture to the writer now and reports what was queued. `advance` does + /// this after the next step so the agent's sealing overlaps it; a step that fails does it + /// before returning the error, and a caller that pauses (or is about to stop stepping) calls + /// this so a save begun at the last boundary reaches the writer as the legacy loop's + /// immediate hand-off would have (TASK-01 review R2-1). + pub async fn flush_captures(&mut self) -> Result, String> { + let mut saves = Vec::new(); + for ticket in self.finish_captures().await? { + saves.push(SaveQueued { + generation: ticket.generation, + durable: ticket.durable, + archive_rank: ticket.archive_rank, + }); + self.pending_saves.push(ticket); + } + Ok(saves) } /// One transition and what the legacy loop does at the boundary it reaches, in the declared @@ -643,12 +698,23 @@ impl LegacySession { /// milestone archive when the rank climbed (`Sim::track_rank`), the rollback, a durable save /// after it, then the interval saves (`checkpoint_if_due`). pub async fn advance(&mut self) -> Result<(Step, Vec), String> { - let report = self - .coordinator - .step() - .await - .map_err(|e| format!("step ({} at {}): {}", e.detail, e.phase, e.error.message))?; - let mut saves = Vec::new(); + let report = match self.coordinator.step().await { + Ok(report) => report, + Err(e) => { + // The legacy writer already has the saves of the earlier boundaries: hand the + // begun captures over before reporting the failure (TASK-01 review R2-1). + let flushed = self.flush_captures().await.err(); + let mut message = + format!("step ({} at {}): {}", e.detail, e.phase, e.error.message); + if let Some(flush) = flushed { + message.push_str(&format!("; and the pending saves: {flush}")); + } + return Err(message); + } + }; + // The captures begun at the last boundary: the agent sealed its payload while this + // transition's Prepare ticked. + let saves = self.flush_captures().await?; if self.checkpointer.is_some() { let rank = self.task.rank(); let ms = self.task.brain_ms(); @@ -658,13 +724,7 @@ impl LegacySession { .expect("attached") .observe_rank(rank, ms); if let Some(RankChange::Climbed(rank)) = change { - 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); + self.begin_save(SaveKind::Milestone(rank)).await?; } } let rolled_back = self @@ -679,13 +739,7 @@ impl LegacySession { })?; if self.checkpointer.is_some() { if rolled_back { - 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); + self.begin_save(SaveKind::Durable).await?; } let due = self .checkpointer @@ -693,13 +747,7 @@ impl LegacySession { .expect("attached") .due(Instant::now()); if let Some(kind) = due { - 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); + self.begin_save(kind).await?; } } Ok(( @@ -723,11 +771,16 @@ impl LegacySession { if self.checkpointer.is_none() { return Ok(None); } + self.flush_captures().await?; let report = self.save(SaveKind::Durable).await?; - self.completed_saves(true).await?; + let outcomes = self.completed_saves(true).await; if let Some(checkpointer) = self.checkpointer.as_mut() { checkpointer.close(); } + // Every queued save has been waited for; the first failure is the shutdown's. + for outcome in outcomes { + outcome?; + } Ok(Some(report)) } diff --git a/services/flysim/crates/fly-legacy-session/src/service.rs b/services/flysim/crates/fly-legacy-session/src/service.rs index 6e95e57..6dc871f 100644 --- a/services/flysim/crates/fly-legacy-session/src/service.rs +++ b/services/flysim/crates/fly-legacy-session/src/service.rs @@ -937,6 +937,13 @@ impl SessionHost { if self.status != FeedStatus::Paused { self.status = FeedStatus::Paused; self.emit(NewEvent::new(FeedEventKind::System, "Paused by the operator")); + // A pause must never hold a begun save (TASK-01 review R2-1). This host + // saves through `queue_save`, which hands its capture over at once, so + // there is normally nothing to flush; a begun capture would reach the + // writer here rather than sit until the next step. + if let Err(error) = self.session.flush_captures().await { + tracing::error!(%error, "could not hand over the pending captures on pause"); + } if let Err(error) = self.checkpoint(SaveKind::Durable, None).await { tracing::error!(%error, "could not checkpoint on pause"); } diff --git a/services/flysim/crates/fly-legacy-session/tests/save_handoff.rs b/services/flysim/crates/fly-legacy-session/tests/save_handoff.rs new file mode 100644 index 0000000..859c39d --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/save_handoff.rs @@ -0,0 +1,126 @@ +//! TASK-01 round-2 review notes R2-1 and R2-2 on the session's save hand-off. The toy raw +//! composition from power-on (`FLY_ROM`; a build without it skips): +//! +//! - R2-1: a save begun at boundary k reaches the writer even when the step after it fails, and +//! `flush_captures` hands it over while the loop idles (a pause), as the legacy loop's writer +//! thread has it from the boundary on. +//! - R2-2: `completed_saves` reports every queued save's outcome, a failed one beside the rest. + +use std::path::PathBuf; + +use fly_legacy_session::composition::{ + LegacyConfig, LegacySession, StoreConfig, +}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_checkpoint::SaveKind; +use fly_session::legacy_parity; +use fly_session::types::id; +use flysim::snapshot::MacroMode; + +async fn session(root: &std::path::Path) -> Option<(LegacySession, StoreConfig)> { + let Some(rom_path) = std::env::var_os("FLY_ROM").map(PathBuf::from) else { + eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)"); + return None; + }; + let config = LegacyConfig { + mode: ExecutionMode::InProcess, + rom_path, + dataset_dir: legacy_parity::toy::dir(), + profile: LegacyProfileKind::Toy, + macro_mode: MacroMode::Raw, + agent_id: id("fly"), + agent_threads: 1, + record: true, + }; + let mut session = LegacySession::start(&root.join("run"), config) + .await + .expect("the session starts"); + session.bootstrap().await.expect("Ready(0)"); + let store = StoreConfig { + hot_dir: root.join("hot"), + durable_dir: root.join("durable"), + keep_generations: 4, + // Saves only when asked. + hot_seconds: 1e9, + checkpoint_seconds: 1e9, + speed: 1.0, + }; + session.attach_store(&store).expect("the store attaches"); + Some((session, store)) +} + +/// One step, then the interval save it began (the first boundary is due for a durable one) +/// written and collected, so a test starts with nothing queued. +async fn warm_up(session: &mut LegacySession) { + session.advance().await.expect("a step"); + session.flush_captures().await.expect("the flush"); + for outcome in session.completed_saves(true).await { + outcome.expect("the first save"); + } +} + +fn files_in(dir: &std::path::Path) -> usize { + std::fs::read_dir(dir) + .map(|entries| entries.filter_map(Result::ok).count()) + .unwrap_or(0) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_begun_save_reaches_the_writer_when_the_next_step_fails() { + let root = tempfile::tempdir().expect("tmp"); + let Some((mut session, _)) = session(root.path()).await else { return }; + warm_up(&mut session).await; + for _ in 0..2 { + session.advance().await.expect("a step"); + } + session.begin_save(SaveKind::Hot).await.expect("a capture begins"); + // The next transition fails at its commit. + session.coordinator.injections.at_step = 3; + session.coordinator.injections.undeclared_stimulus = true; + let error = session.advance().await.err().expect("the step fails"); + assert!(error.starts_with("step ("), "{error}"); + let outcomes = session.completed_saves(true).await; + assert_eq!(outcomes.len(), 1, "the save begun before the failed step was written"); + let report = outcomes.into_iter().next().unwrap().expect("and it committed"); + assert!(!report.durable); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_pause_flushes_the_begun_save() { + let root = tempfile::tempdir().expect("tmp"); + let Some((mut session, store)) = session(root.path()).await else { return }; + warm_up(&mut session).await; + session.begin_save(SaveKind::Hot).await.expect("a capture begins"); + let before = files_in(&store.hot_dir); + let queued = session.flush_captures().await.expect("the flush"); + assert_eq!(queued.len(), 1); + let outcomes = session.completed_saves(true).await; + assert_eq!(outcomes.len(), 1); + assert!(outcomes[0].is_ok()); + assert!(files_in(&store.hot_dir) > before, "the hot generation is on disk"); + assert!( + session.flush_captures().await.expect("a second flush").is_empty(), + "nothing is held twice" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn every_save_outcome_is_reported_after_a_failure() { + let root = tempfile::tempdir().expect("tmp"); + let Some((mut session, store)) = session(root.path()).await else { return }; + warm_up(&mut session).await; + // The store's hot directory goes away under the writer: every save after it fails. The + // first failure must not hide the outcomes behind it. + std::fs::remove_dir_all(&store.hot_dir).expect("remove hot"); + std::fs::write(&store.hot_dir, b"not a directory").expect("block hot"); + let mut expected = 0; + for _ in 0..3 { + session.begin_save(SaveKind::Hot).await.expect("begin"); + session.flush_captures().await.expect("flush"); + expected += 1; + } + let outcomes = session.completed_saves(true).await; + assert_eq!(outcomes.len(), expected, "one outcome per queued save: {outcomes:?}"); + assert!(outcomes.iter().all(Result::is_err), "the writes failed: {outcomes:?}"); +} diff --git a/services/flysim/crates/fly-legacy-session/tests/session_trace.rs b/services/flysim/crates/fly-legacy-session/tests/session_trace.rs index 2446d9d..7eb09bf 100644 --- a/services/flysim/crates/fly-legacy-session/tests/session_trace.rs +++ b/services/flysim/crates/fly-legacy-session/tests/session_trace.rs @@ -753,6 +753,9 @@ async fn fafb_reward_segments() { "FLY_DOOR_CHECKPOINT", "FLY_CATCH_CHECKPOINT", "FLY_ENGAGE_CHECKPOINT", + // The live fly's largest task ledgers (42 and 46 KB, TASK-01 review B1). + "FLY_ROW64_CHECKPOINT", + "FLY_ROW65_YARD_CHECKPOINT", ] .iter() .filter_map(|var| std::env::var_os(var).map(|p| ((*var).to_owned(), PathBuf::from(p)))) diff --git a/services/flysim/crates/fly-legacy-session/tests/speed.rs b/services/flysim/crates/fly-legacy-session/tests/speed.rs index 65dac55..a90340b 100644 --- a/services/flysim/crates/fly-legacy-session/tests/speed.rs +++ b/services/flysim/crates/fly-legacy-session/tests/speed.rs @@ -30,6 +30,30 @@ use flysim::frame::{LegacyFrame, Parts}; use flysim::macros::macro_layer; use flysim::snapshot::MacroMode; +/// The legacy frame's phases, timed through the one hook the stream itself uses. +struct Phases { + last: Instant, + sums: std::collections::BTreeMap<&'static str, f64>, + on: bool, +} + +impl flysim::frame::FrameObserver for Phases { + fn after(&mut self, phase: flysim::frame::FramePhase, _agent: &mut NeuralAgent) { + let now = Instant::now(); + if self.on { + let name = match phase { + flysim::frame::FramePhase::Ticked => "legacy.ticks", + flysim::frame::FramePhase::Executed => "legacy.decode+execute", + flysim::frame::FramePhase::Emulated => "legacy.frame", + flysim::frame::FramePhase::Advanced => "legacy.take_frame", + flysim::frame::FramePhase::Committed => "legacy.evaluate+commit", + }; + *self.sums.entry(name).or_default() += (now - self.last).as_secs_f64() * 1000.0; + } + self.last = now; + } +} + const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0; fn env_usize(name: &str, default: usize) -> usize { @@ -94,8 +118,16 @@ async fn session_against_legacy_per_frame() { let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms); } let mut legacy_ms = 0.0; + let mut phases = Phases { + last: Instant::now(), + sums: Default::default(), + on: false, + }; + let mut boundary_ms = 0.0; for n in 0..warmup + frames { let started = Instant::now(); + phases.on = n >= warmup; + phases.last = started; let mut parts = Parts { agent: &mut agent, emulator: &mut emulator, @@ -103,16 +135,40 @@ async fn session_against_legacy_per_frame() { ratchet: &mut ratchet, macros: macros.as_mut(), }; - let transition = frame.transition(&mut parts, &mut ()).unwrap(); + let transition = frame.transition(&mut parts, &mut phases).unwrap(); + let at = Instant::now(); frame .boundary(&mut parts, &transition.evaluated.progress, transition.ms) .unwrap(); + if n >= warmup { + boundary_ms += at.elapsed().as_secs_f64() * 1000.0; + } if n >= warmup { legacy_ms += started.elapsed().as_secs_f64() * 1000.0; } } + // What a legacy checkpoint costs the loop: the agent's export (the writer thread encodes). + let at = Instant::now(); + for _ in 0..10 { + std::hint::black_box(agent.export_state()); + } + let export_ms = at.elapsed().as_secs_f64() * 100.0; drop(agent); let legacy_per = legacy_ms / frames as f64; + for (name, sum) in &phases.sums { + eprintln!( + " legacy {name:<24} mean {:>8.0} us", + sum * 1000.0 / frames as f64 + ); + } + eprintln!( + " legacy boundary mean {:>8.0} us", + boundary_ms * 1000.0 / frames as f64 + ); + eprintln!( + " legacy agent.export_state mean {:>8.0} us (per checkpoint)", + export_ms * 1000.0 + ); eprintln!( "legacy loop: {legacy_per:.2} ms/frame over {frames} frames ({threads} threads), realtime factor at 1x {:.2}", (FRAME_MS / legacy_per).min(1.0) @@ -152,6 +208,32 @@ async fn session_against_legacy_per_frame() { session.step().await.unwrap(); } let per = started.elapsed().as_secs_f64() * 1000.0 / frames as f64; + if !paced { + // What a save costs the loop: the participants' State.Capture at the boundary. + let root = tempfile::tempdir().unwrap(); + session + .attach_store(&fly_legacy_session::composition::StoreConfig { + hot_dir: root.path().join("hot"), + durable_dir: root.path().join("durable"), + keep_generations: 2, + hot_seconds: 1e9, + checkpoint_seconds: 1e9, + speed: 1.0, + }) + .unwrap(); + let at = Instant::now(); + for _ in 0..5 { + let ticket = session + .queue_save(fly_session::legacy_checkpoint::SaveKind::Hot) + .await + .unwrap(); + drop(ticket); + } + eprintln!( + " session save (capture on the loop) mean {:>8.0} us", + at.elapsed().as_secs_f64() * 1e6 / 5.0 + ); + } let factor = FRAME_MS / per; eprintln!( "session {} {}: {per:.2} ms/frame, realtime factor {:.2} ({:.2}x the legacy loop's cost)", diff --git a/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs b/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs new file mode 100644 index 0000000..55b37a8 --- /dev/null +++ b/services/flysim/crates/fly-legacy-session/tests/speed_ab.rs @@ -0,0 +1,207 @@ +//! TASK-01 review N5: the session runtime's cost per frame against the legacy loop's, measured +//! A/B-interleaved on one box so both see the same load: chunks of `FLY_TASK01_AB_CHUNK` frames +//! of the legacy loop (`LegacyFrame`, the service's frame, trace off) alternate with chunks of the +//! session (agent, world and task under the coordinator, service configuration: no details, +//! bounded history, snapshots at 30 Hz), both from the same checkpoint with the same sweep threads. +//! A shared box's load then shifts both arms alike, and the ratio is the comparison. +//! +//! `FLY_TASK01_BENCH=1` plus rom-env and `data/fafb-v783`. Reported per execution mode: mean +//! ms/frame of each arm, the ratio, the fps each sustains unpaced, and the headroom at 1x (one +//! Game Boy frame is 16.74 ms). + +use std::sync::Arc; +use std::time::Instant; + +use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold}; +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity; +use fly_session::types::id; +use flybrain_core::agent::{AgentConfig, NeuralAgent}; +use flybrain_core::dataset::load_brain_dataset_from_dir; +use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros; +use flybrain_core::lif::SweepPlan; +use flybrain_gb::GameAdapter; +use flybrain_gb::pokemon_red::PokemonRedReward; +use flybrain_gb::ratchet::Ratchet; +use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator}; +use flysim::config::Config; +use flysim::frame::{LegacyFrame, Parts}; +use flysim::macros::{MacroLayer, macro_layer}; +use flysim::snapshot::MacroMode; + +const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0; + +fn env_usize(name: &str, default: usize) -> usize { + std::env::var(name) + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +struct Legacy { + emulator: Emulator, + adapter: PokemonRedReward, + ratchet: Ratchet, + agent: NeuralAgent, + frame: LegacyFrame, + macros: Option, +} + +impl Legacy { + fn new( + rom: &[u8], + dataset: &std::path::Path, + checkpoint: &flysim::store::Checkpoint, + threads: usize, + ) -> Legacy { + let data = Arc::new(load_brain_dataset_from_dir(dataset).unwrap()); + let mut emulator = + Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).unwrap(); + let mut adapter = PokemonRedReward::new(); + let mut ratchet = Ratchet::with_policy(adapter.recovery_policy()); + let mut config = Config::default(); + config.loop_.game = "pokemon-red".to_owned(); + config.macros.mode = MacroMode::Macros; + let (channels, hold_ms) = channels_and_hold(MacroMode::Macros); + let channels: Vec<&str> = channels.iter().map(String::as_str).collect(); + let mut agent_config = + AgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels)); + agent_config.warmup_ms = config.loop_.warmup_ms; + let mut agent = NeuralAgent::new(data, agent_config).unwrap(); + if threads > 1 { + agent.set_sweep_plan(SweepPlan::with_threads(threads).unwrap()); + } + let mut frame = LegacyFrame::new(); + frame + .restore( + &mut Parts { + agent: &mut agent, + emulator: &mut emulator, + adapter: &mut adapter, + ratchet: &mut ratchet, + macros: None, + }, + checkpoint, + ) + .unwrap(); + let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32); + if let Some(layer) = macros.as_mut() { + let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms); + } + Legacy { + emulator, + adapter, + ratchet, + agent, + frame, + macros, + } + } + + fn step(&mut self) { + let mut parts = Parts { + agent: &mut self.agent, + emulator: &mut self.emulator, + adapter: &mut self.adapter, + ratchet: &mut self.ratchet, + macros: self.macros.as_mut(), + }; + let transition = self.frame.transition(&mut parts, &mut ()).unwrap(); + self.frame + .boundary(&mut parts, &transition.evaluated.progress, transition.ms) + .unwrap(); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn session_against_legacy_interleaved() { + if std::env::var_os("FLY_TASK01_BENCH").is_none() { + eprintln!("skipping: FLY_TASK01_BENCH is not set"); + return; + } + let (Some(rom_path), Some(dataset), Some(checkpoint_path)) = ( + std::env::var_os("FLY_ROM").map(std::path::PathBuf::from), + legacy_parity::fafb_dir(), + std::env::var_os("FLY_DOOR_CHECKPOINT").map(std::path::PathBuf::from), + ) else { + eprintln!("skipping: FLY_ROM, data/fafb-v783 or FLY_DOOR_CHECKPOINT missing"); + return; + }; + let frames = env_usize("FLY_TASK01_BENCH_FRAMES", 1800); + let chunk = env_usize("FLY_TASK01_AB_CHUNK", 60); + let threads = env_usize("FLY_TASK01_BENCH_THREADS", 3); + let rom = std::fs::read(&rom_path).unwrap(); + let bytes = std::fs::read(&checkpoint_path).unwrap(); + let checkpoint = flysim::store::decode(&bytes).unwrap(); + for mode in [ExecutionMode::InProcess, ExecutionMode::Process] { + let mut legacy = Legacy::new(&rom, &dataset, &checkpoint, threads); + let root = tempfile::tempdir().unwrap(); + let mut session = LegacySession::start( + root.path(), + LegacyConfig { + mode, + rom_path: rom_path.clone(), + dataset_dir: dataset.clone(), + profile: LegacyProfileKind::Production, + macro_mode: MacroMode::Macros, + agent_id: id("fly"), + agent_threads: threads.max(1), + record: false, + }, + ) + .await + .unwrap(); + session.bootstrap().await.unwrap(); + session.import_flysim01(&bytes, &id("e2")).await.unwrap(); + session.coordinator.disable_pacing(); + // Warm both. + for _ in 0..chunk { + legacy.step(); + session.step().await.unwrap(); + } + session.coordinator.metrics.clear(); + let _ = fly_session::profile::report(); + let (mut legacy_ms, mut session_ms) = (0.0, 0.0); + let mut done = 0; + while done < frames { + let at = Instant::now(); + for _ in 0..chunk { + legacy.step(); + } + legacy_ms += at.elapsed().as_secs_f64() * 1000.0; + let at = Instant::now(); + for _ in 0..chunk { + session.step().await.unwrap(); + } + session_ms += at.elapsed().as_secs_f64() * 1000.0; + done += chunk; + } + let (l, s) = (legacy_ms / done as f64, session_ms / done as f64); + eprintln!( + "{}: legacy {l:.2} ms/frame ({:.0} fps), session {s:.2} ms/frame ({:.0} fps); session/legacy {:.2}; headroom at 1x legacy {:.2} ms, session {:.2} ms ({done} frames each, {chunk}-frame chunks, {threads} threads)", + mode.label(), + 1000.0 / l, + 1000.0 / s, + s / l, + FRAME_MS - l, + FRAME_MS - s + ); + for (name, count, mean) in fly_session::profile::report() { + eprintln!( + " span {name:<26} mean {:>8.0} us n {count}", + mean.as_secs_f64() * 1e6 + ); + } + for name in session.coordinator.metrics.names() { + let p = session.coordinator.metrics.percentiles(&name).unwrap(); + eprintln!( + " {name:<24} p50 {:>8.0} us p95 {:>8.0} us n {}", + p.p50_us(), + p.p95_us(), + session.coordinator.metrics.count(&name) + ); + } + session.stop().await; + } +} diff --git a/services/flysim/crates/fly-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index 3cea2a0..f71b5d9 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -384,6 +384,8 @@ pub struct Coordinator { pending_rollback: Option<(u64, EpisodeRequest)>, /// [`Coordinator::bound_history`]. history_limit: Option, + /// [`Coordinator::snapshot_every`]. + snapshot_every: u64, lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>, stats: Stats, /// The ordered actions this session took, for the ordering assertions. @@ -505,6 +507,7 @@ impl Coordinator { defer_rollbacks: false, pending_rollback: None, history_limit: None, + snapshot_every: 1, lifecycle_acks: Vec::new(), stats: Stats::default(), audit: Vec::new(), @@ -714,6 +717,15 @@ impl Coordinator { self.history_limit = Some(keep); } + /// Publishes the committed snapshot of every `n`-th boundary, and of every boundary with task + /// events or boundary actions. Presentation reads snapshots as latest values + /// (`publishing-v1`), and the legacy feed publishes at `snapshot_hz` (30 Hz) from its 60 Hz + /// loop, so a live composition need not pay a publication on every frame. 1 (every boundary) + /// by default. + pub fn snapshot_every(&mut self, n: u64) { + self.snapshot_every = n.max(1); + } + fn trim_history(&mut self) { let Some(keep) = self.history_limit else { return }; fn trim(items: &mut Vec, keep: usize) { @@ -771,6 +783,19 @@ impl Coordinator { &mut self, checkpoint_id: &Id, ) -> Outcome<(u64, Vec, Vec<(Id, Vec)>)> { + let pending = self.begin_capture(checkpoint_id).await?; + self.finish_capture(pending).await + } + + /// Sends every participant's `State.Capture` for the committed boundary and returns without + /// waiting for the replies: the capture off the loop (TASK-01 review N5). + /// + /// Each participant takes its state at the boundary when it handles the request, which it + /// does before any request sent after it (a worker takes its lock in arrival order), and a + /// participant that encodes off its lock (the legacy agent) answers the next Prepare while it + /// seals the payload. The session may step on; [`Coordinator::finish_capture`] collects the + /// payloads, in the order sent, whenever the host is ready for them. + pub async fn begin_capture(&mut self, checkpoint_id: &Id) -> Outcome { let origin = self.phases.phase(); let Some(boundary) = origin.committed_boundary().filter(|_| origin.is_committed_boundary()) else { @@ -789,24 +814,67 @@ impl Coordinator { participants.extend(self.agents.iter().map(|slot| slot.worker.clone())); let params = object(CaptureParams { checkpoint_id: checkpoint_id.clone() }.to_json()); let want = vec![crate::state::PAYLOAD_ATTACHMENT.to_owned()]; - let mut payloads = Vec::new(); + let scope = self.scope(boundary); + let mut calls = Vec::new(); for worker in participants { - let reply = self - .call(&worker, "State.Capture", Some(self.scope(boundary)), params.clone(), &[], &want) - .await?; + let request_id = self.serials.next(&worker.service); + let sent = crate::rpc::send( + &self.bus, + &worker, + "State.Capture", + Some(scope.clone()), + params.clone(), + &[], + request_id, + &want, + ) + .await; + match sent { + Ok(sent) => calls.push((worker, sent)), + Err(e) => { + self.blame(Some(worker.worker_id.clone())); + return Err(self.fail_now(e, "capture")); + } + } + } + self.transition(origin)?; + Ok(PendingCapture { checkpoint_id: checkpoint_id.clone(), boundary, scope, calls }) + } + + /// Collects a capture begun with [`Coordinator::begin_capture`]: the world's payload and + /// every agent's, read and released. + pub async fn finish_capture( + &mut self, + pending: PendingCapture, + ) -> Outcome<(u64, Vec, Vec<(Id, Vec)>)> { + let PendingCapture { checkpoint_id, boundary, scope, calls } = pending; + let mut payloads = Vec::new(); + for (worker, sent) in calls { + let reply = match sent.finish().await { + Ok(reply) => reply, + Err(e) => { + self.blame(Some(worker.worker_id.clone())); + return Err(self.fail_now(e, "capture")); + } + }; + self.check_reply(&worker, &reply, &Some(scope.clone()), "State.Capture")?; + if let Err(e) = reply.result() { + return Err(self.fail_now(e, "capture")); + } let Some(artifact) = reply.artifacts.get(crate::state::PAYLOAD_ATTACHMENT).cloned() else { return Err(self.fail_now( DomainError::before(ErrorCode::BufferInvalid, "State.Capture carried no payload"), "capture", )); }; + let span = crate::profile::span("coord.capture.read"); let bytes = artifact.read_all().await.map_err(|e| { self.fail_now(DomainError::before(ErrorCode::BufferInvalid, e.message.clone()), "capture") })?; + drop(span); self.acknowledge_replies(&worker, std::slice::from_ref(&reply.request_id)).await?; payloads.push((worker.worker_id.clone(), bytes)); } - self.transition(origin)?; let world = payloads.remove(0).1; self.audit.push(format!("captured-payloads:{checkpoint_id}@{boundary}")); Ok((boundary, world, payloads)) @@ -1575,6 +1643,19 @@ struct AdmissionState { ended: Vec<(Admission, AdmissionEnd)>, } +impl AdmissionState { + fn set_remaining(&mut self, agent_id: &Id, remaining: Option) { + match remaining { + Some(ms) => { + self.remaining.insert(agent_id.clone(), ms); + } + None => { + self.remaining.remove(agent_id); + } + } + } +} + /// The edge's handle on admission: queue what the composition's rules admitted, read the last /// commit's stimulus pulse, collect the outcomes. Clone it freely; every clone is the same queue. #[derive(Clone, Debug, Default)] @@ -1632,6 +1713,11 @@ impl AdmissionQueue { } fn end(&self, admissions: Vec, end: AdmissionEnd) { + self.commit(admissions, end, &[]); + } + + /// Ends the admissions and records the commit's pulses under one lock. + fn commit(&self, admissions: Vec, end: AdmissionEnd, pulses: &[(Id, Option)]) { let mut state = self.lock(); for admission in admissions { state @@ -1639,18 +1725,38 @@ impl AdmissionQueue { .retain(|a| a.interaction_id() != admission.interaction_id()); state.ended.push((admission, end.clone())); } + for (agent_id, remaining) in pulses { + state.set_remaining(agent_id, *remaining); + } + } + + /// Decides and queues one admission under the lock every commit takes: `decide` gets the + /// agent's last reported pulse and the longest pending one, and returns the admission to + /// queue (or a refusal). No commit can interleave between the reads and the push, which is + /// the single-threaded legacy loop's answer (TASK-01 review R2-3). + pub fn admit_with( + &self, + agent_id: &Id, + decide: impl FnOnce(Option, Option) -> Result, + ) -> Result { + let mut state = self.lock(); + let remaining = state.remaining.get(agent_id).copied(); + let pending = state + .queued + .iter() + .chain(state.in_flight.iter()) + .filter(|a| a.agent_id() == agent_id) + .map(|a| match a { + Admission::Stimulus { duration_ms, .. } => *duration_ms, + }) + .reduce(f64::max); + let admission = decide(remaining, pending)?; + state.queued.push(admission.clone()); + Ok(admission) } fn set_remaining(&self, agent_id: &Id, remaining: Option) { - let mut state = self.lock(); - match remaining { - Some(ms) => { - state.remaining.insert(agent_id.clone(), ms); - } - None => { - state.remaining.remove(agent_id); - } - } + self.lock().set_remaining(agent_id, remaining); } fn forget_remaining(&self) { @@ -1691,6 +1797,21 @@ pub struct RollbackDetails { pub agents: Vec<(Id, fly_session_types::extensions::AgentRollbackResult)>, } +/// A capture sent to every participant and not yet collected ([`Coordinator::begin_capture`]). +pub struct PendingCapture { + checkpoint_id: Id, + boundary: u64, + scope: Scope, + calls: Vec<(WorkerRef, crate::rpc::SentCall)>, +} + +impl PendingCapture { + /// The committed boundary the capture is of. + pub fn boundary(&self) -> u64 { + self.boundary + } +} + /// A checkpoint of another format, assembled by an importer in each participant's own capture /// format, to install as a session's start ([`Coordinator::import`]). #[derive(Clone, Debug)] @@ -2445,10 +2566,14 @@ impl Coordinator { self.stats.advances += 1; // The admissions this transition carried are applied: its Prepare committed. let applied = std::mem::take(&mut self.in_flight_admissions); - self.admissions.end(applied.clone(), AdmissionEnd::Applied { boundary: k + 1 }); - for (agent_id, result) in &commits { - self.admissions.set_remaining(agent_id, result.telemetry.stimulus_remaining_ms); - } + // One lock for the end of the in-flight admissions and the new pulse: an edge thread + // never sees the admission gone and the old pulse still standing (TASK-01 review R2-3). + let pulses: Vec<(Id, Option)> = commits + .iter() + .map(|(agent_id, result)| (agent_id.clone(), result.telemetry.stimulus_remaining_ms)) + .collect(); + self.admissions + .commit(applied.clone(), AdmissionEnd::Applied { boundary: k + 1 }, &pulses); let view_digests = if self.record_details && self.digest_views { self.view_digests(&step_result.observation).await? @@ -2521,7 +2646,16 @@ impl Coordinator { } let publishing = Instant::now(); self.publish_events(k + 1, &evaluation.events).await?; - self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?; + // Every boundary with events or boundary actions is published; otherwise every + // `snapshot_every`-th (1 unless the composition thins it, as the legacy feed publishes at + // `snapshot_hz`, 30 Hz, from a 60 Hz loop). + if self.snapshot_every <= 1 + || (k + 1).is_multiple_of(self.snapshot_every) + || !evaluation.events.is_empty() + || !boundary_actions.is_empty() + { + self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?; + } self.metrics.record("publish", publishing.elapsed()); // A rollback request was applied above and is not an episode end; only a terminal one @@ -5921,3 +6055,71 @@ impl Coordinator { }) } } + +#[cfg(test)] +mod admission_race_tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + + /// TASK-01 review R2-3: a sugar arriving while a commit ends the in-flight admission and + /// reports the pulse must never see "no pending admission" beside the old, over pulse. The + /// only state the hammer accepts in is exactly that torn one; the commit under test is + /// atomic, so it is never seen. + #[test] + fn no_sugar_is_admitted_between_a_commit_ending_and_its_pulse() { + let queue = AdmissionQueue::default(); + let agent = id("fly"); + let in_flight = Admission::Stimulus { + agent_id: agent.clone(), + interaction_id: id("sugar-1"), + kind_id: id("reward-pulse"), + duration_ms: 400.0, + }; + let stop = AtomicBool::new(false); + let torn = AtomicBool::new(false); + std::thread::scope(|scope| { + scope.spawn(|| { + while !stop.load(Ordering::Relaxed) { + let admitted = queue.admit_with(&agent, |remaining, pending| { + if remaining.unwrap_or(0.0).max(pending.unwrap_or(0.0)) > 0.0 { + Err(()) + } else { + Ok(Admission::Stimulus { + agent_id: agent.clone(), + interaction_id: id("sugar-x"), + kind_id: id("reward-pulse"), + duration_ms: 1.0, + }) + } + }); + if admitted.is_ok() { + torn.store(true, Ordering::Relaxed); + return; + } + } + }); + for _ in 0..200_000 { + if torn.load(Ordering::Relaxed) { + break; + } + // The state after a cut: the sugar is in flight and the last pulse is over. + { + let mut state = queue.lock(); + state.queued.clear(); + state.in_flight = vec![in_flight.clone()]; + state.set_remaining(&agent, Some(0.0)); + } + queue.commit( + vec![in_flight.clone()], + AdmissionEnd::Applied { boundary: 1 }, + &[(agent.clone(), Some(400.0))], + ); + } + stop.store(true, Ordering::Relaxed); + }); + assert!( + !torn.load(Ordering::Relaxed), + "a sugar was admitted into a live pulse in the commit's window" + ); + } +} diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index 53901bb..6bcd53d 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -325,6 +325,43 @@ pub fn encode_payload( encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string()) } +/// A capture's inputs, copied at the boundary so the encoding can run off the endpoint's lock. +struct CaptureSnapshot { + state: AgentState, + agent_id: Id, + checkpoint_id: Id, + scope: Scope, + committed_step: u64, + profile: AssetRef, + seed: i32, + reinforcements: u64, + macro_channels: Vec, + accumulator: TickAccumulator, + context: TypedValue, +} + +impl CaptureSnapshot { + fn encode(&self) -> DomainResult> { + encode_payload( + &self.state, + &PayloadIdentity { + agent_id: &self.agent_id, + checkpoint_id: &self.checkpoint_id, + source_scope: &self.scope, + committed_step: self.committed_step, + profile: &self.profile, + seed: self.seed, + reinforcements: self.reinforcements, + macro_channels: &self.macro_channels, + }, + &self.accumulator, + &self.context, + None, + ) + .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None)) + } +} + /// The reinforcement calls a `FLYAGT01` capture payload records (`learning.updates`). pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result { let parts = decode_envelope(bytes, PAYLOAD_MAGIC) @@ -1375,7 +1412,8 @@ impl LegacyAgentWorker { /// The capture payload: `agent_to_chunks` in a checkpoint envelope, plus a `session` /// manifest member with the accumulator, the context and the identities. The readout /// transient is not in it (`legacy-transient-reset`). - fn payload(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult> { + /// Everything a capture payload is encoded from, copied out of the live agent. + fn snapshot(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult { let agent = self.agent.as_ref().expect("initialized"); let accumulator = self.accumulator.as_ref().expect("initialized"); let context = self.context.as_ref().expect("initialized"); @@ -1383,23 +1421,19 @@ impl LegacyAgentWorker { // The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`). state.remainder = rational_remainder_to_legacy(&accumulator.remainder()) .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?; - encode_payload( - &state, - &PayloadIdentity { - agent_id: &self.config.agent_id, - checkpoint_id, - source_scope: scope, - committed_step: k, - profile: &self.profile.asset, - seed: self.seed, - reinforcements: self.reinforcements, - macro_channels: &self.config.macro_channels, - }, - accumulator, - &context.typed, - None, - ) - .map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None)) + Ok(CaptureSnapshot { + state, + agent_id: self.config.agent_id.clone(), + checkpoint_id: checkpoint_id.clone(), + scope: scope.clone(), + committed_step: k, + profile: self.profile.asset.clone(), + seed: self.seed, + reinforcements: self.reinforcements, + macro_channels: self.config.macro_channels.clone(), + accumulator: accumulator.clone(), + context: context.typed.clone(), + }) } async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { @@ -1425,36 +1459,50 @@ impl LegacyAgentWorker { )); } let params: CaptureParams = ctx.params()?; - let previous = self.status.state(); - self.status.set_state(WorkerState::Capturing); - let bytes = self.payload(¶ms.checkpoint_id, &scope, k); - let bytes = match bytes { - Ok(bytes) => bytes, - Err(e) => { - self.status.set_state(previous); - return Err(e); - } + // The boundary's state, taken under the endpoint's lock: a copy, as the legacy loop's + // `export_state` is. Encoding, digesting and sealing it -- milliseconds on the full + // connectome -- run after the lock is released (`HandlerReply::deferred`), so the next + // Prepare does not wait for them (TASK-01 review N5). + let snapshot = { + let _span = crate::profile::span("agent.capture.snapshot"); + self.snapshot(¶ms.checkpoint_id, &scope, k)? }; - let digest = digest_of_bytes(&bytes); - let artifact = crate::state::seal_payload(ctx.client, &bytes, &digest).await; - self.status.set_state(previous); - let artifact = artifact?; let graph = self.graph.as_ref().expect("initialized"); - let result = CaptureResult { - checkpoint_id: params.checkpoint_id, - boundary: k, - compatibility_digest: compatibility_digest( - &self.config.agent_id, - &self.profile.asset, - graph, - self.seed, - ), - payload: artifact.reference().clone(), - }; - Ok(HandlerReply::with_artifacts( - object(result.to_json()), - vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)], - )) + let compatibility = compatibility_digest( + &self.config.agent_id, + &self.profile.asset, + graph, + self.seed, + ); + let client = ctx.client.clone(); + Ok(HandlerReply::deferred(Box::pin(async move { + let bytes = tokio::task::spawn_blocking(move || { + let _span = crate::profile::span("agent.capture.encode"); + let bytes = snapshot.encode()?; + let digest = { + let _span = crate::profile::span("agent.capture.digest"); + digest_of_bytes(&bytes) + }; + Ok::<_, DomainError>((bytes, digest)) + }) + .await + .map_err(|e| DomainError::new(ErrorCode::Internal, e.to_string(), MutationCertainty::None))?; + let (bytes, digest) = bytes?; + let artifact = { + let _span = crate::profile::span("agent.capture.seal"); + crate::state::seal_payload(&client, &bytes, &digest).await? + }; + let result = CaptureResult { + checkpoint_id: params.checkpoint_id, + boundary: k, + compatibility_digest: compatibility, + payload: artifact.reference().clone(), + }; + Ok(HandlerReply::with_artifacts( + object(result.to_json()), + vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)], + )) + }))) } async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult { diff --git a/services/flysim/crates/fly-session/src/rpc.rs b/services/flysim/crates/fly-session/src/rpc.rs index 11a4477..c5227d1 100644 --- a/services/flysim/crates/fly-session/src/rpc.rs +++ b/services/flysim/crates/fly-session/src/rpc.rs @@ -69,8 +69,35 @@ pub async fn call( request_id: DomainRequestId, want_artifacts: &[String], ) -> Result { + send(bus, target, method, scope, params, attachments, request_id, want_artifacts) + .await? + .finish() + .await +} + +/// A domain call that has been sent and not yet answered: the bus has it in order, so a call +/// sent after it to the same worker is dispatched after it. +pub struct SentCall { + method: String, + pending: flybus::PendingCall, + request_id: DomainRequestId, + want_artifacts: Vec, +} + +/// Sends one domain call without waiting for its reply ([`SentCall::finish`] waits). +#[allow(clippy::too_many_arguments)] +pub async fn send( + bus: &flybus::Client, + target: &WorkerRef, + method: &str, + scope: Option, + params: Map, + attachments: &[(&str, &flybus::Artifact)], + request_id: DomainRequestId, + want_artifacts: &[String], +) -> Result { let request = SessionRpcRequest { request_id: request_id.clone(), scope, params: Value::Object(params) }; - let mut pending = bus + let pending = bus .call( &target.service, Some(&target.bus_incarnation), @@ -80,26 +107,49 @@ pub async fn call( ) .await .map_err(|e| bus_error(method, &e))?; - let result = pending.result().await.map_err(|e| bus_error(method, &e))?; - let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone())) - .map_err(|e| DomainError::invalid(format!("{method}: {e}")))?; - let mut artifacts = BTreeMap::new(); - for name in want_artifacts { - if let Ok(artifact) = result.artifact(name) { - // An independent explicit hold, so the handle outlives this delivery and can be - // forwarded to several Commit calls and to publication. - match artifact.retain().await { - Ok(hold) => { - artifacts.insert(name.clone(), hold); - } - Err(_) => { - artifacts.insert(name.clone(), artifact); - } + Ok(SentCall { + method: method.to_owned(), + pending, + request_id, + want_artifacts: want_artifacts.to_vec(), + }) +} + +impl SentCall { + /// Waits for the terminal reply. + pub async fn finish(mut self) -> Result { + let method = self.method.as_str(); + let result = self.pending.result().await.map_err(|e| bus_error(method, &e))?; + let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone())) + .map_err(|e| DomainError::invalid(format!("{method}: {e}")))?; + // An independent explicit hold on each wanted attachment, so the handle outlives this + // delivery and can be forwarded to several Commit calls and to publication. The holds + // are independent router round trips, so they are taken concurrently. + let wanted: Vec<(String, flybus::Artifact)> = self + .want_artifacts + .iter() + .filter_map(|name| result.artifact(name).ok().map(|a| (name.clone(), a))) + .collect(); + let retains: Vec<_> = wanted + .into_iter() + .map(|(name, artifact)| { + tokio::spawn(async move { + match artifact.retain().await { + Ok(hold) => (name, hold), + Err(_) => (name, artifact), + } + }) + }) + .collect(); + let mut artifacts = BTreeMap::new(); + for retain in retains { + if let Ok((name, artifact)) = retain.await { + artifacts.insert(name, artifact); } } + drop(result); + Ok(DomainReply { outcome, request_id: self.request_id, artifacts }) } - drop(result); - Ok(DomainReply { outcome, request_id, artifacts }) } /// Maps a bus failure onto a domain error, preserving how certain the mutation is. diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index e0f8469..0c4d42a 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -113,24 +113,39 @@ impl StatusCell { } } +/// The rest of a reply a handler finishes outside the endpoint's lock. +pub type DeferredReply = + std::pin::Pin> + Send>>; + /// What a handler produced: a domain `result` object and the artifacts it attaches. pub struct HandlerReply { pub result: Map, pub artifacts: Vec<(String, flybus::Artifact)>, /// True when a failure left the endpoint mutated; the shell reports it as such. pub mutated: bool, + /// When set, the reply is this future's: the handler took what it needs from the endpoint + /// (a state snapshot at the committed boundary) and the rest -- encoding, digesting and + /// sealing a capture payload -- runs after the endpoint's lock is released, so the next + /// mutation (the next `Agent.Prepare`) does not wait for it. The bus call is answered + /// when it completes, and cached like any other reply. + pub deferred: Option, } impl HandlerReply { pub fn new(result: Map) -> HandlerReply { - HandlerReply { result, artifacts: Vec::new(), mutated: true } + HandlerReply { result, artifacts: Vec::new(), mutated: true, deferred: None } } pub fn with_artifacts( result: Map, artifacts: Vec<(String, flybus::Artifact)>, ) -> HandlerReply { - HandlerReply { result, artifacts, mutated: true } + HandlerReply { result, artifacts, mutated: true, deferred: None } + } + + /// A reply finished by `rest` outside the endpoint's lock ([`HandlerReply::deferred`]). + pub fn deferred(rest: DeferredReply) -> HandlerReply { + HandlerReply { result: Map::new(), artifacts: Vec::new(), mutated: true, deferred: Some(rest) } } /// The canonical JSON of one method result. @@ -304,6 +319,7 @@ async fn run( ) }; let mut running: Vec> = Vec::new(); + let order = Arc::new(LockOrder::default()); while let Some(incoming) = service.next().await { let method = incoming.method().to_owned(); let responder = incoming.responder(); @@ -491,9 +507,12 @@ async fn run( // original bus call still completes normally. The endpoint mutex, not this loop, // enforces one mutation at a time. running.retain(|task| !task.is_finished()); + let ticket = order.issue(); running.push(tokio::spawn(execute( client.clone(), endpoint.clone(), + order.clone(), + ticket, cache.clone(), status.clone(), worker_id.clone(), @@ -512,11 +531,73 @@ async fn run( } } +/// Admitted mutations take the endpoint's lock in the order they arrived. +/// +/// Each runs in a task of its own, so the shell keeps reading, and tasks are not scheduled in +/// spawn order: without this, a `State.Capture` followed on the wire by the next +/// `Agent.Prepare` could find the agent already prepared. A ticket per admitted mutation, taken +/// in arrival order, and the lock taken only on the ticket's turn keep the wire's order. +#[derive(Default)] +struct LockOrder { + issued: std::sync::atomic::AtomicU64, + turn: std::sync::atomic::AtomicU64, + changed: tokio::sync::Notify, +} + +impl LockOrder { + fn issue(&self) -> u64 { + self.issued.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + } + + async fn lock_in_turn<'a, E>( + &self, + ticket: u64, + endpoint: &'a tokio::sync::Mutex, + ) -> tokio::sync::MutexGuard<'a, E> { + loop { + let changed = self.changed.notified(); + if self.turn.load(std::sync::atomic::Ordering::SeqCst) == ticket { + break; + } + changed.await; + } + // Queue on the lock first, then hand the turn on: the next ticket queues behind this + // one on the (fair) mutex. + let lock = endpoint.lock(); + tokio::pin!(lock); + let guard = match futures_poll_once(lock.as_mut()).await { + Some(guard) => guard, + None => { + self.advance(); + return lock.await; + } + }; + self.advance(); + guard + } + + fn advance(&self) { + self.turn.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + self.changed.notify_waiters(); + } +} + +/// Polls a future once: its output if it is ready, else `None` with the future registered. +async fn futures_poll_once(mut f: F) -> Option { + std::future::poll_fn(|cx| match std::pin::Pin::new(&mut f).poll(cx) { + std::task::Poll::Ready(v) => std::task::Poll::Ready(Some(v)), + std::task::Poll::Pending => std::task::Poll::Ready(None), + }) + .await +} + /// Runs one admitted mutation, records its reply and answers the bus call. #[allow(clippy::too_many_arguments)] async fn execute( client: flybus::Client, endpoint: Arc>, + order: Arc, + ticket: u64, cache: Arc>, status: StatusCell, worker_id: Id, @@ -533,7 +614,7 @@ async fn execute( let outcome = { // One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is // never held across a bus round trip taken by anything else. - let mut e = endpoint.lock().await; + let mut e = order.lock_in_turn(ticket, &endpoint).await; let ctx = HandlerCtx { method: &method, request: &request, @@ -542,16 +623,34 @@ async fn execute( }; e.handle(ctx).await }; + // A deferred reply finishes here, with the endpoint's lock released. + let outcome = match outcome { + Ok(HandlerReply { deferred: Some(rest), .. }) => rest.await, + other => other, + }; match outcome { Ok(reply) => { let outcome = success(&request, &worker_id, &incarnation_id, reply.result.clone()); - let mut holds = Vec::with_capacity(reply.artifacts.len()); - for (name, artifact) in &reply.artifacts { - // The cache owns its own hold, so a replay survives the first caller - // consuming its delivery. - match artifact.retain().await { - Ok(hold) => holds.push((name.clone(), hold)), - Err(_) => holds.push((name.clone(), artifact.clone())), + // The cache owns its own hold on every artifact, so a replay survives the first + // caller consuming its delivery. The holds are independent router round trips, so + // they are taken concurrently. + let retains: Vec<_> = reply + .artifacts + .iter() + .map(|(name, artifact)| { + let (name, artifact) = (name.clone(), artifact.clone()); + tokio::spawn(async move { + match artifact.retain().await { + Ok(hold) => (name, hold), + Err(_) => (name, artifact), + } + }) + }) + .collect(); + let mut holds = Vec::with_capacity(retains.len()); + for retain in retains { + if let Ok(pair) = retain.await { + holds.push(pair); } } let cached = CachedReply::with_artifacts(outcome.clone(), holds);