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, read_complete_execution_workflow,
16 read_execution_stage_occupancy, read_execution_workflow,
17 },
18};
19use std::{collections::BTreeMap, future::Future, num::NonZeroUsize};
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
50#[derive(Clone, Debug, Eq, PartialEq)]
56pub struct RetainedStageEvidence {
57 binding: ArtifactChecksumRecord,
58 learned_evidence: ArtifactChecksumRecord,
59}
60impl RetainedStageEvidence {
61 #[must_use]
63 pub const fn new(
64 binding: ArtifactChecksumRecord,
65 learned_evidence: ArtifactChecksumRecord,
66 ) -> Self {
67 Self {
68 binding,
69 learned_evidence,
70 }
71 }
72}
73
74#[derive(Clone, Debug, Eq, PartialEq)]
76pub enum ExecutionWorkflowAdvance {
77 Paused,
79 Complete(ExecutionWorkflowSettlementView),
82}
83
84pub async fn advance_execution_workflow<D: ExecutionWorkflowStageDriver>(
101 layout: &BackupLayoutGuard,
102 expected_workflow: &ArtifactChecksumRecord,
103 retained: &BTreeMap<u64, RetainedStageEvidence>,
104 stage_limit: NonZeroUsize,
105 driver: &mut D,
106) -> Result<ExecutionWorkflowAdvance, ExecutionWorkflowRunError<D::Error>> {
107 let (workflow, mut completed) = admit_retained_stages(layout, expected_workflow, retained)?;
108 let mut advanced = 0;
109 for node in workflow.allocation().ordered_operations() {
110 let sequence = node.operation_sequence();
111 if completed.contains_key(&sequence) {
112 continue;
113 }
114 if advanced == stage_limit.get() {
115 return Ok(ExecutionWorkflowAdvance::Paused);
116 }
117 let predecessors = node
118 .depends_on()
119 .iter()
120 .map(|dependency| {
121 completed.get(dependency).cloned().ok_or(
122 ExecutionWorkflowRunError::<D::Error>::MissingPredecessor(*dependency),
123 )
124 })
125 .collect::<Result<Vec<_>, ExecutionWorkflowRunError<D::Error>>>()?;
126 let checkpoint =
127 execute_absent_stage(layout, &workflow, sequence, predecessors, driver).await?;
128 completed.insert(sequence, checkpoint);
129 advanced += 1;
130 }
131 Ok(ExecutionWorkflowAdvance::Complete(
132 read_complete_execution_workflow(layout, expected_workflow)?,
133 ))
134}
135
136fn admit_retained_stages<E: std::error::Error + 'static>(
137 layout: &BackupLayoutGuard,
138 expected_workflow: &ArtifactChecksumRecord,
139 retained: &BTreeMap<u64, RetainedStageEvidence>,
140) -> Result<
141 (
142 ExecutionWorkflowRecord,
143 BTreeMap<u64, ExecutionStagePredecessorRecord>,
144 ),
145 ExecutionWorkflowRunError<E>,
146> {
147 let workflow = read_execution_workflow(layout, expected_workflow)?;
148 let occupied = read_execution_stage_occupancy(layout, expected_workflow)?;
149 if !retained.keys().copied().eq(occupied.iter().copied()) {
150 return Err(ExecutionWorkflowRunError::RetainedStageSetMismatch);
151 }
152 let mut completed = BTreeMap::new();
153 for (&sequence, evidence) in retained {
154 let stage =
155 ExecutionStageGuard::open(layout, expected_workflow, sequence, &evidence.binding)?;
156 for predecessor in stage.binding().predecessors() {
157 let Some(original) = retained.get(&predecessor.stage_sequence()) else {
158 return Err(ExecutionWorkflowRunError::RetainedStageSetMismatch);
159 };
160 if &original.learned_evidence != predecessor.learned_evidence() {
161 return Err(ExecutionWorkflowRunError::RetainedLearnedMismatch(sequence));
162 }
163 }
164 let checkpoint = stage.replay_checkpoint(evidence.learned_evidence.clone())?;
165 completed.insert(sequence, checkpoint);
166 }
167 if read_execution_stage_occupancy(layout, expected_workflow)? != occupied {
170 return Err(ExecutionWorkflowRunError::RetainedStageSetMismatch);
171 }
172 Ok((workflow, completed))
173}
174
175async fn execute_absent_stage<D: ExecutionWorkflowStageDriver>(
176 layout: &BackupLayoutGuard,
177 workflow: &ExecutionWorkflowRecord,
178 sequence: u64,
179 predecessors: Vec<ExecutionStagePredecessorRecord>,
180 driver: &mut D,
181) -> Result<ExecutionStagePredecessorRecord, ExecutionWorkflowRunError<D::Error>> {
182 let plan = driver
183 .bind_stage(workflow, sequence, &predecessors)
184 .map_err(ExecutionWorkflowRunError::Driver)?;
185 let binding = ExecutionStageBindingRecord::new(workflow, sequence, &plan, predecessors)?;
186 let stage = ExecutionStageGuard::prepare(layout, binding, plan)?;
187 let learned = driver
188 .execute_stage(&stage)
189 .await
190 .map_err(ExecutionWorkflowRunError::Driver)?;
191 Ok(stage.reconcile_checkpoint(learned)?)
192}
193
194#[derive(Debug, Error)]
196pub enum ExecutionWorkflowRunError<E: std::error::Error + 'static> {
197 #[error("original workflow predecessor {0} did not complete")]
199 MissingPredecessor(u64),
200 #[error("retained stage identities do not match occupied original stages")]
202 RetainedStageSetMismatch,
203 #[error("retained stage {0} has a different learned predecessor commitment")]
205 RetainedLearnedMismatch(u64),
206 #[error(transparent)]
208 Workflow(#[from] ExecutionWorkflowPersistenceError),
209 #[error(transparent)]
211 Binding(#[from] ExecutionWorkflowError),
212 #[error(transparent)]
214 Preparation(#[from] ExecutionStagePreparationError),
215 #[error("original workflow stage driver failed: {0}")]
217 Driver(#[source] E),
218 #[error(transparent)]
220 Checkpoint(#[from] ExecutionStageCheckpointError),
221}
222
223#[cfg(test)]
224mod tests;