N5: captures off the loop; wanted and cached artifacts held concurrently
- worker: a handler may finish its reply outside the endpoint's lock (HandlerReply::deferred); admitted mutations take the lock in arrival order (LockOrder), so a request sent before another is handled first; a reply's cache holds are taken concurrently. - legacy agent: State.Capture copies the state under the lock and encodes, digests and seals it off the lock, so the next Prepare ticks while the payload is written. - rpc: send/finish split (SentCall); the caller's holds on wanted attachments are taken concurrently. - coordinator: begin_capture sends every State.Capture and returns; finish_capture collects them. LegacySession begins a boundary's saves and collects them after the next transition, then queues them to the writer thread.
This commit is contained in:
parent
1bfaf923b2
commit
d35eda399b
5 changed files with 408 additions and 120 deletions
|
|
@ -27,7 +27,7 @@ use flysim::snapshot::MacroMode;
|
||||||
use crate::task::{PokeredConfig, PokeredTask, TaskRecord};
|
use crate::task::{PokeredConfig, PokeredTask, TaskRecord};
|
||||||
use fly_session::legacy_checkpoint::{
|
use fly_session::legacy_checkpoint::{
|
||||||
AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind,
|
AgentImport, CheckpointerConfig, LegacyCapture, LegacyCheckpointer, RankChange, SaveKind,
|
||||||
SaveReport, SaveTicket, now_wall_ms,
|
SaveReport, SaveTicket, TaskHalf, now_wall_ms,
|
||||||
};
|
};
|
||||||
use flysim::store::Checkpoint;
|
use flysim::store::Checkpoint;
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
@ -96,6 +96,8 @@ pub struct LegacySession {
|
||||||
saves: u64,
|
saves: u64,
|
||||||
/// Saves on the writer thread whose outcome has not been collected.
|
/// Saves on the writer thread whose outcome has not been collected.
|
||||||
pending_saves: Vec<SaveTicket>,
|
pending_saves: Vec<SaveTicket>,
|
||||||
|
/// 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
|
/// The feed event log's watermark the saves record: the restored file's, carried over (the
|
||||||
/// session runtime has no feed event log of its own before EDGE-01).
|
/// session runtime has no feed event log of its own before EDGE-01).
|
||||||
last_event_id: u64,
|
last_event_id: u64,
|
||||||
|
|
@ -433,6 +435,7 @@ impl LegacySession {
|
||||||
checkpointer: None,
|
checkpointer: None,
|
||||||
saves: 0,
|
saves: 0,
|
||||||
pending_saves: Vec::new(),
|
pending_saves: Vec::new(),
|
||||||
|
pending_captures: Vec::new(),
|
||||||
last_event_id: 0,
|
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
|
/// 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`].
|
/// outcome is collected by [`LegacySession::completed_saves`].
|
||||||
pub async fn queue_save(&mut self, kind: SaveKind) -> Result<SaveTicket, String> {
|
pub async fn queue_save(&mut self, kind: SaveKind) -> Result<SaveTicket, String> {
|
||||||
|
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;
|
self.saves += 1;
|
||||||
let (boundary, world, agents) = self
|
let capture = self
|
||||||
.coordinator
|
.coordinator
|
||||||
.capture_payloads(&parse_id(&format!("legacy-save-{}", self.saves))?)
|
.begin_capture(&parse_id(&format!("legacy-save-{}", self.saves))?)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?;
|
.map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?;
|
||||||
let [(_, agent)] = <[(Id, Vec<u8>); 1]>::try_from(agents)
|
|
||||||
.map_err(|_| "the legacy composition has exactly one agent".to_owned())?;
|
|
||||||
let (task, _slot_filled) = self.task.task_half();
|
let (task, _slot_filled) = self.task.task_half();
|
||||||
let capture = LegacyCapture {
|
self.pending_captures.push((capture, kind, task));
|
||||||
boundary,
|
Ok(())
|
||||||
agent_payload: agent,
|
}
|
||||||
world_payload: world,
|
|
||||||
task,
|
/// Collects every begun capture, in order, and queues it to the checkpointer's writer.
|
||||||
};
|
pub async fn finish_captures(&mut self) -> Result<Vec<SaveTicket>, String> {
|
||||||
let last_event_id = self.last_event_id;
|
let mut tickets = Vec::new();
|
||||||
let checkpointer = self.checkpointer.as_mut().ok_or("no store is attached")?;
|
for (capture, kind, task) in std::mem::take(&mut self.pending_captures) {
|
||||||
checkpointer.save(kind, capture, last_event_id, now_wall_ms())
|
let (boundary, world, agents) = self
|
||||||
|
.coordinator
|
||||||
|
.finish_capture(capture)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("capture ({}): {}", e.detail, e.error.message))?;
|
||||||
|
let [(_, agent)] = <[(Id, Vec<u8>); 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`,
|
/// The saves queued so far that have committed (or failed), without waiting; with `wait`,
|
||||||
|
|
@ -630,7 +663,17 @@ impl LegacySession {
|
||||||
.step()
|
.step()
|
||||||
.await
|
.await
|
||||||
.map_err(|e| format!("step ({} at {}): {}", e.detail, e.phase, e.error.message))?;
|
.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();
|
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() {
|
if self.checkpointer.is_some() {
|
||||||
let rank = self.task.rank();
|
let rank = self.task.rank();
|
||||||
let ms = self.task.brain_ms();
|
let ms = self.task.brain_ms();
|
||||||
|
|
@ -640,13 +683,7 @@ impl LegacySession {
|
||||||
.expect("attached")
|
.expect("attached")
|
||||||
.observe_rank(rank, ms);
|
.observe_rank(rank, ms);
|
||||||
if let Some(RankChange::Climbed(rank)) = change {
|
if let Some(RankChange::Climbed(rank)) = change {
|
||||||
let ticket = self.queue_save(SaveKind::Milestone(rank)).await?;
|
self.begin_save(SaveKind::Milestone(rank)).await?;
|
||||||
saves.push(SaveQueued {
|
|
||||||
generation: ticket.generation,
|
|
||||||
durable: ticket.durable,
|
|
||||||
archive_rank: ticket.archive_rank,
|
|
||||||
});
|
|
||||||
self.pending_saves.push(ticket);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let rolled_back = self
|
let rolled_back = self
|
||||||
|
|
@ -661,13 +698,7 @@ impl LegacySession {
|
||||||
})?;
|
})?;
|
||||||
if self.checkpointer.is_some() {
|
if self.checkpointer.is_some() {
|
||||||
if rolled_back {
|
if rolled_back {
|
||||||
let ticket = self.queue_save(SaveKind::Durable).await?;
|
self.begin_save(SaveKind::Durable).await?;
|
||||||
saves.push(SaveQueued {
|
|
||||||
generation: ticket.generation,
|
|
||||||
durable: ticket.durable,
|
|
||||||
archive_rank: ticket.archive_rank,
|
|
||||||
});
|
|
||||||
self.pending_saves.push(ticket);
|
|
||||||
}
|
}
|
||||||
let due = self
|
let due = self
|
||||||
.checkpointer
|
.checkpointer
|
||||||
|
|
@ -675,13 +706,7 @@ impl LegacySession {
|
||||||
.expect("attached")
|
.expect("attached")
|
||||||
.due(Instant::now());
|
.due(Instant::now());
|
||||||
if let Some(kind) = due {
|
if let Some(kind) = due {
|
||||||
let ticket = self.queue_save(kind).await?;
|
self.begin_save(kind).await?;
|
||||||
saves.push(SaveQueued {
|
|
||||||
generation: ticket.generation,
|
|
||||||
durable: ticket.durable,
|
|
||||||
archive_rank: ticket.archive_rank,
|
|
||||||
});
|
|
||||||
self.pending_saves.push(ticket);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok((
|
Ok((
|
||||||
|
|
@ -705,6 +730,9 @@ impl LegacySession {
|
||||||
if self.checkpointer.is_none() {
|
if self.checkpointer.is_none() {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
|
for ticket in self.finish_captures().await? {
|
||||||
|
self.pending_saves.push(ticket);
|
||||||
|
}
|
||||||
let report = self.save(SaveKind::Durable).await?;
|
let report = self.save(SaveKind::Durable).await?;
|
||||||
self.completed_saves(true).await?;
|
self.completed_saves(true).await?;
|
||||||
if let Some(checkpointer) = self.checkpointer.as_mut() {
|
if let Some(checkpointer) = self.checkpointer.as_mut() {
|
||||||
|
|
|
||||||
|
|
@ -709,6 +709,19 @@ impl Coordinator {
|
||||||
&mut self,
|
&mut self,
|
||||||
checkpoint_id: &Id,
|
checkpoint_id: &Id,
|
||||||
) -> Outcome<(u64, Vec<u8>, Vec<(Id, Vec<u8>)>)> {
|
) -> Outcome<(u64, Vec<u8>, Vec<(Id, Vec<u8>)>)> {
|
||||||
|
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<PendingCapture> {
|
||||||
let origin = self.phases.phase();
|
let origin = self.phases.phase();
|
||||||
let Some(boundary) = origin.committed_boundary().filter(|_| origin.is_committed_boundary())
|
let Some(boundary) = origin.committed_boundary().filter(|_| origin.is_committed_boundary())
|
||||||
else {
|
else {
|
||||||
|
|
@ -727,11 +740,53 @@ impl Coordinator {
|
||||||
participants.extend(self.agents.iter().map(|slot| slot.worker.clone()));
|
participants.extend(self.agents.iter().map(|slot| slot.worker.clone()));
|
||||||
let params = object(CaptureParams { checkpoint_id: checkpoint_id.clone() }.to_json());
|
let params = object(CaptureParams { checkpoint_id: checkpoint_id.clone() }.to_json());
|
||||||
let want = vec![crate::state::PAYLOAD_ATTACHMENT.to_owned()];
|
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 {
|
for worker in participants {
|
||||||
let reply = self
|
let request_id = self.serials.next(&worker.service);
|
||||||
.call(&worker, "State.Capture", Some(self.scope(boundary)), params.clone(), &[], &want)
|
let sent = crate::rpc::send(
|
||||||
.await?;
|
&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<u8>, Vec<(Id, Vec<u8>)>)> {
|
||||||
|
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 {
|
let Some(artifact) = reply.artifacts.get(crate::state::PAYLOAD_ATTACHMENT).cloned() else {
|
||||||
return Err(self.fail_now(
|
return Err(self.fail_now(
|
||||||
DomainError::before(ErrorCode::BufferInvalid, "State.Capture carried no payload"),
|
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?;
|
self.acknowledge_replies(&worker, std::slice::from_ref(&reply.request_id)).await?;
|
||||||
payloads.push((worker.worker_id.clone(), bytes));
|
payloads.push((worker.worker_id.clone(), bytes));
|
||||||
}
|
}
|
||||||
self.transition(origin)?;
|
|
||||||
let world = payloads.remove(0).1;
|
let world = payloads.remove(0).1;
|
||||||
self.audit.push(format!("captured-payloads:{checkpoint_id}@{boundary}"));
|
self.audit.push(format!("captured-payloads:{checkpoint_id}@{boundary}"));
|
||||||
Ok((boundary, world, payloads))
|
Ok((boundary, world, payloads))
|
||||||
|
|
@ -1624,6 +1678,21 @@ pub struct RollbackDetails {
|
||||||
pub agents: Vec<(Id, fly_session_types::extensions::AgentRollbackResult)>,
|
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
|
/// 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`]).
|
/// format, to install as a session's start ([`Coordinator::import`]).
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
|
|
|
||||||
|
|
@ -312,6 +312,43 @@ pub fn encode_payload(
|
||||||
encode_envelope(PAYLOAD_MAGIC, &manifest, &chunks.chunks).map_err(|e| e.to_string())
|
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<String>,
|
||||||
|
accumulator: TickAccumulator,
|
||||||
|
context: TypedValue,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CaptureSnapshot {
|
||||||
|
fn encode(&self) -> DomainResult<Vec<u8>> {
|
||||||
|
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`).
|
/// The reinforcement calls a `FLYAGT01` capture payload records (`learning.updates`).
|
||||||
pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result<u64, String> {
|
pub fn decode_payload_reinforcements(bytes: &[u8]) -> Result<u64, String> {
|
||||||
let parts = decode_envelope(bytes, PAYLOAD_MAGIC)
|
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`
|
/// 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
|
/// manifest member with the accumulator, the context and the identities. The readout
|
||||||
/// transient is not in it (`legacy-transient-reset`).
|
/// transient is not in it (`legacy-transient-reset`).
|
||||||
fn payload(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult<Vec<u8>> {
|
/// Everything a capture payload is encoded from, copied out of the live agent.
|
||||||
|
fn snapshot(&self, checkpoint_id: &Id, scope: &Scope, k: u64) -> DomainResult<CaptureSnapshot> {
|
||||||
let agent = self.agent.as_ref().expect("initialized");
|
let agent = self.agent.as_ref().expect("initialized");
|
||||||
let accumulator = self.accumulator.as_ref().expect("initialized");
|
let accumulator = self.accumulator.as_ref().expect("initialized");
|
||||||
let context = self.context.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`).
|
// The session owns the frame remainder, as the legacy loop does (`Sim::checkpoint`).
|
||||||
state.remainder = rational_remainder_to_legacy(&accumulator.remainder())
|
state.remainder = rational_remainder_to_legacy(&accumulator.remainder())
|
||||||
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?;
|
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))?;
|
||||||
encode_payload(
|
Ok(CaptureSnapshot {
|
||||||
&state,
|
state,
|
||||||
&PayloadIdentity {
|
agent_id: self.config.agent_id.clone(),
|
||||||
agent_id: &self.config.agent_id,
|
checkpoint_id: checkpoint_id.clone(),
|
||||||
checkpoint_id,
|
scope: scope.clone(),
|
||||||
source_scope: scope,
|
committed_step: k,
|
||||||
committed_step: k,
|
profile: self.profile.asset.clone(),
|
||||||
profile: &self.profile.asset,
|
seed: self.seed,
|
||||||
seed: self.seed,
|
reinforcements: self.reinforcements,
|
||||||
reinforcements: self.reinforcements,
|
macro_channels: self.config.macro_channels.clone(),
|
||||||
macro_channels: &self.config.macro_channels,
|
accumulator: accumulator.clone(),
|
||||||
},
|
context: context.typed.clone(),
|
||||||
accumulator,
|
})
|
||||||
&context.typed,
|
|
||||||
None,
|
|
||||||
)
|
|
||||||
.map_err(|e| DomainError::new(ErrorCode::Internal, e, MutationCertainty::None))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {
|
async fn state_capture(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {
|
||||||
|
|
@ -1330,42 +1364,50 @@ impl LegacyAgentWorker {
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let params: CaptureParams = ctx.params()?;
|
let params: CaptureParams = ctx.params()?;
|
||||||
let previous = self.status.state();
|
// The boundary's state, taken under the endpoint's lock: a copy, as the legacy loop's
|
||||||
self.status.set_state(WorkerState::Capturing);
|
// `export_state` is. Encoding, digesting and sealing it -- milliseconds on the full
|
||||||
let span = crate::profile::span("agent.capture.encode");
|
// connectome -- run after the lock is released (`HandlerReply::deferred`), so the next
|
||||||
let bytes = self.payload(¶ms.checkpoint_id, &scope, k);
|
// Prepare does not wait for them (TASK-01 review N5).
|
||||||
drop(span);
|
let snapshot = {
|
||||||
let bytes = match bytes {
|
let _span = crate::profile::span("agent.capture.snapshot");
|
||||||
Ok(bytes) => bytes,
|
self.snapshot(¶ms.checkpoint_id, &scope, k)?
|
||||||
Err(e) => {
|
|
||||||
self.status.set_state(previous);
|
|
||||||
return Err(e);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
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 graph = self.graph.as_ref().expect("initialized");
|
||||||
let result = CaptureResult {
|
let compatibility = compatibility_digest(
|
||||||
checkpoint_id: params.checkpoint_id,
|
&self.config.agent_id,
|
||||||
boundary: k,
|
&self.profile.asset,
|
||||||
compatibility_digest: compatibility_digest(
|
graph,
|
||||||
&self.config.agent_id,
|
self.seed,
|
||||||
&self.profile.asset,
|
);
|
||||||
graph,
|
let client = ctx.client.clone();
|
||||||
self.seed,
|
Ok(HandlerReply::deferred(Box::pin(async move {
|
||||||
),
|
let bytes = tokio::task::spawn_blocking(move || {
|
||||||
payload: artifact.reference().clone(),
|
let _span = crate::profile::span("agent.capture.encode");
|
||||||
};
|
let bytes = snapshot.encode()?;
|
||||||
Ok(HandlerReply::with_artifacts(
|
let digest = {
|
||||||
object(result.to_json()),
|
let _span = crate::profile::span("agent.capture.digest");
|
||||||
vec![(crate::state::PAYLOAD_ATTACHMENT.to_owned(), artifact)],
|
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<HandlerReply> {
|
async fn state_stage_restore(&mut self, ctx: &HandlerCtx<'_>) -> DomainResult<HandlerReply> {
|
||||||
|
|
|
||||||
|
|
@ -69,8 +69,35 @@ pub async fn call(
|
||||||
request_id: DomainRequestId,
|
request_id: DomainRequestId,
|
||||||
want_artifacts: &[String],
|
want_artifacts: &[String],
|
||||||
) -> Result<DomainReply, DomainError> {
|
) -> Result<DomainReply, DomainError> {
|
||||||
|
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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<Scope>,
|
||||||
|
params: Map<String, Value>,
|
||||||
|
attachments: &[(&str, &flybus::Artifact)],
|
||||||
|
request_id: DomainRequestId,
|
||||||
|
want_artifacts: &[String],
|
||||||
|
) -> Result<SentCall, DomainError> {
|
||||||
let request = SessionRpcRequest { request_id: request_id.clone(), scope, params: Value::Object(params) };
|
let request = SessionRpcRequest { request_id: request_id.clone(), scope, params: Value::Object(params) };
|
||||||
let mut pending = bus
|
let pending = bus
|
||||||
.call(
|
.call(
|
||||||
&target.service,
|
&target.service,
|
||||||
Some(&target.bus_incarnation),
|
Some(&target.bus_incarnation),
|
||||||
|
|
@ -80,26 +107,49 @@ pub async fn call(
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(|e| bus_error(method, &e))?;
|
.map_err(|e| bus_error(method, &e))?;
|
||||||
let result = pending.result().await.map_err(|e| bus_error(method, &e))?;
|
Ok(SentCall {
|
||||||
let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone()))
|
method: method.to_owned(),
|
||||||
.map_err(|e| DomainError::invalid(format!("{method}: {e}")))?;
|
pending,
|
||||||
let mut artifacts = BTreeMap::new();
|
request_id,
|
||||||
for name in want_artifacts {
|
want_artifacts: want_artifacts.to_vec(),
|
||||||
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 {
|
impl SentCall {
|
||||||
Ok(hold) => {
|
/// Waits for the terminal reply.
|
||||||
artifacts.insert(name.clone(), hold);
|
pub async fn finish(mut self) -> Result<DomainReply, DomainError> {
|
||||||
}
|
let method = self.method.as_str();
|
||||||
Err(_) => {
|
let result = self.pending.result().await.map_err(|e| bus_error(method, &e))?;
|
||||||
artifacts.insert(name.clone(), artifact);
|
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.
|
/// Maps a bus failure onto a domain error, preserving how certain the mutation is.
|
||||||
|
|
|
||||||
|
|
@ -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<Box<dyn std::future::Future<Output = DomainResult<HandlerReply>> + Send>>;
|
||||||
|
|
||||||
/// What a handler produced: a domain `result` object and the artifacts it attaches.
|
/// What a handler produced: a domain `result` object and the artifacts it attaches.
|
||||||
pub struct HandlerReply {
|
pub struct HandlerReply {
|
||||||
pub result: Map<String, Value>,
|
pub result: Map<String, Value>,
|
||||||
pub artifacts: Vec<(String, flybus::Artifact)>,
|
pub artifacts: Vec<(String, flybus::Artifact)>,
|
||||||
/// True when a failure left the endpoint mutated; the shell reports it as such.
|
/// True when a failure left the endpoint mutated; the shell reports it as such.
|
||||||
pub mutated: bool,
|
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<DeferredReply>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HandlerReply {
|
impl HandlerReply {
|
||||||
pub fn new(result: Map<String, Value>) -> HandlerReply {
|
pub fn new(result: Map<String, Value>) -> HandlerReply {
|
||||||
HandlerReply { result, artifacts: Vec::new(), mutated: true }
|
HandlerReply { result, artifacts: Vec::new(), mutated: true, deferred: None }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_artifacts(
|
pub fn with_artifacts(
|
||||||
result: Map<String, Value>,
|
result: Map<String, Value>,
|
||||||
artifacts: Vec<(String, flybus::Artifact)>,
|
artifacts: Vec<(String, flybus::Artifact)>,
|
||||||
) -> HandlerReply {
|
) -> 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.
|
/// The canonical JSON of one method result.
|
||||||
|
|
@ -304,6 +319,7 @@ async fn run<E: WorkerEndpoint>(
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
let mut running: Vec<tokio::task::JoinHandle<()>> = Vec::new();
|
let mut running: Vec<tokio::task::JoinHandle<()>> = Vec::new();
|
||||||
|
let order = Arc::new(LockOrder::default());
|
||||||
while let Some(incoming) = service.next().await {
|
while let Some(incoming) = service.next().await {
|
||||||
let method = incoming.method().to_owned();
|
let method = incoming.method().to_owned();
|
||||||
let responder = incoming.responder();
|
let responder = incoming.responder();
|
||||||
|
|
@ -491,9 +507,12 @@ async fn run<E: WorkerEndpoint>(
|
||||||
// original bus call still completes normally. The endpoint mutex, not this loop,
|
// original bus call still completes normally. The endpoint mutex, not this loop,
|
||||||
// enforces one mutation at a time.
|
// enforces one mutation at a time.
|
||||||
running.retain(|task| !task.is_finished());
|
running.retain(|task| !task.is_finished());
|
||||||
|
let ticket = order.issue();
|
||||||
running.push(tokio::spawn(execute(
|
running.push(tokio::spawn(execute(
|
||||||
client.clone(),
|
client.clone(),
|
||||||
endpoint.clone(),
|
endpoint.clone(),
|
||||||
|
order.clone(),
|
||||||
|
ticket,
|
||||||
cache.clone(),
|
cache.clone(),
|
||||||
status.clone(),
|
status.clone(),
|
||||||
worker_id.clone(),
|
worker_id.clone(),
|
||||||
|
|
@ -512,11 +531,73 @@ async fn run<E: WorkerEndpoint>(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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<E>,
|
||||||
|
) -> 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<F: std::future::Future + Unpin>(mut f: F) -> Option<F::Output> {
|
||||||
|
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.
|
/// Runs one admitted mutation, records its reply and answers the bus call.
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
async fn execute<E: WorkerEndpoint>(
|
async fn execute<E: WorkerEndpoint>(
|
||||||
client: flybus::Client,
|
client: flybus::Client,
|
||||||
endpoint: Arc<tokio::sync::Mutex<E>>,
|
endpoint: Arc<tokio::sync::Mutex<E>>,
|
||||||
|
order: Arc<LockOrder>,
|
||||||
|
ticket: u64,
|
||||||
cache: Arc<tokio::sync::Mutex<ResultCache>>,
|
cache: Arc<tokio::sync::Mutex<ResultCache>>,
|
||||||
status: StatusCell,
|
status: StatusCell,
|
||||||
worker_id: Id,
|
worker_id: Id,
|
||||||
|
|
@ -533,7 +614,7 @@ async fn execute<E: WorkerEndpoint>(
|
||||||
let outcome = {
|
let outcome = {
|
||||||
// One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is
|
// 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.
|
// 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 {
|
let ctx = HandlerCtx {
|
||||||
method: &method,
|
method: &method,
|
||||||
request: &request,
|
request: &request,
|
||||||
|
|
@ -542,16 +623,34 @@ async fn execute<E: WorkerEndpoint>(
|
||||||
};
|
};
|
||||||
e.handle(ctx).await
|
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 {
|
match outcome {
|
||||||
Ok(reply) => {
|
Ok(reply) => {
|
||||||
let outcome = success(&request, &worker_id, &incarnation_id, reply.result.clone());
|
let outcome = success(&request, &worker_id, &incarnation_id, reply.result.clone());
|
||||||
let mut holds = Vec::with_capacity(reply.artifacts.len());
|
// The cache owns its own hold on every artifact, so a replay survives the first
|
||||||
for (name, artifact) in &reply.artifacts {
|
// caller consuming its delivery. The holds are independent router round trips, so
|
||||||
// The cache owns its own hold, so a replay survives the first caller
|
// they are taken concurrently.
|
||||||
// consuming its delivery.
|
let retains: Vec<_> = reply
|
||||||
match artifact.retain().await {
|
.artifacts
|
||||||
Ok(hold) => holds.push((name.clone(), hold)),
|
.iter()
|
||||||
Err(_) => holds.push((name.clone(), artifact.clone())),
|
.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);
|
let cached = CachedReply::with_artifacts(outcome.clone(), holds);
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue