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