diff --git a/services/flysim/crates/fly-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index 9d54739..01a17ac 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -20,7 +20,7 @@ use crate::publish::PublicationOutcome; use crate::metrics::Metrics; use crate::phase::{Phase, PhaseMachine}; use crate::rpc::{self, DomainReply, Serials, WorkerRef}; -use crate::task::{ActionExecutor, Task}; +use crate::task::{ActionExecutor, Inspection, Task}; // `crate::types` is this crate's facade over the shared `fly-session-types` crate; the // glob keeps the contract's own names in sight instead of restating them. use crate::types::*; @@ -237,6 +237,11 @@ pub struct AgentSlot { pub worker_threads: u64, pub tick_duration: RationalNs, pub warmup_ticks: u64, + /// The numerical model and plasticity versions the profile runs, which are part of the + /// agent's compatibility identity. The synthetic fake model's by default; the legacy profile + /// runs `lif-1ms-f64-v2` and `fly-kc-mbon-rstdp-v2`. + pub model_version: String, + pub plasticity_version: String, pub committed_step: u64, /// The graph this fly attested to at `Agent.Initialize`, which is what the published /// descriptor says about it. `None` before initialization. @@ -271,6 +276,8 @@ impl AgentSlot { worker_threads: 1, tick_duration: RationalNs::ZERO, warmup_ticks: 0, + model_version: crate::agent::MODEL_VERSION.to_owned(), + plasticity_version: crate::agent::PLASTICITY_VERSION.to_owned(), committed_step: 0, graph: None, telemetry: None, @@ -339,6 +346,36 @@ pub struct Coordinator { /// The rollback policy the composition declares, if any (`legacy-ratchet-rollback-v1` is /// the only one defined). Without one, a task's rollback request is a task failure. rollback_policy: Option, + /// The documents `Environment.Initialize` names. The synthetic arena's by default; a + /// composition with its own backend (the legacy Game Boy) sets them. + backend_config: AssetRef, + task_config: AssetRef, + /// The decision schema every agent's profile registers. + decision_schema: SchemaRef, + /// The inspection attachments the task reads (`Task::inspection_attachments`), and the + /// holds on them: O[k]'s until transition k -> k+1 has been evaluated, O[k+1]'s from the + /// world's result until it becomes the committed boundary's. + inspection_names: Vec, + inspection_held: BTreeMap, + pending_inspection: BTreeMap, + /// O[k]'s inspection with its bytes, as the executor and the task read it. + current_inspection: Option, + /// The environment's advertised capabilities, from `Worker.Hello`. + environment_capabilities: Vec, + /// Agent reply attachments `Agent.Commit` is asked for (`telemetry.spikes`), kept in the + /// step details. None by default. + commit_attachments: Vec, + /// Record [`StepDetails`] for every transition (a parity run). + record_details: bool, + last_details: Option, + /// Audience admissions: queued by the edge, cut into the next Prepare. + admissions: AdmissionQueue, + /// The admissions the transition in flight carries, until it commits or fails. + in_flight_admissions: Vec, + /// How many rollbacks this session has applied, which names the next rollback epoch. + rollbacks: u64, + /// The world's state format, when it is not the synthetic arena's. + state_format_id: Option, lifecycle_acks: Vec<(WorkerRef, DomainRequestId)>, stats: Stats, /// The ordered actions this session took, for the ordering assertions. @@ -435,6 +472,27 @@ impl Coordinator { pause: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), episode: None, rollback_policy: None, + backend_config: crate::environment::synthetic_asset( + "counter-arena-backend", + "counter-arena-backend-v1", + ), + task_config: crate::environment::synthetic_asset( + "counter-arena-setup", + "counter-arena-setup-v1", + ), + decision_schema: crate::task::decision_schema(), + inspection_names: Vec::new(), + inspection_held: BTreeMap::new(), + pending_inspection: BTreeMap::new(), + current_inspection: None, + environment_capabilities: Vec::new(), + commit_attachments: Vec::new(), + record_details: false, + last_details: None, + admissions: AdmissionQueue::default(), + in_flight_admissions: Vec::new(), + rollbacks: 0, + state_format_id: None, lifecycle_acks: Vec::new(), stats: Stats::default(), audit: Vec::new(), @@ -531,9 +589,10 @@ impl Coordinator { } /// Declares the composition's rollback policy (`workers-v1` section 4 and `step-v1` section 6, - /// both amended 2026-09-23). Only `legacy-ratchet-rollback-v1` is defined. Until the rollback - /// sequence is wired (TASK-01), a declared rollback request pauses the session at its boundary - /// like a terminal one, which is safe; an undeclared one fails the epoch. + /// both amended 2026-09-23). Only `legacy-ratchet-rollback-v1` is defined. With it declared, a + /// rollback request is applied at the boundary it was asked for (`apply_rollback`, TASK-01), + /// and every agent must advertise the policy at `Worker.Hello`; without it the request fails + /// the epoch. pub fn declare_rollback_policy(&mut self, policy: &str) -> Result<(), DomainError> { if policy != fly_session_types::extensions::ROLLBACK_POLICY { return Err(DomainError::invalid(format!("{policy} is not a defined rollback policy"))); @@ -542,6 +601,76 @@ impl Coordinator { Ok(()) } + /// The documents `Environment.Initialize` names: the backend configuration and the task + /// setup. A composition with its own backend sets them before [`Coordinator::bootstrap`]. + pub fn set_environment_config(&mut self, backend_config: AssetRef, task_config: AssetRef) { + self.backend_config = backend_config; + self.task_config = task_config; + } + + /// The view and audio stream ids this composition's world produces, which name the + /// attachments `Environment.Initialize` is asked for (afterwards they come from its + /// descriptor). The synthetic arena's by default. + pub fn set_media(&mut self, views: &[&str], audio_streams: &[&str]) { + self.media_names = views + .iter() + .map(|v| media::view_attachment(v)) + .chain(audio_streams.iter().map(|a| media::audio_attachment(a))) + .collect(); + } + + /// The state format the world's captures declare (`Compatibility.stateFormatId`): the + /// synthetic arena's by default, `fly-gb-env-v1` for the legacy Game Boy world (ENV-01). + pub fn set_state_format(&mut self, state_format_id: &str) { + self.state_format_id = Some(id(state_format_id)); + } + + /// The world's compatibility as this composition declares it. + fn world_compatibility(&self, descriptor: &EnvironmentDescriptor) -> crate::state::Compatibility { + let mut compatibility = crate::state::Compatibility::of(descriptor); + if let Some(format) = &self.state_format_id { + compatibility.state_format_id = format.clone(); + } + compatibility + } + + /// The decision schema the agents' profile registers (`gameboy-channels-v1` for the legacy + /// composition). A PreparedDecision carrying another is refused. + pub fn set_decision_schema(&mut self, schema: SchemaRef) { + self.decision_schema = schema; + } + + /// Ask every `Agent.Commit` for these reply attachments and keep their bytes in the step + /// details (the legacy agent's `telemetry.spikes`). Implies [`Coordinator::record_details`]. + pub fn request_commit_attachments(&mut self, names: &[&str]) { + self.commit_attachments = names.iter().map(|n| (*n).to_owned()).collect(); + self.record_details = true; + } + + /// Record [`StepDetails`] for every transition, for a parity run to read. + pub fn record_details(&mut self, on: bool) { + self.record_details = on; + } + + /// The details of the last completed transition, when they are recorded. + pub fn take_details(&mut self) -> Option { + self.last_details.take() + } + + /// The admission queue: the edge's handle for audience and operator inputs. + pub fn admissions(&self) -> AdmissionQueue { + self.admissions.clone() + } + + /// O[k]'s inspection with its bytes, as the task last read it. + pub fn current_inspection(&self) -> Option<&Inspection> { + self.current_inspection.as_ref() + } + + pub fn episode_id(&self) -> &Id { + &self.episode_id + } + pub fn rollback_policy(&self) -> Option<&Id> { self.rollback_policy.as_ref() } @@ -639,6 +768,13 @@ impl Coordinator { self.pending_views.clear(); self.audio.clear(); self.pending_audio.clear(); + self.inspection_held.clear(); + self.pending_inspection.clear(); + // An admission whose Prepare never committed is aborted, and the edge refunds it + // (`legacy-gameboy-v1` section 15). Queued ones stay queued for the restored epoch. + let aborted = std::mem::take(&mut self.in_flight_admissions); + self.admissions.end(aborted, AdmissionEnd::Aborted); + self.admissions.forget_remaining(); match &participant { Some(who) => self.audit.push(format!("fail:{detail}:{who}")), None => self.audit.push(format!("fail:{detail}")), @@ -717,7 +853,12 @@ impl Coordinator { Ok(()) } - async fn hello(&mut self, worker: WorkerRef, role: Role, required: &str) -> Outcome { + async fn hello( + &mut self, + worker: WorkerRef, + role: Role, + required: &str, + ) -> Outcome<(Id, Vec)> { let params = HelloParams { session_id: self.session_id.clone(), expected_worker_id: worker.worker_id.clone(), @@ -757,19 +898,33 @@ impl Coordinator { )); } self.audit.push(format!("hello:{}", worker.worker_id)); - Ok(result.incarnation_id) + Ok((result.incarnation_id, result.capabilities)) } async fn hello_environment(&mut self) -> Outcome<()> { let worker = self.environment.clone(); - let incarnation = self.hello(worker, Role::Environment, "world-step-v1").await?; + let (incarnation, capabilities) = + self.hello(worker, Role::Environment, "world-step-v1").await?; self.environment.domain_incarnation = Some(incarnation); + self.environment_capabilities = capabilities; Ok(()) } async fn hello_agent(&mut self, index: usize) -> Outcome<()> { let worker = self.agents[index].worker.clone(); - let incarnation = self.hello(worker, Role::Agent, "agent-step-v1").await?; + let (incarnation, capabilities) = self.hello(worker, Role::Agent, "agent-step-v1").await?; + if self.rollback_policy.is_some() + && !capabilities.iter().any(|c| c == fly_session_types::extensions::ROLLBACK_CAPABILITY) + { + return Err(self.fail_now( + DomainError::before( + ErrorCode::Unsupported, + "the composition declares a rollback policy and the agent does not answer \ + Agent.Rollback", + ), + "hello", + )); + } self.agents[index].worker.domain_incarnation = Some(incarnation); Ok(()) } @@ -791,20 +946,15 @@ impl Coordinator { .map(|a| PortBinding { port_id: a.port_id.clone(), agent_id: a.agent_id.clone() }) .collect(); let params = EnvironmentInitializeParams { - backend_config: crate::environment::synthetic_asset( - "counter-arena-backend", - "counter-arena-backend-v1", - ), - task_config: crate::environment::synthetic_asset( - "counter-arena-setup", - "counter-arena-setup-v1", - ), + backend_config: self.backend_config.clone(), + task_config: self.task_config.clone(), episode_id: self.episode_id.clone(), port_bindings: bindings.iter().map(PortBinding::pair).collect(), }; let worker = self.environment.clone(); let scope = self.scope(0); - let want = self.media_names.clone(); + self.inspection_names = self.task.inspection_attachments(); + let want = self.wanted_media(); let reply = self .call( &worker, @@ -845,10 +995,18 @@ impl Coordinator { "port-assignment", )); } - let (views, audio) = media::split_attachments(reply.artifacts); + let mut artifacts = reply.artifacts; + let held = self.take_inspection(&mut artifacts); + let (views, audio) = media::split_attachments(artifacts); self.views = views; self.audio = audio; self.media_names = media::attachment_names(&result.descriptor); + let inspection = self + .read_inspection(0, &result.observation.inspection, &held) + .await + .map_err(|e| self.fail_now(e, "observation-0"))?; + self.inspection_held = held; + self.current_inspection = Some(inspection); self.timelines = AudioTimelines::fresh(&result.descriptor); if let Err(e) = self.timelines.accept(&result.descriptor, &result.observation) { return Err(self.fail_now(e, "observation-0")); @@ -872,8 +1030,85 @@ impl Coordinator { Ok(()) } + /// SHA-256 of each sensory view's bytes as this session holds them, for the step details. + async fn view_digests( + &mut self, + observation: &WorldObservation, + ) -> Outcome> { + let mut out = Vec::new(); + for view in &observation.sensory_views { + let name = media::view_attachment(&view.view_id); + let Some(artifact) = self.views.get(&name).cloned() else { continue }; + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("reading {name}: {}", e.message), + MutationCertainty::Applied, + ), + "details", + ) + })?; + out.push((view.view_id.clone(), digest_of_bytes(&bytes))); + } + Ok(out) + } + + /// The attachments a world reply is asked for: the declared media, then the inspection + /// attachments the task reads. + fn wanted_media(&self) -> Vec { + let mut want = self.media_names.clone(); + for name in &self.inspection_names { + if !want.contains(name) { + want.push(name.clone()); + } + } + want + } + + /// Takes the inspection attachments out of a world reply's artifacts, leaving the media. + fn take_inspection( + &self, + artifacts: &mut BTreeMap, + ) -> BTreeMap { + self.inspection_names + .iter() + .filter_map(|name| artifacts.remove(name).map(|a| (name.clone(), a))) + .collect() + } + + /// Reads one boundary's inspection attachments into the [`Inspection`] the task and the + /// executor read. Every declared attachment must be there: a boundary whose inspection + /// bytes are missing is refused, never replaced by an older one. + async fn read_inspection( + &self, + boundary: u64, + value: &TypedValue, + held: &BTreeMap, + ) -> DomainResult { + let mut attachments = BTreeMap::new(); + for name in &self.inspection_names { + let artifact = held.get(name).ok_or_else(|| { + DomainError::new( + ErrorCode::BufferInvalid, + format!("boundary {boundary}'s inspection arrived without {name}"), + MutationCertainty::Unknown, + ) + })?; + let bytes = artifact.read_all().await.map_err(|e| { + DomainError::new( + ErrorCode::BufferInvalid, + format!("reading {name}: {}", e.message), + MutationCertainty::Unknown, + ) + })?; + attachments.insert(name.clone(), std::sync::Arc::new(bytes)); + } + Ok(Inspection { boundary, value: value.clone(), attachments }) + } + fn bootstrap_task(&mut self) -> Outcome<()> { - let observation = self.observation.clone().expect("initialized"); + let inspection = self.current_inspection.clone().expect("initialized"); let bindings: Vec = self .agents .iter() @@ -881,7 +1116,7 @@ impl Coordinator { .collect(); let bootstrap = self .task - .bootstrap(&observation.inspection, &bindings) + .bootstrap(&inspection, &bindings) .map_err(|e| self.fail_now(e, "task-bootstrap"))?; for event in &bootstrap.events { if event.source_step != 0 { @@ -1101,6 +1336,170 @@ pub struct StepReport { pub terminal: bool, } +/// One audience input the coordinator admits into a Prepare (`workers-v1` section 5 and its +/// amendment; `legacy-gameboy-v1` section 15). +/// +/// The rules that decide *whether* an input is admitted (a rate limiter, "no overlap with an +/// active pulse") are the composition's and run on the edge side of [`AdmissionQueue`], reading +/// [`AdmissionQueue::stimulus_remaining_ms`]: the last completed commit's value, one commit +/// stale at most. The coordinator only places what was admitted at the next admission cut, in +/// admission order, and reports each one applied or aborted. +#[derive(Clone, Debug, PartialEq)] +pub enum Admission { + /// A profile-supported stimulus in `Prepare.preStepStimulations` (sugar: `reward-pulse`). + Stimulus { agent_id: Id, interaction_id: Id, kind_id: Id, duration_ms: f64 }, +} + +impl Admission { + pub fn agent_id(&self) -> &Id { + match self { + Admission::Stimulus { agent_id, .. } => agent_id, + } + } + + pub fn interaction_id(&self) -> &Id { + match self { + Admission::Stimulus { interaction_id, .. } => interaction_id, + } + } +} + +/// How an admission ended: applied by a Prepare whose transition committed at `boundary`, or +/// aborted because the epoch failed first (the edge refunds it). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AdmissionEnd { + Applied { boundary: u64 }, + Aborted, +} + +#[derive(Debug, Default)] +struct AdmissionState { + queued: Vec, + remaining: BTreeMap, + ended: Vec<(Admission, AdmissionEnd)>, +} + +/// 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)] +pub struct AdmissionQueue(std::sync::Arc>); + +impl AdmissionQueue { + fn lock(&self) -> std::sync::MutexGuard<'_, AdmissionState> { + self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Queue an admitted input for the next admission cut. + pub fn admit(&self, admission: Admission) { + self.lock().queued.push(admission); + } + + /// `stimulusRemainingMs` of the agent's last completed commit (an `Agent.Rollback` reply + /// counts as one). `None` before the first commit of an epoch -- after a restore the pulse + /// is unknown and the legacy rule refuses with a retry (`legacy-gameboy-v1` section 15). + pub fn stimulus_remaining_ms(&self, agent_id: &Id) -> Option { + self.lock().remaining.get(agent_id).copied() + } + + /// Inputs admitted and not yet cut into a Prepare. + pub fn queued(&self) -> usize { + self.lock().queued.len() + } + + /// Every admission that has ended since the last call, in the order they ended. + pub fn take_ended(&self) -> Vec<(Admission, AdmissionEnd)> { + std::mem::take(&mut self.lock().ended) + } + + fn cut(&self) -> Vec { + std::mem::take(&mut self.lock().queued) + } + + fn end(&self, admissions: Vec, end: AdmissionEnd) { + let mut state = self.lock(); + for admission in admissions { + state.ended.push((admission, end.clone())); + } + } + + 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); + } + } + } + + fn forget_remaining(&self) { + self.lock().remaining.clear(); + } +} + +/// Everything one transition exchanged, for a parity run (`Coordinator::record_details`): the +/// fields a legacy `FLY_TRACE` line is assembled from. +#[derive(Clone, Debug)] +pub struct StepDetails { + /// The boundary the transition started from. + pub step: u64, + /// O[k]'s `engineFrame`. + pub engine_frame: Option, + /// The admissions this transition's Prepare applied, in admission order. + pub admissions: Vec, + pub prepared: Vec<(Id, PreparedDecision)>, + pub controls: Vec, + pub commits: Vec<(Id, AgentCommitResult)>, + /// `(agent, attachment, bytes)` for each requested commit reply attachment. + pub commit_attachments: Vec<(Id, String, Vec)>, + /// SHA-256 of each O[k+1] view's bytes, by view id. + pub view_digests: Vec<(String, Digest)>, + pub evaluation: crate::task::Evaluation, + /// The boundary actions applied at `Ready(k+1)`, in order. + pub boundary_actions: Vec, + /// After a rollback: the new epoch, the restored observation and each agent's reply. + pub rollback: Option, +} + +/// What a rollback at a boundary produced. +#[derive(Clone, Debug)] +pub struct RollbackDetails { + pub epoch: Id, + pub observation: WorldObservation, + pub view_digests: Vec<(String, Digest)>, + pub agents: Vec<(Id, fly_session_types::extensions::AgentRollbackResult)>, +} + +/// 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)] +pub struct ImportSpec { + pub checkpoint_id: Id, + /// The boundary the checkpoint is at. + pub boundary: u64, + /// The environment's `State.Capture` payload. + pub world_payload: Vec, + /// Every agent, in sorted agent-id order. + pub agents: Vec, + pub task_ledger: TypedValue, + /// Each declared audio stream's next sample. + pub audio_positions: BTreeMap, +} + +/// One agent of an [`ImportSpec`]. +#[derive(Clone, Debug)] +pub struct ImportedAgent { + pub agent_id: Id, + /// The agent's `State.Capture` payload. + pub payload: Vec, + pub brain_ticks: u64, + pub remainder: RationalNs, + /// The decision context the payload retains. + pub context: TypedValue, +} + /// One per-agent bus call, ready to dispatch. struct Job { agent_id: Id, @@ -1110,6 +1509,8 @@ struct Job { params: Map, attachments: Vec<(String, flybus::Artifact)>, request_id: DomainRequestId, + /// Reply attachments to extract. + want: Vec, } /// Issues one domain call with owned arguments, so it can run in its own task. @@ -1546,7 +1947,7 @@ impl Coordinator { job.params.clone(), job.attachments.clone(), job.request_id.clone(), - Vec::new(), + job.want.clone(), deadline, ) .await; @@ -1581,7 +1982,7 @@ impl Coordinator { job.params.clone(), job.attachments.clone(), job.request_id.clone(), - Vec::new(), + job.want.clone(), deadline, ) .await; @@ -1682,14 +2083,18 @@ impl Coordinator { self.transition(Phase::Observing(k + 1))?; self.verify_step_result(k, &descriptor, &batch_id, &controls, &old_observation, &step_result)?; let scope = self.scope(k); + let pending_inspection = std::mem::take(&mut self.pending_inspection); + let new_inspection = self + .read_inspection(k + 1, &step_result.observation.inspection, &pending_inspection) + .await + .map_err(|e| self.fail_now(e, "step-result"))?; + let old_inspection = self + .current_inspection + .clone() + .expect("a bootstrapped session holds O[k]'s inspection"); let evaluation = self .task - .evaluate_transition( - &scope, - &old_observation.inspection, - &step_result.observation.inspection, - &controls, - ) + .evaluate_transition(&scope, &old_inspection, &new_inspection, &controls) .map_err(|e| { // Task interpretation failed after prepared brains and the world already // changed, so the epoch is failed rather than re-evaluated. @@ -1746,7 +2151,7 @@ impl Coordinator { self.pending_audio.get(&name).map(|a| (name, a.clone())) }) .collect(); - let commits = self + let (commits, commit_attachments) = self .commit_all(k, &step_result.observation, &mut outcomes, &mut next_contexts, &new_views) .await?; @@ -1786,8 +2191,40 @@ impl Coordinator { self.audio = new_audio; self.pending_views.clear(); self.pending_audio.clear(); + // O[k] has been evaluated, so its inspection is released; O[k+1]'s is the boundary's. + self.inspection_held = pending_inspection; + self.current_inspection = Some(new_inspection); self.observation = Some(step_result.observation.clone()); 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); + } + + let view_digests = if self.record_details { + self.view_digests(&step_result.observation).await? + } else { + Vec::new() + }; + + // ---- Ready(k+1): the boundary actions the transition asked for, saves first + // (`step-v1` section 6 amendment). + let mut boundary_actions = Vec::new(); + for slot_id in &evaluation.slot_saves { + let action = self.save_slot(k + 1, slot_id).await?; + boundary_actions.push(action); + } + let mut rollback_details = None; + if let Some(request) = &evaluation.episode + && request.kind == EpisodeRequestKind::Rollback + { + let request = request.clone(); + let (action, details) = self.apply_rollback(k + 1, &request).await?; + boundary_actions.push(action); + rollback_details = Some(details); + } let event_ids: Vec = evaluation.events.iter().map(|e| e.id.clone()).collect(); let decisions: BTreeMap = prepared @@ -1803,7 +2240,23 @@ impl Coordinator { &step_result, &outcomes, &event_ids, + &boundary_actions, ); + if self.record_details { + self.last_details = Some(StepDetails { + step: k, + engine_frame: old_observation.engine_frame.clone(), + admissions: applied, + prepared: prepared.clone(), + controls: controls.clone(), + commits: commits.clone(), + commit_attachments, + view_digests, + evaluation: evaluation.clone(), + boundary_actions: boundary_actions.clone(), + rollback: rollback_details, + }); + } // The prepared decisions and their request ids are needed by the trace, so they are // released only after it has been recorded. for slot in &mut self.agents { @@ -1813,7 +2266,12 @@ impl Coordinator { self.publish_events(k + 1, &evaluation.events).await?; self.publish_snapshot(k + 1, &decisions, &controls, &event_ids).await?; - let terminal = evaluation.episode.is_some(); + // A rollback request was applied above and is not an episode end; only a terminal one + // pauses the session for the episode policy. + let terminal = evaluation + .episode + .as_ref() + .is_some_and(|request| request.kind == EpisodeRequestKind::Terminal); if terminal { // A terminal event's final rewards are committed; then the session pauses at this // boundary and the declared episode policy runs. No worker resets itself. @@ -1857,17 +2315,44 @@ impl Coordinator { let scope = self.scope(k); // The task's per-agent decision contexts and the admitted pre-step stimulation list // are frozen here; anything accepted later waits for the next boundary. + let cut = self.admissions.cut(); + let mut admitted = Vec::new(); + for admission in cut { + if self.agent(admission.agent_id()).is_some() { + admitted.push(admission); + } else { + // An input for no configured agent is never applied; the edge refunds it. + self.admissions.end(vec![admission], AdmissionEnd::Aborted); + } + } + self.in_flight_admissions = admitted.clone(); let mut jobs = Vec::new(); let mut bodies = Vec::new(); for index in 0..self.agents.len() { let slot = &self.agents[index]; + let pre_step_stimulations: Vec = admitted + .iter() + .filter_map(|a| match a { + Admission::Stimulus { agent_id, interaction_id, kind_id, duration_ms } + if *agent_id == slot.agent_id => + { + Some(Stimulus { + id: interaction_id.clone(), + kind_id: kind_id.clone(), + duration_ms: *duration_ms, + }) + } + Admission::Stimulus { .. } => None, + }) + .collect(); let params = PrepareParams { agent_id: slot.agent_id.clone(), profile_digest: slot.profile.digest.clone(), interval, decision_context_digest: slot.context_digest.clone(), - // No audience input exists in the first synthetic composition. - pre_step_stimulations: Vec::::new(), + // What the admission cut admitted for this agent, in admission order. The + // synthetic composition has no audience input, so its list is empty. + pre_step_stimulations, }; let params = match params.to_json() { Value::Object(m) => m, @@ -1890,6 +2375,7 @@ impl Coordinator { params, attachments: Vec::new(), request_id, + want: Vec::new(), }); } let results = self.run_jobs(jobs, self.dispatch).await; @@ -1934,7 +2420,7 @@ impl Coordinator { method, )); } - if decision.decision.schema != crate::task::decision_schema() { + if decision.decision.schema != self.decision_schema { return Err(self.fail_now( DomainError::before( ErrorCode::IdentityMismatch, @@ -2009,7 +2495,11 @@ impl Coordinator { ) -> Outcome> { let scope = self.scope(k); let progress = self.task.progress(); - let clock = observation.world_time; + let _ = observation; + let inspection = self + .current_inspection + .clone() + .expect("a bootstrapped session holds O[k]'s inspection"); let mut intents: BTreeMap = BTreeMap::new(); // Sorted agent-id order, never completion order. for index in 0..self.agents.len() { @@ -2019,6 +2509,18 @@ impl Coordinator { .prepared .clone() .expect("every agent is Prepared before the batch is built"); + // `step-v1` section 3, Phase B amendment: the clock is the agent's brain time after + // its Prepare -- its executed ticks at its tick duration, exactly. + let tick = self.agents[index].tick_duration; + let clock = RationalNs::reduced( + u128::from(tick.numerator) * u128::from(decision.brain_ticks), + u128::from(tick.denominator), + ) + .map_err(|e| DomainError::invalid(e.0)); + let clock = match clock { + Ok(clock) => clock, + Err(e) => return Err(self.fail_now(e, "executor")), + }; let executor = self.executors.get_mut(&agent_id).ok_or_else(|| { DomainError::before( ErrorCode::IdentityMismatch, @@ -2032,7 +2534,7 @@ impl Coordinator { let applied = executor.apply( &scope, &decision.decision, - &observation.inspection, + &inspection, &progress, &clock, ); @@ -2101,7 +2603,7 @@ impl Coordinator { let worker = self.environment.clone(); let request_id = self.serials.next(&worker.service); self.last_advance_request = Some(request_id.clone()); - let want = self.media_names.clone(); + let want = self.wanted_media(); self.audit.push(format!("advance:{k}")); self.blame(Some(worker.worker_id.clone())); let advance_deadline = self.deadlines.probe; @@ -2223,7 +2725,9 @@ impl Coordinator { Err(e) => return Err(self.fail_now(e, "advance")), }; self.blame(None); - let (pending_views, pending_audio) = media::split_attachments(reply.artifacts); + let mut artifacts = reply.artifacts; + self.pending_inspection = self.take_inspection(&mut artifacts); + let (pending_views, pending_audio) = media::split_attachments(artifacts); self.pending_views = pending_views; self.pending_audio = pending_audio; @@ -2289,6 +2793,326 @@ impl Coordinator { } } +// ------------------------------------------------------------------------------------------- +// Boundary actions: slot saves and the declared rollback (`step-v1` section 6 amendment) + +/// The epoch a rollback moves to: the session's epoch root, then `.rb`, or a digest-named +/// id when that would pass the `Id` length bound. Deterministic, so two runs of the same +/// session name the same epochs. +fn rollback_epoch(current: &Id, n: u64) -> Id { + let root = match current.rfind(".rb") { + Some(at) if current[at + 3..].chars().all(|c| c.is_ascii_digit()) && at > 0 => { + ¤t[..at] + } + _ => current.as_str(), + }; + let named = format!("{root}.rb{n}"); + match parse_id(&named) { + Ok(epoch) => epoch, + Err(_) => { + let digest = digest_of_bytes(named.as_bytes()); + id(&format!("rb{n}-{}", &digest[..16])) + } + } +} + +impl Coordinator { + fn require_slots(&mut self, what: &str) -> Outcome<()> { + if self + .environment_capabilities + .iter() + .any(|c| c == fly_session_types::extensions::SLOTS_CAPABILITY) + { + return Ok(()); + } + Err(self.fail_now( + DomainError::new( + ErrorCode::Unsupported, + format!("the task asked for {what} and the world does not advertise gameboy-slots-v1"), + MutationCertainty::Applied, + ), + "boundary", + )) + } + + /// `Environment.SaveSlot` at the committed boundary `k`, under the current epoch. + async fn save_slot( + &mut self, + k: u64, + slot_id: &Id, + ) -> Outcome { + self.require_slots("a slot save")?; + let scope = self.scope(k); + let params = fly_session_types::extensions::SaveSlotParams { slot_id: slot_id.clone() }; + let worker = self.environment.clone(); + let reply = self + .call( + &worker, + fly_session_types::extensions::METHOD_SAVE_SLOT, + Some(scope.clone()), + object(params.to_json()), + &[], + &[], + ) + .await?; + let result: fly_session_types::extensions::SaveSlotResult = + reply.parse().map_err(|e| self.fail_now(e, "save-slot"))?; + if let Err(e) = result.validate_against_scope(&scope) { + return Err(self.fail_now(DomainError::invalid(e.0), "save-slot")); + } + if result.slot_id != *slot_id { + return Err(self.fail_now( + DomainError::before(ErrorCode::IdentityMismatch, "the world saved another slot"), + "save-slot", + )); + } + self.audit.push(format!("save-slot:{slot_id}@{k}")); + Ok(fly_session_types::trace::BoundaryAction { + kind: fly_session_types::trace::BoundaryActionKind::SaveSlot, + slot_id: slot_id.clone(), + state_digest: Some(result.state_digest), + }) + } + + /// The declared rollback policy at `Ready(e, k)` (`step-v1` section 6 amendment, steps 2 to + /// 5; `legacy-gameboy-v1` section 11): a new epoch, `Environment.RestoreSlot`, the task's + /// coordinator-local part, `Agent.Rollback` on every agent, then `Ready(e', k)`. Any failure + /// fails the epoch; nothing continues in `e` once one participant is in `e'`. + async fn apply_rollback( + &mut self, + k: u64, + request: &EpisodeRequest, + ) -> Outcome<(fly_session_types::trace::BoundaryAction, RollbackDetails)> { + let Some(policy) = self.rollback_policy.clone() else { + return Err(self.fail_now( + DomainError::new( + ErrorCode::Unsupported, + "the task asked for a rollback and this composition declares no rollback policy", + MutationCertainty::Applied, + ), + "rollback", + )); + }; + self.require_slots("a rollback")?; + let slot_id = match fly_session_types::gameboy::RollbackRequest::from_typed(&request.outcome) + { + Ok(outcome) => outcome.slot_id, + Err(e) => return Err(self.fail_now(DomainError::invalid(e.0), "rollback")), + }; + let slot_id = match parse_id(&slot_id) { + Ok(slot_id) => slot_id, + Err(e) => return Err(self.fail_now(DomainError::invalid(e), "rollback")), + }; + self.transition(Phase::RollingBack(k))?; + let prior = self.epoch.clone(); + self.rollbacks += 1; + let epoch = rollback_epoch(&prior, self.rollbacks); + let scope = scope_at(&self.session_id, &epoch, k); + + // Step 2: the world restores the slot at the same boundary under the new epoch. + let params = fly_session_types::extensions::RestoreSlotParams { + slot_id: slot_id.clone(), + prior_epoch: prior.clone(), + policy: policy.clone(), + }; + let worker = self.environment.clone(); + let want = self.wanted_media(); + let reply = self + .call( + &worker, + fly_session_types::extensions::METHOD_RESTORE_SLOT, + Some(scope.clone()), + object(params.to_json()), + &[], + &want, + ) + .await?; + let result: fly_session_types::extensions::RestoreSlotResult = + reply.parse().map_err(|e| self.fail_now(e, "restore-slot"))?; + if let Err(e) = result.validate_against_scope(&scope) { + return Err(self.fail_now(DomainError::invalid(e.0), "restore-slot")); + } + let descriptor = self.descriptor.clone().expect("bootstrapped"); + let restored = result.observation; + let world_time = self.observation.as_ref().map(|o| o.world_time); + if restored.boundary != k || Some(restored.world_time) != world_time { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + "a restored slot is not at the boundary and world time it was restored at", + ), + "restore-slot", + )); + } + if let Err(e) = restored.validate_against(&descriptor) { + return Err(self.fail_now( + DomainError::new(ErrorCode::BufferInvalid, e, MutationCertainty::Applied), + "restore-slot", + )); + } + if let Err(e) = media::check_required_views(&descriptor, &restored).and_then(|()| { + media::check_required_audio(&descriptor, &restored, media::ObservationOrigin::Installed) + }) { + return Err(self.fail_now(e, "restore-slot")); + } + let mut artifacts = reply.artifacts; + let held = self.take_inspection(&mut artifacts); + let (views, audio) = media::split_attachments(artifacts); + if !audio.is_empty() { + return Err(self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + "a restored slot carried an audio chunk; no interval was played", + MutationCertainty::Applied, + ), + "restore-slot", + )); + } + for view in &restored.sensory_views { + let name = media::view_attachment(&view.view_id); + match views.get(&name) { + Some(artifact) if artifact.reference() == &view.pixels => {} + _ => { + return Err(self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("the restored view {} arrived without a live owned handle", view.view_id), + MutationCertainty::Applied, + ), + "restore-slot", + )); + } + } + } + let inspection = self + .read_inspection(k, &restored.inspection, &held) + .await + .map_err(|e| self.fail_now(e, "restore-slot"))?; + self.audit.push(format!("restore-slot:{slot_id}@{k}:{epoch}")); + + // Step 3, coordinator-local: the task clears its transient observations, the executor + // cancels and observes the restored boundary, which gives the next contexts. + let evaluation = self + .task + .rollback(&scope, &inspection) + .map_err(|e| self.fail_now(e, "task-rollback"))?; + for agent_id in self.agent_ids() { + if !evaluation.next_contexts.contains_key(&agent_id) { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + format!("the task's rollback produced no context for {agent_id}"), + ), + "task-rollback", + )); + } + } + + // Step 4: every agent, with the restored view and its context. No tick. + let attachments: Vec<(String, flybus::Artifact)> = + views.iter().map(|(n, a)| (n.clone(), a.clone())).collect(); + let mut replies = Vec::new(); + for index in 0..self.agents.len() { + let agent_id = self.agents[index].agent_id.clone(); + let context = evaluation.next_contexts[&agent_id].clone(); + let params = fly_session_types::extensions::AgentRollbackParams { + agent_id: agent_id.clone(), + prior_epoch: prior.clone(), + policy: policy.clone(), + input: self.sensory_input(&restored, k), + decision_context: context.clone(), + }; + let worker = self.agents[index].worker.clone(); + let refs: Vec<(&str, &flybus::Artifact)> = + attachments.iter().map(|(n, a)| (n.as_str(), a)).collect(); + let reply = self + .call( + &worker, + fly_session_types::extensions::METHOD_AGENT_ROLLBACK, + Some(scope.clone()), + object(params.to_json()), + &refs, + &[], + ) + .await?; + let result: fly_session_types::extensions::AgentRollbackResult = + reply.parse().map_err(|e| self.fail_now(e, "agent-rollback"))?; + if let Err(e) = result.validate_against_scope(&scope) { + return Err(self.fail_now(DomainError::invalid(e.0), "agent-rollback")); + } + if result.agent_id != agent_id || result.decision_context_digest != context.digest() { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + "an agent rolled back with another identity or context", + ), + "agent-rollback", + )); + } + self.audit.push(format!("agent-rollback:{agent_id}@{k}:{epoch}")); + replies.push((agent_id, context, result)); + } + + // Step 5: every reply in hand. The session is at Ready(e', k). + let view_digests = if self.record_details { + let mut out = Vec::new(); + for view in &restored.sensory_views { + let name = media::view_attachment(&view.view_id); + if let Some(artifact) = views.get(&name) { + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("reading {name}: {}", e.message), + MutationCertainty::Applied, + ), + "details", + ) + })?; + out.push((view.view_id.clone(), digest_of_bytes(&bytes))); + } + } + out + } else { + Vec::new() + }; + self.epoch = epoch.clone(); + let positions = self.timelines.positions(); + self.timelines = match AudioTimelines::restored(&descriptor, &positions) { + Ok(timelines) => timelines, + Err(e) => return Err(self.fail_now(e, "rollback")), + }; + self.views = views; + self.audio.clear(); + self.inspection_held = held; + self.current_inspection = Some(inspection); + self.observation = Some(restored.clone()); + let mut agents = Vec::new(); + for (agent_id, context, result) in replies { + let slot = self + .agents + .iter_mut() + .find(|slot| slot.agent_id == agent_id) + .expect("configured"); + slot.context_digest = context.digest(); + slot.context = context; + slot.telemetry = Some(result.telemetry.clone()); + self.admissions.set_remaining(&agent_id, result.telemetry.stimulus_remaining_ms); + agents.push((agent_id, result)); + } + self.transition(Phase::Ready(k))?; + self.audit.push(format!("rolled-back:{slot_id}@{k}:{epoch}")); + Ok(( + fly_session_types::trace::BoundaryAction { + kind: fly_session_types::trace::BoundaryActionKind::Rollback, + slot_id: slot_id.clone(), + state_digest: None, + }, + RollbackDetails { epoch, observation: restored, view_digests, agents }, + )) + } +} + impl Coordinator { /// Phase C's verification: batch identity, boundary, cadence, schema and required views. #[allow(clippy::too_many_arguments)] @@ -2429,7 +3253,8 @@ impl Coordinator { outcomes: &mut BTreeMap, next_contexts: &mut BTreeMap, views: &BTreeMap, - ) -> Outcome> { + ) -> Outcome<(Vec<(Id, AgentCommitResult)>, Vec<(Id, String, Vec)>)> { + let mut extracted: Vec<(Id, String, Vec)> = Vec::new(); let scope = self.scope(k); let attachments: Vec<(String, flybus::Artifact)> = views.iter().map(|(n, a)| (n.clone(), a.clone())).collect(); @@ -2481,6 +3306,7 @@ impl Coordinator { params, attachments: attachments.clone(), request_id, + want: self.commit_attachments.clone(), }); } self.last_commit_requests = bodies @@ -2519,7 +3345,7 @@ impl Coordinator { params, job_attachments, request_id, - &[], + &self.commit_attachments.clone(), ) .await { @@ -2569,6 +3395,29 @@ impl Coordinator { if let Err(e) = result.telemetry.validate() { return Err(self.fail_now(DomainError::invalid(e), method)); } + for name in self.commit_attachments.clone() { + let Some(artifact) = reply.artifacts.get(&name) else { + return Err(self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("Agent.Commit carried no {name}"), + MutationCertainty::Applied, + ), + method, + )); + }; + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now( + DomainError::new( + ErrorCode::BufferInvalid, + format!("reading {name}: {}", e.message), + MutationCertainty::Applied, + ), + method, + ) + })?; + extracted.push((agent_id.clone(), name, bytes)); + } self.audit.push(format!("committed:{agent_id}@{k}")); self.stats.commits += 1; self.blame(None); @@ -2625,7 +3474,7 @@ impl Coordinator { } } commits.sort_by(|a, b| a.0.cmp(&b.0)); - Ok(commits) + Ok((commits, extracted)) } /// Records the `step-v1` section 8 trace for this transition. @@ -2645,6 +3494,7 @@ impl Coordinator { result: &StepResult, outcomes: &BTreeMap, event_ids: &[Id], + boundary_actions: &[fly_session_types::trace::BoundaryAction], ) { let mut agents = Vec::new(); let mut outcome_ids = Vec::new(); @@ -2695,8 +3545,9 @@ impl Coordinator { outcome_ids, event_ids: event_ids.to_vec(), published_boundary: k + 1, - // The synthetic composition takes no boundary actions (step-v1 section 8 amendment). - boundary_actions: Vec::new(), + // Saves first, each slot once, at most one rollback, last (step-v1 section 8 + // amendment). The synthetic composition takes none. + boundary_actions: boundary_actions.to_vec(), }; let operational = TraceOperational { // Wall time is for pacing, health and presentation only. @@ -3125,7 +3976,7 @@ impl Coordinator { /// The live composition's compatibility identities. pub fn compatibility(&self) -> Outcome { match &self.descriptor { - Some(descriptor) => Ok(crate::state::Compatibility::of(descriptor)), + Some(descriptor) => Ok(self.world_compatibility(descriptor)), None => Err(SessionFailure { error: DomainError::before( ErrorCode::InvalidPhase, @@ -3160,8 +4011,8 @@ impl Coordinator { &slot.agent_id, &slot.profile.digest, &graph.dataset_digest, - crate::agent::MODEL_VERSION, - crate::agent::PLASTICITY_VERSION, + &slot.model_version, + &slot.plasticity_version, slot.seed, &graph.index_digest, )) @@ -3393,8 +4244,8 @@ impl Coordinator { profile_digest: slot.profile.digest.clone(), dataset_digest: graph.dataset_digest, index_digest: graph.index_digest, - model_version: crate::agent::MODEL_VERSION.to_owned(), - plasticity_version: crate::agent::PLASTICITY_VERSION.to_owned(), + model_version: slot.model_version.clone(), + plasticity_version: slot.plasticity_version.clone(), seed: slot.seed, brain_ticks: slot.brain_ticks, remainder: slot.remainder, @@ -3693,8 +4544,13 @@ impl Coordinator { /// A replacement is the only way a fenced participant comes back: `step-v1` section 7's /// incarnation row says every live participant of a failed epoch belongs to an invalid /// one, so the reference is exchanged deliberately here and never repaired in place. + /// + /// A session that bootstrapped and has taken no transition may also replace a participant: + /// that is how a checkpoint of another format is installed as its start + /// ([`Coordinator::import`]) into a world that stages only on a fresh replacement. pub fn replace_participant(&mut self, worker_id: &Id, worker: WorkerRef) -> Outcome<()> { - if !self.fenced { + let unstarted = self.phases.phase() == Phase::Ready(0) && self.stats.advances == 0; + if !self.fenced && !unstarted { return Err(self.fail_now( DomainError::before( ErrorCode::InvalidPhase, @@ -3813,13 +4669,253 @@ impl Coordinator { } let boundary = manifest.source_scope.step; self.transition(Phase::Restoring(boundary))?; - let outcome = self.restore_group(&envelope, &manifest, new_epoch, boundary).await; + let outcome = self.restore_group(&envelope.payloads, &manifest, new_epoch, boundary).await; match outcome { Ok(report) => Ok(report), Err(e) => Err(e), } } + /// The scope an imported checkpoint's payloads record as their source: this session, its + /// current epoch, the boundary the checkpoint is at. + pub fn import_scope(&self, boundary: u64) -> Scope { + self.scope(boundary) + } + + /// One participant's `State.Capture` payload at the committed boundary, outside any group + /// capture: the template an importer rewrites a foreign agent state into. + pub async fn capture_participant(&mut self, worker_id: &Id) -> Outcome> { + let Some(boundary) = self.phases.phase().committed_boundary() else { + return Err(self.fail_now( + DomainError::before(ErrorCode::InvalidPhase, "a capture needs a committed boundary"), + "capture", + )); + }; + let worker = if self.environment.worker_id == *worker_id { + self.environment.clone() + } else { + match self.agents.iter().find(|slot| slot.agent_id == *worker_id) { + Some(slot) => slot.worker.clone(), + None => { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + format!("{worker_id} is not a participant"), + ), + "capture", + )); + } + } + }; + let params = object( + CaptureParams { checkpoint_id: id(&format!("template-{worker_id}")) }.to_json(), + ); + let want = vec![crate::state::PAYLOAD_ATTACHMENT.to_owned()]; + let reply = self + .call(&worker, "State.Capture", Some(self.scope(boundary)), params, &[], &want) + .await?; + let artifact = reply.artifacts.get(crate::state::PAYLOAD_ATTACHMENT).cloned(); + let Some(artifact) = artifact else { + return Err(self.fail_now( + DomainError::before(ErrorCode::BufferInvalid, "State.Capture carried no payload"), + "capture", + )); + }; + let bytes = artifact.read_all().await.map_err(|e| { + self.fail_now( + DomainError::before(ErrorCode::BufferInvalid, e.message.clone()), + "capture", + ) + })?; + self.acknowledge_replies(&worker, &[reply.request_id.clone()]).await?; + Ok(bytes) + } + + /// Installs a checkpoint of another format as this session's start (TASK-01: the legacy + /// composition's FLYSIM01 import). + /// + /// Only a session that bootstrapped and has taken no transition may import, and the install + /// is the ordinary group restore of `state-media-v1` section 6 -- stage every participant, + /// validate the coordinator's own state, activate, install, `Paused(k)` -- over payloads the + /// importer assembled in each participant's own capture format. The coordinator's own + /// payloads (executor state, prior inspection, the admission record) are written here, from + /// the live composition, exactly as a capture writes them. Nothing a participant stages is + /// trusted: each validates its payload as it would one of its own captures. + pub async fn import(&mut self, spec: ImportSpec, new_epoch: &Id) -> Outcome { + if self.fenced || self.phases.phase() != Phase::Ready(0) || self.stats.advances != 0 { + return Err(self.fail_now( + DomainError::before( + ErrorCode::InvalidPhase, + "a checkpoint is imported as the start of a session that has taken no transition", + ), + "import", + )); + } + if *new_epoch == self.epoch { + return Err(self.fail_now( + DomainError::before(ErrorCode::StaleEpoch, "an import installs a fresh epoch"), + "import", + )); + } + let descriptor = self.descriptor.clone().expect("bootstrapped"); + let boundary = spec.boundary; + let world_time = RationalNs::reduced( + u128::from(descriptor.step_duration.numerator) * u128::from(boundary), + u128::from(descriptor.step_duration.denominator), + ) + .map_err(|e| DomainError::invalid(e.0)); + let world_time = match world_time { + Ok(time) => time, + Err(e) => return Err(self.fail_now(e, "import")), + }; + let recorded: Vec = spec.agents.iter().map(|a| a.agent_id.clone()).collect(); + if recorded != self.agent_ids() { + return Err(self.fail_now( + DomainError::before( + ErrorCode::IdentityMismatch, + "the import's agents are not this composition's", + ), + "import", + )); + } + let compatibility = self.compatibility()?; + let canonical = |value: &Value| -> DomainResult> { + canonicalize(value) + .map(String::into_bytes) + .map_err(|e| DomainError::invalid(e.0)) + }; + let mut payloads: Vec<(String, Vec)> = Vec::new(); + payloads.push((crate::state::WORLD_PAYLOAD.to_owned(), spec.world_payload)); + let mut agent_rows = Vec::new(); + for imported in &spec.agents { + let slot = self.agent(&imported.agent_id).expect("checked"); + let Some(graph) = slot.graph.clone() else { + return Err(self.fail_now( + DomainError::before(ErrorCode::InvalidPhase, "an agent attested no graph"), + "import", + )); + }; + let name = crate::state::agent_payload(&imported.agent_id); + agent_rows.push(crate::state::AgentEntry { + agent_id: imported.agent_id.clone(), + profile_digest: slot.profile.digest.clone(), + dataset_digest: graph.dataset_digest, + index_digest: graph.index_digest, + model_version: slot.model_version.clone(), + plasticity_version: slot.plasticity_version.clone(), + seed: slot.seed, + brain_ticks: imported.brain_ticks, + remainder: imported.remainder, + payload: name.clone(), + }); + payloads.push((name, imported.payload.clone())); + } + let mut own = |name: &str, value: &Value| -> DomainResult<()> { + payloads.push((name.to_owned(), canonical(value)?)); + Ok(()) + }; + let mut executor_rows = Vec::new(); + let mut failure = None; + if let Err(e) = own(crate::state::TASK_LEDGER_PAYLOAD, &spec.task_ledger.to_json()) { + failure = Some(e); + } + let prior = self.observation.as_ref().map(|o| o.inspection.to_json()).expect("bootstrapped"); + if let Err(e) = own(crate::state::PRIOR_INSPECTION_PAYLOAD, &prior) { + failure = failure.or(Some(e)); + } + for agent_id in self.agent_ids() { + let name = crate::state::executor_payload(&agent_id); + match self.executors.get(&agent_id).map(|e| e.capture()) { + Some(Ok(state)) => { + if let Err(e) = own(&name, &state.to_json()) { + failure = failure.or(Some(e)); + } + } + Some(Err(e)) => failure = failure.or(Some(e)), + None => { + failure = failure.or(Some(DomainError::before( + ErrorCode::IdentityMismatch, + format!("{agent_id} has no configured action executor"), + ))) + } + } + executor_rows.push((agent_id, name)); + } + let record = json!({ + "payloadVersion": 1, + "kind": "coordinator", + "committedStep": boundary.to_string(), + "admission": {"audienceInput": "none-configured", "admitted": Value::Array(Vec::new())}, + "eventWatermarks": {"lastSourceStep": "0", "issued": "0"}, + "audioPositions": Value::Object( + spec.audio_positions + .iter() + .map(|(stream, sample)| (stream.clone(), Value::String(sample.to_string()))) + .collect(), + ), + "agents": Value::Array( + spec.agents + .iter() + .map(|imported| { + let slot = self.agent(&imported.agent_id).expect("checked"); + json!({ + "agentId": imported.agent_id.as_str(), + "portId": slot.port_id.as_str(), + "profile": slot.profile.to_json(), + "seed": slot.seed, + "workerThreads": slot.worker_threads.to_string(), + "committedStep": boundary.to_string(), + "brainTicks": imported.brain_ticks.to_string(), + "remainder": imported.remainder.to_json(), + "context": imported.context.to_json(), + }) + }) + .collect(), + ), + }); + if let Err(e) = own(crate::state::ADMISSION_PAYLOAD, &record) { + failure = failure.or(Some(e)); + } + if let Some(e) = failure { + return Err(self.fail_now(e, "import")); + } + let manifest = crate::state::CheckpointManifest { + checkpoint_id: spec.checkpoint_id.clone(), + source_scope: self.scope(boundary), + episode_id: self.episode_id.clone(), + world_time, + scheduler_id: "lockstep-v1".to_owned(), + composition_digest: self.composition_digest(), + port_map: self + .agents + .iter() + .map(|slot| (slot.port_id.clone(), slot.agent_id.clone())) + .collect(), + compatibility, + agents: agent_rows, + coordinator: crate::state::CoordinatorEntry { + task_ledger: crate::state::TASK_LEDGER_PAYLOAD.to_owned(), + prior_inspection: crate::state::PRIOR_INSPECTION_PAYLOAD.to_owned(), + executor_state: executor_rows, + admission_state: crate::state::ADMISSION_PAYLOAD.to_owned(), + event_watermarks: crate::state::EventWatermarks { last_source_step: 0, issued: 0 }, + }, + environment: crate::state::EnvironmentEntry { + worker_id: self.environment.worker_id.clone(), + payload: crate::state::WORLD_PAYLOAD.to_owned(), + }, + helper_state: Vec::new(), + payloads: payloads + .iter() + .map(|(name, bytes)| (name.clone(), bytes.len() as u64, digest_of_bytes(bytes))) + .collect(), + }; + self.transition(Phase::Restoring(boundary))?; + let report = self.restore_group(&payloads, &manifest, new_epoch, boundary).await?; + self.audit.push(format!("imported:{}@{boundary}", spec.checkpoint_id)); + Ok(report) + } + /// Marks every participant of an abandoned group install as one that must be replaced. /// /// A participant that staged holds a replacement state nothing installed; one that @@ -3866,7 +4962,7 @@ impl Coordinator { )); } let live = match &self.descriptor { - Some(descriptor) => crate::state::Compatibility::of(descriptor), + Some(descriptor) => self.world_compatibility(descriptor), None => { return Err(DomainError::before( ErrorCode::InvalidPhase, @@ -3921,7 +5017,7 @@ impl Coordinator { #[allow(clippy::too_many_lines)] async fn restore_group( &mut self, - envelope: &fly_session_types::checkpoint::Envelope, + envelope_payloads: &[(String, Vec)], manifest: &crate::state::CheckpointManifest, new_epoch: &Id, boundary: u64, @@ -3930,7 +5026,7 @@ impl Coordinator { // Step 3: import the payloads as *new* artifacts. Nothing the fence dropped is asked // to come back, and a router that restarted has none of the old roots anyway. let mut imported: BTreeMap = BTreeMap::new(); - for (name, bytes) in &envelope.payloads { + for (name, bytes) in envelope_payloads { let digest = digest_of_bytes(bytes); let artifact = match crate::state::seal_payload(&self.bus, bytes, &digest).await { Ok(artifact) => artifact, @@ -4043,8 +5139,7 @@ impl Coordinator { // coordinator** state validates". The coordinator's own staged ledgers are checked // here, before a single token is activated, so a checkpoint whose task ledger or // executor state is unreadable installs nothing anywhere. - let payloads: BTreeMap> = envelope - .payloads + let payloads: BTreeMap> = envelope_payloads .iter() .map(|(name, bytes)| (name.clone(), bytes.clone())) .collect(); @@ -4078,10 +5173,11 @@ impl Coordinator { let mut activated: Vec = Vec::new(); let mut restored_observation: Option<(WorldObservation, BTreeMap)> = None; + let mut restored_inspection: BTreeMap = BTreeMap::new(); for (who, worker, token) in &staged { let params = ActivateRestoreParams { restore_token: token.clone() }; let want = if *who == self.environment.worker_id { - self.media_names.clone() + self.wanted_media() } else { Vec::new() }; @@ -4129,7 +5225,9 @@ impl Coordinator { )); } if let Some(observation) = result.observation { - let (views, audio) = media::split_attachments(reply.artifacts); + let mut artifacts = reply.artifacts; + restored_inspection = self.take_inspection(&mut artifacts); + let (views, audio) = media::split_attachments(artifacts); if !audio.is_empty() { self.taint_group(&staged); return Err(self.fail_now( @@ -4172,6 +5270,69 @@ impl Coordinator { self.taint_group(&staged); return Err(self.fail_now(e, "restore")); } + // The restored boundary's inspection, and the task's own look at it: a task whose + // executor state is transient (`legacy-transient-reset`) re-observes the restored world + // here, and the contexts it derives must be the ones the checkpoint recorded -- the + // agents hold those, and a Prepare under another would be refused. + let restored_value = self + .observation + .as_ref() + .map(|o| o.inspection.clone()) + .expect("installed above"); + let inspection = match self.read_inspection(boundary, &restored_value, &restored_inspection).await + { + Ok(inspection) => inspection, + Err(e) => { + self.taint_group(&staged); + return Err(self.fail_now(e, "restore")); + } + }; + let clock = match self.agents.first() { + Some(slot) => RationalNs::reduced( + u128::from(slot.tick_duration.numerator) * u128::from(slot.brain_ticks), + u128::from(slot.tick_duration.denominator), + ) + .unwrap_or(RationalNs::ZERO), + None => RationalNs::ZERO, + }; + let restored_scope = scope_at(&self.session_id, new_epoch, boundary); + match self.task.restored(&restored_scope, &inspection, &clock) { + Ok(Some(contexts)) => { + let differing = self + .agents + .iter() + .find(|slot| { + contexts.get(&slot.agent_id).map(TypedValue::digest) + != Some(slot.context_digest.clone()) + }) + .map(|slot| slot.agent_id.clone()); + if let Some(agent_id) = differing { + { + self.taint_group(&staged); + return Err(self.fail_now( + DomainError::before( + ErrorCode::IncompatibleState, + format!( + "the restored world gives {} another decision context than the \ + checkpoint recorded", + agent_id + ), + ), + "restore", + )); + } + } + } + Ok(None) => {} + Err(e) => { + self.taint_group(&staged); + return Err(self.fail_now(e, "restore")); + } + } + self.inspection_held = restored_inspection; + self.current_inspection = Some(inspection); + // The pulse is unknown until the new epoch's first commit (`legacy-gameboy-v1` 15). + self.admissions.forget_remaining(); // Step 5: Paused(k), and only now is the fence lifted. self.epoch = new_epoch.clone(); diff --git a/services/flysim/crates/fly-session/src/phase.rs b/services/flysim/crates/fly-session/src/phase.rs index f528112..235576a 100644 --- a/services/flysim/crates/fly-session/src/phase.rs +++ b/services/flysim/crates/fly-session/src/phase.rs @@ -9,6 +9,8 @@ //! Ready(k) / Paused(k) -> Capturing(k) -> same boundary //! any unresolved partial failure -> Failed -> Restoring(new epoch) -> Paused(k) //! terminal episode -> Paused(k) -> Resetting(new epoch) -> Ready(0) +//! declared rollback: Ready(e, k) -> RollingBack(e', k) -> Ready(e', k) +//! checkpoint as the start: Ready(0), no transition taken -> Restoring(k) -> Paused(k) //! ``` //! //! A transition the table does not list is a bug, not a recoverable condition, so it returns @@ -34,6 +36,9 @@ pub enum Phase { Restoring(u64), /// `Resetting(k)`: leaving boundary `k` for a new epoch and episode at step 0. Resetting(u64), + /// A declared rollback policy running at a committed boundary (`step-v1` section 2 + /// amendment of 2026-09-23): same boundary, new epoch, no capture. + RollingBack(u64), } impl Phase { @@ -50,6 +55,7 @@ impl Phase { Phase::Failed => "Failed".to_owned(), Phase::Restoring(k) => format!("Restoring({k})"), Phase::Resetting(k) => format!("Resetting({k})"), + Phase::RollingBack(k) => format!("RollingBack({k})"), } } @@ -115,6 +121,14 @@ impl PhaseMachine { (Restoring(k), Paused(j)) => k == j, (Paused(k), Resetting(j)) => k == j, (Resetting(_), Ready(0)) => true, + // `step-v1` section 2, amendment of 2026-09-23: `Ready(e, k) -> RollingBack(e', k) + // -> Ready(e', k)`. The epoch changes, which is the coordinator's; the boundary + // does not. + (Ready(k), RollingBack(j)) | (RollingBack(k), Ready(j)) => k == j, + // A session that bootstrapped and has taken no transition may install a checkpoint + // as its start: the legacy composition's FLYSIM01 import (TASK-01). The install is + // the group restore of `state-media-v1` section 6 and ends `Paused(k)` like one. + (Ready(0), Restoring(_)) => true, _ => false, } } @@ -150,6 +164,21 @@ impl PhaseMachine { mod tests { use super::*; + #[test] + fn a_rollback_keeps_its_boundary_and_an_import_starts_from_an_unstepped_zero() { + let mut m = PhaseMachine::new(); + m.to(Phase::Ready(0)).unwrap(); + m.to(Phase::Restoring(40)).unwrap(); + m.to(Phase::Paused(40)).unwrap(); + m.to(Phase::Ready(40)).unwrap(); + assert!(m.to(Phase::RollingBack(41)).is_err(), "a rollback keeps the boundary"); + m.to(Phase::RollingBack(40)).unwrap(); + assert!(m.to(Phase::Capturing(40)).is_err(), "no capture inside a rollback"); + assert!(m.to(Phase::Preparing(40)).is_err(), "no Prepare before every reply"); + m.to(Phase::Ready(40)).unwrap(); + assert!(m.to(Phase::Restoring(3)).is_err(), "only boundary 0 may take a start"); + } + #[test] fn the_happy_path_walks_the_section_2_diagram() { let mut m = PhaseMachine::new(); diff --git a/services/flysim/crates/fly-session/src/task.rs b/services/flysim/crates/fly-session/src/task.rs index bbb2bf4..81d5e4b 100644 --- a/services/flysim/crates/fly-session/src/task.rs +++ b/services/flysim/crates/fly-session/src/task.rs @@ -7,6 +7,7 @@ //! writes a controller or neural state directly. use std::collections::BTreeMap; +use std::sync::Arc; use serde_json::{Map, Value, json}; @@ -53,6 +54,48 @@ pub fn controller_schema_ref() -> SchemaRef { synthetic_schema("arena.controller.v1", 1) } +/// One boundary's inspection as the task and the executor read it: the observation's typed +/// `inspection` value plus the bytes of the attachments the task declared +/// ([`Task::inspection_attachments`]). +/// +/// An artifact-backed inspection (`gameboy-memory-inspection-v1`: a 64 KiB image per boundary) +/// names its bytes by `ArtifactRef`; the coordinator holds the artifact until the transition +/// that reads it has been evaluated (`step-v1` section 3, Phase C amendment) and hands the task +/// the bytes, so neither the task nor the executor ever reads a live world. The synthetic +/// composition declares no attachment, and its inspection derefs to the typed value it always +/// was. +#[derive(Clone, Debug)] +pub struct Inspection { + /// The boundary the observation belongs to. + pub boundary: u64, + pub value: TypedValue, + /// Attachment name to bytes, for the names the task declared. + pub attachments: BTreeMap>>, +} + +impl Inspection { + /// An inspection with no attachment: the synthetic composition's. + pub fn plain(boundary: u64, value: TypedValue) -> Inspection { + Inspection { boundary, value, attachments: BTreeMap::new() } + } +} + +impl std::ops::Deref for Inspection { + type Target = TypedValue; + + fn deref(&self) -> &TypedValue { + &self.value + } +} + +/// What a task's part of a rollback produced (`step-v1` section 6 amendment, step 3): the next +/// decision contexts for the restored boundary, and any events it reports. +#[derive(Clone, Debug)] +pub struct RollbackEvaluation { + pub next_contexts: BTreeMap, + pub events: Vec, +} + /// What `Task.bootstrap` produced. #[derive(Clone, Debug)] pub struct Bootstrap { @@ -70,16 +113,27 @@ pub struct Evaluation { pub progress: TypedValue, pub events: Vec, pub episode: Option, + /// Slot saves the transition asks for at the boundary it reached, applied by the coordinator + /// after every Commit and before any capture or rollback there (`step-v1` section 3, Phase C + /// amendment; environment capability `gameboy-slots-v1`). Empty in every composition that + /// declares no slots. + pub slot_saves: Vec, } /// A checkpointable task ledger and the two evaluation entry points. pub trait Task: Send { fn schema(&self) -> SchemaRef; + /// The inspection attachments this task and its executor read, which the coordinator asks + /// the environment for, holds and hands over as bytes. None by default. + fn inspection_attachments(&self) -> Vec { + Vec::new() + } + /// Called once, at boundary 0, before any agent is initialized. fn bootstrap( &mut self, - initial_inspection: &TypedValue, + initial_inspection: &Inspection, bindings: &[PortBinding], ) -> DomainResult; @@ -87,11 +141,40 @@ pub trait Task: Send { fn evaluate_transition( &mut self, scope: &Scope, - old_inspection: &TypedValue, - new_inspection: &TypedValue, + old_inspection: &Inspection, + new_inspection: &Inspection, applied_controls: &[PortControl], ) -> DomainResult; + /// Step 3 of a declared rollback policy, coordinator-local (`step-v1` section 6 amendment): + /// the task clears its transient observations and the executor cancels any running action + /// and observes the restored boundary, which yields the next decision contexts. `scope` is + /// the new epoch at the restored boundary. A task that declares no rollback policy refuses. + fn rollback( + &mut self, + _scope: &Scope, + _restored: &Inspection, + ) -> DomainResult { + Err(DomainError::before( + ErrorCode::Unsupported, + "this task declares no rollback policy", + )) + } + + /// After a group restore installed this task's ledger: the restored boundary's inspection + /// and the agents' restored brain clock. A task whose executor state is transient + /// (`restore: legacy-transient-reset`) re-observes the world here and returns the decision + /// contexts it would hand the agents, which the coordinator holds against the ones the + /// checkpoint recorded. `None` (the default) means the recorded contexts stand unchecked. + fn restored( + &mut self, + _scope: &Scope, + _restored: &Inspection, + _clock: &RationalNs, + ) -> DomainResult>> { + Ok(None) + } + fn progress(&self) -> TypedValue; /// How many times `evaluate_transition` has run. A transition must evaluate once. @@ -127,7 +210,7 @@ pub trait ActionExecutor: Send { &mut self, scope: &Scope, decision: &TypedValue, - current_game_state: &TypedValue, + current_game_state: &Inspection, progress: &TypedValue, clock: &RationalNs, ) -> DomainResult<(ControllerIntent, Vec)>; @@ -151,7 +234,7 @@ impl ActionExecutor for IdentityExecutor { &mut self, _scope: &Scope, decision: &TypedValue, - _current_game_state: &TypedValue, + _current_game_state: &Inspection, _progress: &TypedValue, _clock: &RationalNs, ) -> DomainResult<(ControllerIntent, Vec)> { @@ -294,7 +377,7 @@ impl Task for CounterTask { fn bootstrap( &mut self, - initial_inspection: &TypedValue, + initial_inspection: &Inspection, bindings: &[PortBinding], ) -> DomainResult { if initial_inspection.schema != inspection_schema() { @@ -329,8 +412,8 @@ impl Task for CounterTask { fn evaluate_transition( &mut self, scope: &Scope, - old_inspection: &TypedValue, - new_inspection: &TypedValue, + old_inspection: &Inspection, + new_inspection: &Inspection, applied_controls: &[PortControl], ) -> DomainResult { let old = old_inspection.integer("counter").map_err(DomainError::invalid)?; @@ -445,6 +528,7 @@ impl Task for CounterTask { progress: self.progress_value(), events, episode, + slot_saves: Vec::new(), }) } diff --git a/services/flysim/crates/fly-session/tests/session.rs b/services/flysim/crates/fly-session/tests/session.rs index fcce346..1c40fe5 100644 --- a/services/flysim/crates/fly-session/tests/session.rs +++ b/services/flysim/crates/fly-session/tests/session.rs @@ -25,7 +25,7 @@ both_transports!( the_committed_snapshot_names_the_boundary_that_just_ended, a_terminal_episode_pauses_at_its_own_boundary, a_rollback_request_without_a_declared_policy_fails_the_epoch, - a_declared_rollback_policy_holds_the_session_at_its_boundary, + a_declared_rollback_policy_needs_participants_that_apply_it, status_answers_with_the_committed_boundary, a_worker_refuses_a_second_initialize, a_single_agent_composition_runs_the_same_transaction, @@ -329,9 +329,13 @@ async fn a_rollback_request_without_a_declared_policy_fails_the_epoch(via: Via) f.shutdown().await; } -/// With `legacy-ratchet-rollback-v1` declared the request is accepted: the transition commits and -/// the session holds at its boundary with the request recorded, for the policy to run. -async fn a_declared_rollback_policy_holds_the_session_at_its_boundary(via: Via) { +/// With `legacy-ratchet-rollback-v1` declared the coordinator runs the policy itself +/// (`step-v1` section 6 amendment; TASK-01), so a composition may only declare it over +/// participants that can apply it: agents that answer `Agent.Rollback` and a world with +/// `gameboy-slots-v1`. The synthetic agents answer neither, so the session never starts -- +/// rather than accepting a rollback request it cannot apply. (Until TASK-01 the declared request +/// paused the session at its boundary.) +async fn a_declared_rollback_policy_needs_participants_that_apply_it(via: Via) { let config = HarnessConfig { terminal: fly_session::task::Terminal::RollbackAfterTransitions(2), ..HarnessConfig::default() @@ -342,13 +346,11 @@ async fn a_declared_rollback_policy_holds_the_session_at_its_boundary(via: Via) .declare_rollback_policy("legacy-ratchet-rollback-v1") .unwrap(); assert!(f.harness.coordinator.declare_rollback_policy("reset-everything").is_err()); - within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap(); - let reports = within("run", f.harness.coordinator.run(4)).await.unwrap(); - assert_eq!(reports.len(), 2); - assert!(!f.harness.coordinator.is_fenced()); - assert_eq!(f.harness.coordinator.phase(), Phase::Paused(2)); - let request = f.harness.coordinator.episode_request().unwrap(); - assert_eq!(request.kind, EpisodeRequestKind::Rollback); + let err = within("bootstrap", f.harness.coordinator.bootstrap()).await.unwrap_err(); + assert_eq!(err.error.code, ErrorCode::Unsupported, "{}", err.error.message); + assert!(err.error.message.contains("Agent.Rollback"), "{}", err.error.message); + assert!(f.harness.coordinator.is_fenced()); + assert!(f.harness.coordinator.episode_request().is_none()); f.shutdown().await; }