ic_backup/workflow/execution_workflow/
mod.rs1use crate::{
4 model::{
5 artifacts::ArtifactChecksumRecord,
6 execution_workflow::{
7 ExecutionStageBindingRecord, ExecutionStagePredecessorRecord, ExecutionWorkflowError,
8 ExecutionWorkflowRecord,
9 },
10 operation_plan::OperationPlanRecord,
11 },
12 ops::persistence::{
13 BackupLayoutGuard, ExecutionStageCheckpointError, ExecutionStageGuard,
14 ExecutionStagePreparationError, ExecutionWorkflowPersistenceError,
15 ExecutionWorkflowSettlementView, create_execution_workflow,
16 read_complete_execution_workflow, read_execution_stage_occupancy, read_execution_workflow,
17 },
18};
19use std::{collections::BTreeMap, future::Future};
20use thiserror::Error;
21
22pub trait ExecutionWorkflowStageDriver {
30 type Error: std::error::Error + 'static;
32
33 fn bind_stage(
37 &mut self,
38 workflow: &ExecutionWorkflowRecord,
39 stage_sequence: u64,
40 predecessors: &[ExecutionStagePredecessorRecord],
41 ) -> Result<OperationPlanRecord, Self::Error>;
42
43 fn execute_stage(
45 &mut self,
46 stage: &ExecutionStageGuard<'_>,
47 ) -> impl Future<Output = Result<ArtifactChecksumRecord, Self::Error>>;
48
49 fn learned_for_successor(
58 &mut self,
59 predecessor: &ExecutionStagePredecessorRecord,
60 _successor_sequence: u64,
61 ) -> Result<ArtifactChecksumRecord, Self::Error> {
62 Ok(predecessor.learned_evidence().clone())
63 }
64}
65
66#[derive(Clone, Debug, Eq, PartialEq)]
72pub struct RetainedStageEvidence {
73 binding: ArtifactChecksumRecord,
74 learned_evidence: ArtifactChecksumRecord,
75 successor_evidence: BTreeMap<u64, ArtifactChecksumRecord>,
76}
77impl RetainedStageEvidence {
78 #[must_use]
80 pub const fn new(
81 binding: ArtifactChecksumRecord,
82 learned_evidence: ArtifactChecksumRecord,
83 ) -> Self {
84 Self {
85 binding,
86 learned_evidence,
87 successor_evidence: BTreeMap::new(),
88 }
89 }
90
91 #[must_use]
95 pub fn with_successor_evidence(
96 mut self,
97 successor_evidence: BTreeMap<u64, ArtifactChecksumRecord>,
98 ) -> Self {
99 self.successor_evidence = successor_evidence;
100 self
101 }
102
103 fn learned_for_successor(&self, sequence: u64) -> &ArtifactChecksumRecord {
104 self.successor_evidence
105 .get(&sequence)
106 .unwrap_or(&self.learned_evidence)
107 }
108}
109
110pub async fn run_new_execution_workflow<D: ExecutionWorkflowStageDriver>(
129 layout: &BackupLayoutGuard,
130 workflow: &ExecutionWorkflowRecord,
131 driver: &mut D,
132) -> Result<ExecutionWorkflowSettlementView, ExecutionWorkflowRunError<D::Error>> {
133 create_execution_workflow(layout, workflow)?;
134 execute_remaining_stages(layout, workflow, BTreeMap::new(), &BTreeMap::new(), driver).await?;
135 Ok(read_complete_execution_workflow(
136 layout,
137 &workflow.digest(),
138 )?)
139}
140
141pub async fn run_retained_execution_workflow<D: ExecutionWorkflowStageDriver>(
156 layout: &BackupLayoutGuard,
157 expected_workflow: &ArtifactChecksumRecord,
158 retained: &BTreeMap<u64, RetainedStageEvidence>,
159 driver: &mut D,
160) -> Result<ExecutionWorkflowSettlementView, ExecutionWorkflowRunError<D::Error>> {
161 let workflow = read_execution_workflow(layout, expected_workflow)?;
162 let occupied = read_execution_stage_occupancy(layout, expected_workflow)?;
163 if !retained.keys().copied().eq(occupied.iter().copied()) {
164 return Err(ExecutionWorkflowRunError::RetainedStageSetMismatch);
165 }
166 let mut completed: BTreeMap<u64, ExecutionStagePredecessorRecord> = BTreeMap::new();
167 for (&sequence, evidence) in retained {
168 for successor in evidence.successor_evidence.keys() {
169 let Ok(node) = workflow.allocation().graph().node(*successor) else {
170 return Err(ExecutionWorkflowRunError::RetainedLearnedMismatch(sequence));
171 };
172 if !node.depends_on().contains(&sequence) {
173 return Err(ExecutionWorkflowRunError::RetainedLearnedMismatch(sequence));
174 }
175 }
176 let stage =
177 ExecutionStageGuard::open(layout, expected_workflow, sequence, &evidence.binding)?;
178 for predecessor in stage.binding().predecessors() {
179 let Some(original) = retained.get(&predecessor.stage_sequence()) else {
180 return Err(ExecutionWorkflowRunError::RetainedStageSetMismatch);
181 };
182 if original.learned_for_successor(sequence) != predecessor.learned_evidence() {
183 return Err(ExecutionWorkflowRunError::RetainedLearnedMismatch(sequence));
184 }
185 }
186 let checkpoint = stage.replay_checkpoint(evidence.learned_evidence.clone())?;
187 completed.insert(sequence, checkpoint);
188 }
189 if read_execution_stage_occupancy(layout, expected_workflow)? != occupied {
192 return Err(ExecutionWorkflowRunError::RetainedStageSetMismatch);
193 }
194 execute_remaining_stages(layout, &workflow, completed, retained, driver).await?;
195 Ok(read_complete_execution_workflow(layout, expected_workflow)?)
196}
197
198async fn execute_remaining_stages<D: ExecutionWorkflowStageDriver>(
201 layout: &BackupLayoutGuard,
202 workflow: &ExecutionWorkflowRecord,
203 mut completed: BTreeMap<u64, ExecutionStagePredecessorRecord>,
204 retained: &BTreeMap<u64, RetainedStageEvidence>,
205 driver: &mut D,
206) -> Result<(), ExecutionWorkflowRunError<D::Error>> {
207 for node in workflow.allocation().graph().ordered_nodes() {
208 let sequence = node.operation_sequence();
209 if completed.contains_key(&sequence) {
210 continue;
211 }
212 let predecessors = node
213 .depends_on()
214 .iter()
215 .map(|dependency| {
216 let original =
217 completed.get(dependency).ok_or(
218 ExecutionWorkflowRunError::<D::Error>::MissingPredecessor(*dependency),
219 )?;
220 let learned = if let Some(evidence) = retained.get(dependency) {
221 evidence.learned_for_successor(sequence).clone()
222 } else {
223 driver
224 .learned_for_successor(original, sequence)
225 .map_err(ExecutionWorkflowRunError::Driver)?
226 };
227 Ok(ExecutionStagePredecessorRecord::new(
228 *dependency,
229 original.binding().clone(),
230 original.settlement().clone(),
231 learned,
232 ))
233 })
234 .collect::<Result<Vec<_>, ExecutionWorkflowRunError<D::Error>>>()?;
235 let checkpoint =
236 execute_absent_stage(layout, workflow, sequence, predecessors, driver).await?;
237 completed.insert(sequence, checkpoint);
238 }
239 Ok(())
240}
241
242async fn execute_absent_stage<D: ExecutionWorkflowStageDriver>(
243 layout: &BackupLayoutGuard,
244 workflow: &ExecutionWorkflowRecord,
245 sequence: u64,
246 predecessors: Vec<ExecutionStagePredecessorRecord>,
247 driver: &mut D,
248) -> Result<ExecutionStagePredecessorRecord, ExecutionWorkflowRunError<D::Error>> {
249 let plan = driver
250 .bind_stage(workflow, sequence, &predecessors)
251 .map_err(ExecutionWorkflowRunError::Driver)?;
252 let binding = ExecutionStageBindingRecord::new(workflow, sequence, &plan, predecessors)?;
253 let stage = ExecutionStageGuard::prepare(layout, binding, plan)?;
254 let learned = driver
255 .execute_stage(&stage)
256 .await
257 .map_err(ExecutionWorkflowRunError::Driver)?;
258 Ok(stage.reconcile_checkpoint(learned)?)
259}
260
261#[derive(Debug, Error)]
263pub enum ExecutionWorkflowRunError<E: std::error::Error + 'static> {
264 #[error("original workflow predecessor {0} did not complete")]
266 MissingPredecessor(u64),
267 #[error("retained stage identities do not match occupied original stages")]
269 RetainedStageSetMismatch,
270 #[error("retained stage {0} has a different learned predecessor commitment")]
273 RetainedLearnedMismatch(u64),
274 #[error(transparent)]
276 Workflow(#[from] ExecutionWorkflowPersistenceError),
277 #[error(transparent)]
279 Binding(#[from] ExecutionWorkflowError),
280 #[error(transparent)]
282 Preparation(#[from] ExecutionStagePreparationError),
283 #[error("original workflow stage driver failed: {0}")]
285 Driver(#[source] E),
286 #[error(transparent)]
288 Checkpoint(#[from] ExecutionStageCheckpointError),
289}
290
291#[cfg(test)]
292mod tests;