diff --git a/services/flysim/crates/fly-legacy-session/src/composition.rs b/services/flysim/crates/fly-legacy-session/src/composition.rs index b93407b..9e7f94f 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; @@ -96,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, @@ -433,6 +435,7 @@ impl LegacySession { checkpointer: None, saves: 0, pending_saves: Vec::new(), + pending_captures: Vec::new(), last_event_id: 0, }) } @@ -575,24 +578,54 @@ 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`, @@ -630,7 +663,17 @@ impl LegacySession { .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. 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); + } if self.checkpointer.is_some() { let rank = self.task.rank(); let ms = self.task.brain_ms(); @@ -640,13 +683,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 @@ -661,13 +698,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 @@ -675,13 +706,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(( @@ -705,6 +730,9 @@ impl LegacySession { if self.checkpointer.is_none() { return Ok(None); } + for ticket in self.finish_captures().await? { + self.pending_saves.push(ticket); + } let report = self.save(SaveKind::Durable).await?; self.completed_saves(true).await?; if let Some(checkpointer) = self.checkpointer.as_mut() { diff --git a/services/flysim/crates/fly-session/src/coordinator.rs b/services/flysim/crates/fly-session/src/coordinator.rs index 9ace7ce..01d2742 100644 --- a/services/flysim/crates/fly-session/src/coordinator.rs +++ b/services/flysim/crates/fly-session/src/coordinator.rs @@ -709,6 +709,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 { @@ -727,11 +740,53 @@ 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"), @@ -746,7 +801,6 @@ impl Coordinator { 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)) @@ -1624,6 +1678,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)] diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index 2f4f570..b6fbd37 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -312,6 +312,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) @@ -1280,7 +1317,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"); @@ -1288,23 +1326,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 { @@ -1330,42 +1364,50 @@ impl LegacyAgentWorker { )); } let params: CaptureParams = ctx.params()?; - let previous = self.status.state(); - self.status.set_state(WorkerState::Capturing); - let span = crate::profile::span("agent.capture.encode"); - let bytes = self.payload(¶ms.checkpoint_id, &scope, k); - drop(span); - 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 span = crate::profile::span("agent.capture.digest"); - let digest = digest_of_bytes(&bytes); - drop(span); - let span = crate::profile::span("agent.capture.seal"); - let artifact = crate::state::seal_payload(ctx.client, &bytes, &digest).await; - drop(span); - 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 4451900..e274025 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);