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::{
16    AttemptJournalError, AttemptJournalGuard, BackupLayoutGuard, ExecutionProgressPersistenceError,
17    ExecutionSettlementCheckpointError, ExecutionSettlementPersistenceError, JournalLock,
18    JournalLockError, OperationPlanPersistenceError, PersistenceError, read_execution_progress,
19    read_execution_settlement, read_json, read_operation_plan, reconcile_execution_settlement,
20    replay_execution_settlement,
21};
22use crate::model::{
23    artifacts::ArtifactChecksumRecord,
24    execution_workflow::{
25        ExecutionStageBindingRecord, ExecutionStagePredecessorRecord, ExecutionWorkflowError,
26        ExecutionWorkflowRecord, MAX_EXECUTION_STAGE_BYTES, MAX_EXECUTION_WORKFLOW_BYTES,
27    },
28    operation_plan::{OperationPlanError, OperationPlanRecord},
29};
30use crate::policy::execution_progress::ExecutionProgressView;
31use std::{
32    collections::{BTreeMap, BTreeSet, btree_map::Entry},
33    fs,
34    path::PathBuf,
35};
36use thiserror::Error;
37
38const WORKFLOW_FILE: &str = "execution-workflow.json";
39const BINDING_FILE: &str = "stage-binding.json";
40
41/// Exact local identities of every original stage's retained checkpoint.
42///
43/// This is a sequential local projection, not an immutable product completion
44/// receipt. It authenticates no learned evidence, remote effect, application
45/// safety or command/byte custody and grants no terminal or reference release.
46#[derive(Clone, Debug, Eq, PartialEq)]
47pub struct ExecutionWorkflowSettlementView {
48    workflow: ArtifactChecksumRecord,
49    stages: Vec<ExecutionStageSettlementView>,
50}
51impl ExecutionWorkflowSettlementView {
52    /// Read the exact original workflow declaration identity.
53    #[must_use]
54    pub const fn workflow(&self) -> &ArtifactChecksumRecord {
55        &self.workflow
56    }
57    /// Read one row per original stage in canonical allocation order.
58    #[must_use]
59    pub fn stages(&self) -> &[ExecutionStageSettlementView] {
60        &self.stages
61    }
62}
63
64/// One original stage's bound plan and complete chronological local checkpoint.
65#[derive(Clone, Debug, Eq, PartialEq)]
66pub struct ExecutionStageSettlementView {
67    stage_sequence: u64,
68    binding: ArtifactChecksumRecord,
69    settlement: ArtifactChecksumRecord,
70}
71impl ExecutionStageSettlementView {
72    /// Read the original opaque stage identity.
73    #[must_use]
74    pub const fn stage_sequence(&self) -> u64 {
75        self.stage_sequence
76    }
77    /// Read the exact retained binding identity.
78    #[must_use]
79    pub const fn binding(&self) -> &ArtifactChecksumRecord {
80        &self.binding
81    }
82    /// Read the complete original journal-history checkpoint identity.
83    #[must_use]
84    pub const fn settlement(&self) -> &ArtifactChecksumRecord {
85        &self.settlement
86    }
87}
88
89/// Durably create the full original workflow allocation without replacement.
90/// # Errors
91/// Rejects occupied/unsafe paths, bounds, ownership and publication failures.
92pub fn create_execution_workflow(
93    layout: &BackupLayoutGuard,
94    record: &ExecutionWorkflowRecord,
95) -> Result<(), ExecutionWorkflowPersistenceError> {
96    layout.check_root()?;
97    let bytes = super::json::encode_json(record, MAX_EXECUTION_WORKFLOW_BYTES)?;
98    super::immutable_record::create_encoded_record(layout, WORKFLOW_FILE, &bytes)
99}
100/// Read exact original workflow allocation; missing evidence never supplies a new budget.
101/// # Errors
102/// Rejects missing/changed/unsafe/oversized records and ownership failures.
103pub fn read_execution_workflow(
104    layout: &BackupLayoutGuard,
105    expected: &ArtifactChecksumRecord,
106) -> Result<ExecutionWorkflowRecord, ExecutionWorkflowPersistenceError> {
107    super::immutable_record::read(
108        layout,
109        WORKFLOW_FILE,
110        MAX_EXECUTION_WORKFLOW_BYTES,
111        |record: &ExecutionWorkflowRecord| &record.digest() == expected,
112        || ExecutionWorkflowPersistenceError::DigestMismatch,
113    )
114}
115
116/// Read which allocated stage paths are already occupied under the held layout.
117///
118/// This is a namespace preflight for a retained run, not evidence that an absent
119/// stage has never dispatched. An occupied partial stage remains occupied and is
120/// never repaired. Derived symlinks and non-directories refuse admission.
121/// # Errors
122/// Rejects changed workflow/layout, unsafe stage entries and IO failures.
123pub(crate) fn read_execution_stage_occupancy(
124    layout: &BackupLayoutGuard,
125    expected: &ArtifactChecksumRecord,
126) -> Result<BTreeSet<u64>, ExecutionWorkflowPersistenceError> {
127    let workflow = read_execution_workflow(layout, expected)?;
128    let mut occupied = BTreeSet::new();
129    for stage in workflow.stages() {
130        let sequence = stage.operation_sequence();
131        match fs::symlink_metadata(stage_path(layout, sequence)) {
132            Ok(metadata) if metadata.is_dir() => {
133                occupied.insert(sequence);
134            }
135            Ok(_) => return Err(ExecutionWorkflowPersistenceError::UnsafeStage),
136            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
137            Err(error) => return Err(PersistenceError::from(error).into()),
138        }
139    }
140    read_execution_workflow(layout, expected)?;
141    Ok(occupied)
142}
143
144/// Replay every allocated stage's exact retained binding and all-Applied checkpoint.
145///
146/// The original workflow determines the complete stage set. Every fixed stage must
147/// exist with a valid child plan, immutable binding, complete original journal set
148/// and exact published settlement. Every binding's predecessor identities must
149/// match this complete original set. Stage locks are held one at a time under
150/// the caller's workflow layout guard. No absent stage means zero spending, and no
151/// occupied checkpoint is repaired or republished. The resulting digest rows
152/// are local evidence only; integration-owned authenticity, complete transfer,
153/// application safety, command quiescence and terminal/release proof remain separate.
154/// # Errors
155/// Rejects missing, unsafe, changed, held or unsettled original evidence without effects.
156pub fn read_complete_execution_workflow(
157    layout: &BackupLayoutGuard,
158    expected: &ArtifactChecksumRecord,
159) -> Result<ExecutionWorkflowSettlementView, ExecutionStageCheckpointError> {
160    read_complete_with(layout, expected, || {
161        read_execution_workflow(layout, expected)
162    })
163}
164
165/// Replay complete original settlement while retaining the exact workflow journal lock.
166///
167/// Terminal-evidence providers may use this instead of reacquiring their held journal
168/// lock. The guard must protect this layout's original `execution-workflow.json`.
169/// Both opening and closing reads retain the ordinary bounds, strict decoding and
170/// expected original digest checks; child locks and checkpoint admission are unchanged.
171/// This supplies local settlement only, never application or reference-release authority.
172/// # Errors
173/// Rejects a guard for another journal, changed originals, or incomplete settlement.
174pub fn read_complete_execution_workflow_locked(
175    layout: &BackupLayoutGuard,
176    journal: &JournalLock,
177    expected: &ArtifactChecksumRecord,
178) -> Result<ExecutionWorkflowSettlementView, ExecutionStageCheckpointError> {
179    if journal.journal() != layout.root().join(WORKFLOW_FILE) {
180        return Err(ExecutionWorkflowPersistenceError::DigestMismatch.into());
181    }
182    read_complete_with(layout, expected, || {
183        layout.check_root()?;
184        let workflow: ExecutionWorkflowRecord =
185            read_json(journal.journal(), MAX_EXECUTION_WORKFLOW_BYTES)?;
186        super::json::check_json_size(&workflow, 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;