Skip to main content

ic_backup/ops/persistence/execution_workflow/
mod.rs

1//! Fixed immutable stage admission using the existing layout, plan and settlement owners.
2
3mod ancestry;
4mod progress;
5mod stage;
6use ancestry::{
7    acquire_stage, read_admitted_binding, read_binding, read_current_binding, stage_path,
8    validate_predecessors,
9};
10pub use progress::{ExecutionWorkflowProgressError, read_execution_workflow_progress};
11pub use stage::ExecutionStageGuard;
12#[cfg(test)]
13use stage::StagePreparationBarrier;
14
15use super::json::read_record;
16use super::{
17    AttemptJournalError, AttemptJournalGuard, BackupLayoutGuard, ExecutionProgressPersistenceError,
18    ExecutionSettlementCheckpointError, ExecutionSettlementPersistenceError, JournalLock,
19    JournalLockError, OperationPlanPersistenceError, PersistenceError, read_execution_progress,
20    read_execution_settlement, read_operation_plan, reconcile_execution_settlement,
21    replay_execution_settlement,
22};
23use crate::model::{
24    artifacts::ArtifactChecksumRecord,
25    execution_workflow::{
26        ExecutionStageBindingRecord, ExecutionStagePredecessorRecord, ExecutionWorkflowError,
27        ExecutionWorkflowRecord, MAX_EXECUTION_STAGE_BYTES, MAX_EXECUTION_WORKFLOW_BYTES,
28    },
29    operation_plan::{OperationPlanError, OperationPlanRecord},
30};
31use crate::policy::execution_progress::ExecutionProgressView;
32use std::{
33    collections::{BTreeMap, BTreeSet, btree_map::Entry},
34    fs,
35    path::PathBuf,
36};
37use thiserror::Error;
38
39const WORKFLOW_FILE: &str = "execution-workflow.json";
40const BINDING_FILE: &str = "stage-binding.json";
41
42/// Exact local identities of every original stage's retained checkpoint.
43///
44/// This is a sequential local projection, not an immutable product completion
45/// receipt. It authenticates no learned evidence, remote effect, application
46/// safety or command/byte custody and grants no terminal or reference release.
47#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct ExecutionWorkflowSettlementView {
49    workflow: ArtifactChecksumRecord,
50    stages: Vec<ExecutionStageSettlementView>,
51}
52impl ExecutionWorkflowSettlementView {
53    /// Read the exact original workflow declaration identity.
54    #[must_use]
55    pub const fn workflow(&self) -> &ArtifactChecksumRecord {
56        &self.workflow
57    }
58    /// Read one row per original stage in canonical allocation order.
59    #[must_use]
60    pub fn stages(&self) -> &[ExecutionStageSettlementView] {
61        &self.stages
62    }
63}
64
65/// One original stage's bound plan and complete chronological local checkpoint.
66#[derive(Clone, Debug, Eq, PartialEq)]
67pub struct ExecutionStageSettlementView {
68    stage_sequence: u64,
69    binding: ArtifactChecksumRecord,
70    settlement: ArtifactChecksumRecord,
71}
72impl ExecutionStageSettlementView {
73    /// Read the original opaque stage identity.
74    #[must_use]
75    pub const fn stage_sequence(&self) -> u64 {
76        self.stage_sequence
77    }
78    /// Read the exact retained binding identity.
79    #[must_use]
80    pub const fn binding(&self) -> &ArtifactChecksumRecord {
81        &self.binding
82    }
83    /// Read the complete original journal-history checkpoint identity.
84    #[must_use]
85    pub const fn settlement(&self) -> &ArtifactChecksumRecord {
86        &self.settlement
87    }
88}
89
90/// Durably create the full original workflow allocation without replacement.
91/// # Errors
92/// Rejects occupied/unsafe paths, bounds, ownership and publication failures.
93pub fn create_execution_workflow(
94    layout: &BackupLayoutGuard,
95    record: &ExecutionWorkflowRecord,
96) -> Result<(), ExecutionWorkflowPersistenceError> {
97    layout.check_root()?;
98    let bytes = super::json::encode_json(record, MAX_EXECUTION_WORKFLOW_BYTES)?;
99    super::immutable_record::create_encoded_record(layout, WORKFLOW_FILE, &bytes)
100}
101/// Read exact original workflow allocation; missing evidence never supplies a new budget.
102/// # Errors
103/// Rejects missing/changed/unsafe/oversized records and ownership failures.
104pub fn read_execution_workflow(
105    layout: &BackupLayoutGuard,
106    expected: &ArtifactChecksumRecord,
107) -> Result<ExecutionWorkflowRecord, ExecutionWorkflowPersistenceError> {
108    super::immutable_record::read(
109        layout,
110        WORKFLOW_FILE,
111        MAX_EXECUTION_WORKFLOW_BYTES,
112        |record: &ExecutionWorkflowRecord| &record.digest() == expected,
113        || ExecutionWorkflowPersistenceError::DigestMismatch,
114    )
115}
116
117/// Read which allocated stage paths are already occupied under the held layout.
118///
119/// This is a namespace preflight for a retained run, not evidence that an absent
120/// stage has never dispatched. An occupied partial stage remains occupied and is
121/// never repaired. Derived symlinks and non-directories refuse admission.
122/// # Errors
123/// Rejects changed workflow/layout, unsafe stage entries and IO failures.
124pub(crate) fn read_execution_stage_occupancy(
125    layout: &BackupLayoutGuard,
126    expected: &ArtifactChecksumRecord,
127) -> Result<BTreeSet<u64>, ExecutionWorkflowPersistenceError> {
128    let workflow = read_execution_workflow(layout, expected)?;
129    let mut occupied = BTreeSet::new();
130    for stage in workflow.stages() {
131        let sequence = stage.operation_sequence();
132        match fs::symlink_metadata(stage_path(layout, sequence)) {
133            Ok(metadata) if metadata.is_dir() => {
134                occupied.insert(sequence);
135            }
136            Ok(_) => return Err(ExecutionWorkflowPersistenceError::UnsafeStage),
137            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
138            Err(error) => return Err(PersistenceError::from(error).into()),
139        }
140    }
141    read_execution_workflow(layout, expected)?;
142    Ok(occupied)
143}
144
145/// Replay every allocated stage's exact retained binding and all-Applied checkpoint.
146///
147/// The original workflow determines the complete stage set. Every fixed stage must
148/// exist with a valid child plan, immutable binding, complete original journal set
149/// and exact published settlement. Every binding's predecessor identities must
150/// match this complete original set. Stage locks are held one at a time under
151/// the caller's workflow layout guard. No absent stage means zero spending, and no
152/// occupied checkpoint is repaired or republished. The resulting digest rows
153/// are local evidence only; integration-owned authenticity, complete transfer,
154/// application safety, command quiescence and terminal/release proof remain separate.
155/// # Errors
156/// Rejects missing, unsafe, changed, held or unsettled original evidence without effects.
157pub fn read_complete_execution_workflow(
158    layout: &BackupLayoutGuard,
159    expected: &ArtifactChecksumRecord,
160) -> Result<ExecutionWorkflowSettlementView, ExecutionStageCheckpointError> {
161    read_complete_with(layout, expected, || {
162        read_execution_workflow(layout, expected)
163    })
164}
165
166/// Replay complete original settlement while retaining the exact workflow journal lock.
167///
168/// Terminal-evidence providers may use this instead of reacquiring their held journal
169/// lock. The guard must protect this layout's original `execution-workflow.json`.
170/// Both opening and closing reads retain the ordinary bounds, strict decoding and
171/// expected original digest checks; child locks and checkpoint admission are unchanged.
172/// This supplies local settlement only, never application or reference-release authority.
173/// # Errors
174/// Rejects a guard for another journal, changed originals, or incomplete settlement.
175pub fn read_complete_execution_workflow_locked(
176    layout: &BackupLayoutGuard,
177    journal: &JournalLock,
178    expected: &ArtifactChecksumRecord,
179) -> Result<ExecutionWorkflowSettlementView, ExecutionStageCheckpointError> {
180    if journal.journal() != layout.root().join(WORKFLOW_FILE) {
181        return Err(ExecutionWorkflowPersistenceError::DigestMismatch.into());
182    }
183    read_complete_with(layout, expected, || {
184        layout.check_root()?;
185        let workflow: ExecutionWorkflowRecord =
186            read_record(journal.journal(), MAX_EXECUTION_WORKFLOW_BYTES)?;
187        if &workflow.digest() != expected {
188            return Err(ExecutionWorkflowPersistenceError::DigestMismatch);
189        }
190        Ok(workflow)
191    })
192}
193
194fn read_complete_with(
195    layout: &BackupLayoutGuard,
196    expected: &ArtifactChecksumRecord,
197    read_original: impl Fn() -> Result<ExecutionWorkflowRecord, ExecutionWorkflowPersistenceError>,
198) -> Result<ExecutionWorkflowSettlementView, ExecutionStageCheckpointError> {
199    let workflow = read_original()?;
200    let mut stages = Vec::with_capacity(workflow.stages().len());
201    for allocated in workflow.stages() {
202        let sequence = allocated.operation_sequence();
203        let stage = acquire_stage(layout, sequence)?;
204        let (binding, plan) = read_current_binding(&stage, &workflow, sequence)?;
205        let settlement = replay_execution_settlement(&stage, &plan.digest())?;
206        read_binding(&stage, &workflow, sequence, &binding.digest())?;
207        let view = ExecutionStageSettlementView {
208            stage_sequence: sequence,
209            binding: binding.digest(),
210            settlement: settlement.digest(),
211        };
212        stages.push((binding, view));
213    }
214    for (binding, _) in &stages {
215        for predecessor in binding.predecessors() {
216            // The original catalog supplies canonical sequence order.
217            let index = stages
218                .binary_search_by_key(&predecessor.stage_sequence(), |(_, view)| {
219                    view.stage_sequence()
220                })
221                .map_err(|_| ExecutionWorkflowPersistenceError::DigestMismatch)?;
222            let actual = &stages[index].1;
223            if predecessor.binding() != actual.binding()
224                || predecessor.settlement() != actual.settlement()
225            {
226                return Err(ExecutionWorkflowPersistenceError::DigestMismatch.into());
227            }
228        }
229    }
230    read_original()?;
231    Ok(ExecutionWorkflowSettlementView {
232        workflow: expected.clone(),
233        stages: stages.into_iter().map(|(_, view)| view).collect(),
234    })
235}
236
237/// Stage-bound checkpoint publication/replay refusal; originals remain retained.
238#[derive(Debug, Error)]
239pub enum ExecutionStageCheckpointError {
240    /// Original workflow/stage or complete ancestor history cannot be admitted.
241    #[error(transparent)]
242    Stage(#[from] ExecutionWorkflowPersistenceError),
243    /// Complete original journal checkpoint derivation/publication failed.
244    #[error(transparent)]
245    Settlement(#[from] ExecutionSettlementCheckpointError),
246}
247
248/// Failed create-only preparation; retained records never grant repair or extra spending.
249#[derive(Debug, Error)]
250pub enum ExecutionStagePreparationError {
251    /// Original stage records, predecessor settlement or layout were rejected.
252    #[error(transparent)]
253    Stage(#[from] ExecutionWorkflowPersistenceError),
254    /// Complete original child authority derivation failed before allocation.
255    #[error(transparent)]
256    Authority(#[from] OperationPlanError),
257    /// Existing attempt-journal locking or durable create-only publication failed.
258    #[error(transparent)]
259    Journal(#[from] AttemptJournalError),
260}
261
262/// Complete retained stage-resume refusal; original evidence and spending remain unchanged.
263#[derive(Debug, Error)]
264pub enum ExecutionStageResumeError {
265    /// Original stage, ancestor history or layout cannot be admitted.
266    #[error(transparent)]
267    Stage(#[from] ExecutionWorkflowPersistenceError),
268    /// Complete original child journals, accounting or causality cannot be admitted.
269    #[error(transparent)]
270    Progress(#[from] ExecutionProgressPersistenceError),
271}
272/// Typed immutable workflow/stage admission failure; no recovery evidence is removed.
273#[derive(Debug, Error)]
274pub enum ExecutionWorkflowPersistenceError {
275    /// Workflow/stage identity differs from the retained expected digest.
276    #[error("execution workflow/stage digest mismatch")]
277    DigestMismatch,
278    /// A derived stage directory is a symlink or another unsafe entry.
279    #[error("unsafe execution stage directory")]
280    UnsafeStage,
281    /// Original model allocation or learned binding was rejected.
282    #[error(transparent)]
283    Model(#[from] ExecutionWorkflowError),
284    /// Existing immutable operation-plan admission failed.
285    #[error(transparent)]
286    Plan(#[from] OperationPlanPersistenceError),
287    /// Existing complete chronological Applied settlement admission failed.
288    #[error(transparent)]
289    Settlement(#[from] ExecutionSettlementPersistenceError),
290    /// Cooperating layout or journal exclusion failed.
291    #[error(transparent)]
292    Lock(#[from] JournalLockError),
293    /// Existing bounded JSON/durable filesystem owner failed.
294    #[error(transparent)]
295    Persistence(#[from] PersistenceError),
296}
297
298#[cfg(all(test, unix))]
299mod tests;