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 9e7f94f..9085f6c 100644 --- a/services/flysim/crates/fly-legacy-session/src/composition.rs +++ b/services/flysim/crates/fly-legacy-session/src/composition.rs @@ -629,42 +629,33 @@ impl LegacySession { } /// 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 } - /// One transition and what the legacy loop does at the boundary it reaches, in the declared - /// order (`legacy-gameboy-v1` sections 4 and 16): the slot save (inside the step), the - /// milestone archive when the rank climbed (`Sim::track_rank`), the rollback, a durable save - /// after it, then the interval saves (`checkpoint_if_due`). - pub async fn advance(&mut self) -> Result<(Step, Vec), String> { - let report = self - .coordinator - .step() - .await - .map_err(|e| format!("step ({} at {}): {}", e.detail, e.phase, e.error.message))?; - // The captures begun at the last boundary: the agent sealed its payload while this - // transition's Prepare ticked. + /// 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 { @@ -674,6 +665,31 @@ impl LegacySession { }); self.pending_saves.push(ticket); } + Ok(saves) + } + + /// One transition and what the legacy loop does at the boundary it reaches, in the declared + /// order (`legacy-gameboy-v1` sections 4 and 16): the slot save (inside the step), the + /// milestone archive when the rank climbed (`Sim::track_rank`), the rollback, a durable save + /// after it, then the interval saves (`checkpoint_if_due`). + pub async fn advance(&mut self) -> Result<(Step, Vec), String> { + let report = match self.coordinator.step().await { + Ok(report) => report, + Err(e) => { + // The legacy writer already has the saves of the earlier boundaries: hand the + // begun captures over before reporting the failure (TASK-01 review R2-1). + let flushed = self.flush_captures().await.err(); + let mut message = + format!("step ({} at {}): {}", e.detail, e.phase, e.error.message); + if let Some(flush) = flushed { + message.push_str(&format!("; and the pending saves: {flush}")); + } + return Err(message); + } + }; + // The captures begun at the last boundary: the agent sealed its payload while this + // transition's Prepare ticked. + let saves = self.flush_captures().await?; if self.checkpointer.is_some() { let rank = self.task.rank(); let ms = self.task.brain_ms(); @@ -730,14 +746,16 @@ impl LegacySession { if self.checkpointer.is_none() { return Ok(None); } - for ticket in self.finish_captures().await? { - self.pending_saves.push(ticket); - } + 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/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-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index 01d2742..85ef174 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -1562,6 +1562,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)] @@ -1619,6 +1632,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 @@ -1626,18 +1644,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) { @@ -2447,10 +2485,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.view_digests(&step_result.observation).await? @@ -5930,3 +5972,71 @@ impl Coordinator { }) } } + +#[cfg(test)] +mod admission_race_tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + + /// TASK-01 review R2-3: a sugar arriving while a commit ends the in-flight admission and + /// reports the pulse must never see "no pending admission" beside the old, over pulse. The + /// only state the hammer accepts in is exactly that torn one; the commit under test is + /// atomic, so it is never seen. + #[test] + fn no_sugar_is_admitted_between_a_commit_ending_and_its_pulse() { + let queue = AdmissionQueue::default(); + let agent = id("fly"); + let in_flight = Admission::Stimulus { + agent_id: agent.clone(), + interaction_id: id("sugar-1"), + kind_id: id("reward-pulse"), + duration_ms: 400.0, + }; + let stop = AtomicBool::new(false); + let torn = AtomicBool::new(false); + std::thread::scope(|scope| { + scope.spawn(|| { + while !stop.load(Ordering::Relaxed) { + let admitted = queue.admit_with(&agent, |remaining, pending| { + if remaining.unwrap_or(0.0).max(pending.unwrap_or(0.0)) > 0.0 { + Err(()) + } else { + Ok(Admission::Stimulus { + agent_id: agent.clone(), + interaction_id: id("sugar-x"), + kind_id: id("reward-pulse"), + duration_ms: 1.0, + }) + } + }); + if admitted.is_ok() { + torn.store(true, Ordering::Relaxed); + return; + } + } + }); + for _ in 0..200_000 { + if torn.load(Ordering::Relaxed) { + break; + } + // The state after a cut: the sugar is in flight and the last pulse is over. + { + let mut state = queue.lock(); + state.queued.clear(); + state.in_flight = vec![in_flight.clone()]; + state.set_remaining(&agent, Some(0.0)); + } + queue.commit( + vec![in_flight.clone()], + AdmissionEnd::Applied { boundary: 1 }, + &[(agent.clone(), Some(400.0))], + ); + } + stop.store(true, Ordering::Relaxed); + }); + assert!( + !torn.load(Ordering::Relaxed), + "a sugar was admitted into a live pulse in the commit's window" + ); + } +}