Skip to main content

ic_backup/workflow/execution_workflow/
mod.rs

1//! Original-workflow stage coordination without a default IC or application adapter.
2
3use 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, num::NonZeroUsize};
20use thiserror::Error;
21
22/// Integration-owned exact child planning and one-shot execution of each original stage.
23///
24/// `bind_stage` must qualify learned inputs against the supplied original predecessors.
25/// `execute_stage` owns fresh effect-boundary admission, provider calls, authenticated
26/// request/reply retention and explicit original Applied receipts. Its returned digest
27/// is opaque learned evidence; the coordinator does not authenticate it. Neither
28/// callback may treat local checkpoint admission as a dispatch or release permit.
29pub trait ExecutionWorkflowStageDriver {
30    /// Integration-owned planning, admission or execution error.
31    type Error: std::error::Error + 'static;
32
33    /// Build one exact child plan under the original stage allocation.
34    /// # Errors
35    /// Returns integration-owned learned-input or child-planning rejection.
36    fn bind_stage(
37        &mut self,
38        workflow: &ExecutionWorkflowRecord,
39        stage_sequence: u64,
40        predecessors: &[ExecutionStagePredecessorRecord],
41    ) -> Result<OperationPlanRecord, Self::Error>;
42
43    /// Execute only the already prepared original child; retain original effects.
44    fn execute_stage(
45        &mut self,
46        stage: &ExecutionStageGuard<'_>,
47    ) -> impl Future<Output = Result<ArtifactChecksumRecord, Self::Error>>;
48
49    /// Qualify the learned commitment for one outgoing dependency edge.
50    ///
51    /// The default reuses the stage checkpoint's learned digest. An integration
52    /// may derive a distinct commitment from its retained original evidence;
53    /// this callback must not dispatch effects or change original spending.
54    /// # Errors
55    /// Refuses an unauthenticated or unavailable edge commitment before the
56    /// successor is prepared or its driver callback is invoked.
57    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/// Integration-qualified identities for an already settled original stage.
67///
68/// Local replay derives its binding and settlement from retained records. The
69/// learned digest is supplied by the integration, which must authenticate the
70/// original response and its relation to the settled attempt before resuming.
71#[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    /// Supply an original binding identity and independently qualified learned input.
79    #[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    /// Supply integration-qualified commitments for outgoing edges that differ
92    /// from this stage's checkpoint digest. Keys must name original successors;
93    /// occupied successor bindings are checked before any driver callback.
94    #[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
110/// Coordinate one *new* fixed workflow in its declared dependency order.
111///
112/// Publish the original allocation once, prepare each child and all its original
113/// journals before invoking the driver, then reconcile its exact all-Applied
114/// checkpoint. The graph's topological order controls stage dependencies, never
115/// numeric sequence order. Success reads back every retained checkpoint through
116/// the canonical complete-workflow owner. No automatic outcome, retry, refund,
117/// terminal receipt, fence or reference release is inferred.
118///
119/// This is a deliberately one-shot entry point. A failure or cancellation retains
120/// the original workflow, prepared stages, pending spending, artifacts and all
121/// obligations. Calling it again refuses the occupied workflow *before* invoking
122/// the driver. Recovery must reopen and reconcile those exact originals through
123/// their separate owners. Retained continuation requires a separately qualified
124/// complete occupied-stage set; a new run cannot reconstruct authority from a prefix.
125/// # Errors
126/// Rejects occupied or changed originals, incomplete stages and driver failures,
127/// preserving all retained evidence without reissuing an effect.
128pub 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(
135        layout,
136        workflow,
137        BTreeMap::new(),
138        &BTreeMap::new(),
139        usize::MAX,
140        driver,
141    )
142    .await?;
143    Ok(read_complete_execution_workflow(
144        layout,
145        &workflow.digest(),
146    )?)
147}
148
149/// Continue an existing allocation after replaying every occupied settled stage.
150///
151/// The caller supplies the complete occupied stage set and authenticates each
152/// stage's learned evidence. Before any driver callback, the coordinator checks
153/// that set against the held layout and replays every exact all-Applied original
154/// checkpoint. Already bound successor edges must commit the qualified digest
155/// supplied for that exact edge; absent overrides use the stage checkpoint's
156/// learned digest. Pending, partially prepared or omitted occupied stages refuse;
157/// none is reissued. Only absent stages may be prepared and executed once, with
158/// fresh authority and external-effect admission remaining with the driver.
159/// This is no terminal receipt, same-ID restore or reference-release permit.
160/// # Errors
161/// Rejects incomplete or changed retained evidence before new driver callbacks;
162/// later stage failures preserve every original journal and effect obligation.
163pub async fn run_retained_execution_workflow<D: ExecutionWorkflowStageDriver>(
164    layout: &BackupLayoutGuard,
165    expected_workflow: &ArtifactChecksumRecord,
166    retained: &BTreeMap<u64, RetainedStageEvidence>,
167    driver: &mut D,
168) -> Result<ExecutionWorkflowSettlementView, ExecutionWorkflowRunError<D::Error>> {
169    let (workflow, completed) = admit_retained_stages(layout, expected_workflow, retained)?;
170    execute_remaining_stages(layout, &workflow, completed, retained, usize::MAX, driver).await?;
171    Ok(read_complete_execution_workflow(layout, expected_workflow)?)
172}
173
174/// Bounded operator advancement, without a second progress or spending ledger.
175#[derive(Clone, Debug, Eq, PartialEq)]
176pub enum ExecutionWorkflowAdvance {
177    /// The selected bound was reached between settled stages; original absent stages remain.
178    Paused,
179    /// Every original stage's exact retained checkpoint passed local replay.
180    /// This grants no product terminal or source-reference release authority.
181    Complete(ExecutionWorkflowSettlementView),
182}
183
184/// Advance at most `stage_limit` absent stages of one prepared original workflow.
185///
186/// Prepare once with `create_execution_workflow`, retaining the original declarations
187/// before effects. Every call uses the same complete occupied-stage evidence admission
188/// as `run_retained_execution_workflow`. A pause happens only between settled stages,
189/// never halfway through a transfer. The limit bounds stage callbacks, not each stage's
190/// original finite effect allowance or elapsed time. All admission, custody, durable
191/// reply retention and effect-specific qualification remain mandatory driver duties.
192///
193/// Pending observations/mutations, partial preparation or changed originals refuse
194/// before any callback; the bound cannot reset them or supply resend permission.
195/// A failed/cancelled callback retains original uncertainty. Inspect it through
196/// `read_execution_workflow_progress` and reconcile through the original owners.
197/// Complete replay invokes no driver callbacks, regardless of the selected limit.
198/// # Errors
199/// Retains the existing typed preparation, checkpoint, original-evidence and driver failures.
200pub async fn advance_execution_workflow<D: ExecutionWorkflowStageDriver>(
201    layout: &BackupLayoutGuard,
202    expected_workflow: &ArtifactChecksumRecord,
203    retained: &BTreeMap<u64, RetainedStageEvidence>,
204    stage_limit: NonZeroUsize,
205    driver: &mut D,
206) -> Result<ExecutionWorkflowAdvance, ExecutionWorkflowRunError<D::Error>> {
207    let (workflow, completed) = admit_retained_stages(layout, expected_workflow, retained)?;
208    if execute_remaining_stages(
209        layout,
210        &workflow,
211        completed,
212        retained,
213        stage_limit.get(),
214        driver,
215    )
216    .await?
217    {
218        Ok(ExecutionWorkflowAdvance::Complete(
219            read_complete_execution_workflow(layout, expected_workflow)?,
220        ))
221    } else {
222        Ok(ExecutionWorkflowAdvance::Paused)
223    }
224}
225
226fn admit_retained_stages<E: std::error::Error + 'static>(
227    layout: &BackupLayoutGuard,
228    expected_workflow: &ArtifactChecksumRecord,
229    retained: &BTreeMap<u64, RetainedStageEvidence>,
230) -> Result<
231    (
232        ExecutionWorkflowRecord,
233        BTreeMap<u64, ExecutionStagePredecessorRecord>,
234    ),
235    ExecutionWorkflowRunError<E>,
236> {
237    let workflow = read_execution_workflow(layout, expected_workflow)?;
238    let occupied = read_execution_stage_occupancy(layout, expected_workflow)?;
239    if !retained.keys().copied().eq(occupied.iter().copied()) {
240        return Err(ExecutionWorkflowRunError::RetainedStageSetMismatch);
241    }
242    let mut completed: BTreeMap<u64, ExecutionStagePredecessorRecord> = BTreeMap::new();
243    for (&sequence, evidence) in retained {
244        for successor in evidence.successor_evidence.keys() {
245            let Ok(node) = workflow.allocation().graph().node(*successor) else {
246                return Err(ExecutionWorkflowRunError::RetainedLearnedMismatch(sequence));
247            };
248            if !node.depends_on().contains(&sequence) {
249                return Err(ExecutionWorkflowRunError::RetainedLearnedMismatch(sequence));
250            }
251        }
252        let stage =
253            ExecutionStageGuard::open(layout, expected_workflow, sequence, &evidence.binding)?;
254        for predecessor in stage.binding().predecessors() {
255            let Some(original) = retained.get(&predecessor.stage_sequence()) else {
256                return Err(ExecutionWorkflowRunError::RetainedStageSetMismatch);
257            };
258            if original.learned_for_successor(sequence) != predecessor.learned_evidence() {
259                return Err(ExecutionWorkflowRunError::RetainedLearnedMismatch(sequence));
260            }
261        }
262        let checkpoint = stage.replay_checkpoint(evidence.learned_evidence.clone())?;
263        completed.insert(sequence, checkpoint);
264    }
265    // Recheck the namespace before invoking any integration callback. Create-only
266    // stage preparation still refuses an occupied path after this preflight.
267    if read_execution_stage_occupancy(layout, expected_workflow)? != occupied {
268        return Err(ExecutionWorkflowRunError::RetainedStageSetMismatch);
269    }
270    Ok((workflow, completed))
271}
272
273// Entry points finish their own create-only or retained-evidence admission before
274// sharing dependency propagation and execution of only the remaining stages.
275async fn execute_remaining_stages<D: ExecutionWorkflowStageDriver>(
276    layout: &BackupLayoutGuard,
277    workflow: &ExecutionWorkflowRecord,
278    mut completed: BTreeMap<u64, ExecutionStagePredecessorRecord>,
279    retained: &BTreeMap<u64, RetainedStageEvidence>,
280    stage_limit: usize,
281    driver: &mut D,
282) -> Result<bool, ExecutionWorkflowRunError<D::Error>> {
283    let mut advanced = 0;
284    for node in workflow.allocation().graph().ordered_nodes() {
285        let sequence = node.operation_sequence();
286        if completed.contains_key(&sequence) {
287            continue;
288        }
289        if advanced == stage_limit {
290            return Ok(false);
291        }
292        let predecessors = node
293            .depends_on()
294            .iter()
295            .map(|dependency| {
296                let original =
297                    completed.get(dependency).ok_or(
298                        ExecutionWorkflowRunError::<D::Error>::MissingPredecessor(*dependency),
299                    )?;
300                let learned = if let Some(evidence) = retained.get(dependency) {
301                    evidence.learned_for_successor(sequence).clone()
302                } else {
303                    driver
304                        .learned_for_successor(original, sequence)
305                        .map_err(ExecutionWorkflowRunError::Driver)?
306                };
307                Ok(ExecutionStagePredecessorRecord::new(
308                    *dependency,
309                    original.binding().clone(),
310                    original.settlement().clone(),
311                    learned,
312                ))
313            })
314            .collect::<Result<Vec<_>, ExecutionWorkflowRunError<D::Error>>>()?;
315        let checkpoint =
316            execute_absent_stage(layout, workflow, sequence, predecessors, driver).await?;
317        completed.insert(sequence, checkpoint);
318        advanced += 1;
319    }
320    Ok(true)
321}
322
323async fn execute_absent_stage<D: ExecutionWorkflowStageDriver>(
324    layout: &BackupLayoutGuard,
325    workflow: &ExecutionWorkflowRecord,
326    sequence: u64,
327    predecessors: Vec<ExecutionStagePredecessorRecord>,
328    driver: &mut D,
329) -> Result<ExecutionStagePredecessorRecord, ExecutionWorkflowRunError<D::Error>> {
330    let plan = driver
331        .bind_stage(workflow, sequence, &predecessors)
332        .map_err(ExecutionWorkflowRunError::Driver)?;
333    let binding = ExecutionStageBindingRecord::new(workflow, sequence, &plan, predecessors)?;
334    let stage = ExecutionStageGuard::prepare(layout, binding, plan)?;
335    let learned = driver
336        .execute_stage(&stage)
337        .await
338        .map_err(ExecutionWorkflowRunError::Driver)?;
339    Ok(stage.reconcile_checkpoint(learned)?)
340}
341
342/// Failure of new original-workflow coordination; all originals remain retained.
343#[derive(Debug, Error)]
344pub enum ExecutionWorkflowRunError<E: std::error::Error + 'static> {
345    /// A validated predecessor was not available in the current run.
346    #[error("original workflow predecessor {0} did not complete")]
347    MissingPredecessor(u64),
348    /// Supplied identities do not cover exactly the occupied original stage paths.
349    #[error("retained stage identities do not match occupied original stages")]
350    RetainedStageSetMismatch,
351    /// An occupied successor froze a different learned predecessor commitment,
352    /// or supplied edge evidence names a non-successor.
353    #[error("retained stage {0} has a different learned predecessor commitment")]
354    RetainedLearnedMismatch(u64),
355    /// Original allocation could not be published or was already occupied.
356    #[error(transparent)]
357    Workflow(#[from] ExecutionWorkflowPersistenceError),
358    /// A driver-supplied child violated the fixed original allocation.
359    #[error(transparent)]
360    Binding(#[from] ExecutionWorkflowError),
361    /// Complete child preparation failed without replacing original evidence.
362    #[error(transparent)]
363    Preparation(#[from] ExecutionStagePreparationError),
364    /// Driver-owned planning, qualification, provider or receipt step failed.
365    #[error("original workflow stage driver failed: {0}")]
366    Driver(#[source] E),
367    /// Canonical all-Applied checkpoint or final local replay failed.
368    #[error(transparent)]
369    Checkpoint(#[from] ExecutionStageCheckpointError),
370}
371
372#[cfg(test)]
373mod tests;