Skip to main content

ic_backup/policy/execution_progress/
mod.rs

1//! Pure original-plan progress from exact retained journals; no scheduling or dispatch.
2
3use crate::model::{
4    artifacts::ArtifactChecksumRecord,
5    attempt_journal::{AttemptJournalRecord, AttemptJournalView},
6    operation_plan::MAX_PLAN_OPERATIONS,
7    operation_plan::OperationPlanRecord,
8};
9use serde::Serialize;
10use std::collections::BTreeMap;
11use thiserror::Error;
12
13/// Passive complete journal set supplied by the local evidence-owning caller.
14#[derive(Clone, Debug)]
15pub struct ExecutionProgressRequest<'a> {
16    /// Original immutable declaration; its hash binds every journal's intent.
17    pub plan: &'a OperationPlanRecord,
18    /// Exactly one validated retained journal per declared operation, in any order.
19    pub journals: &'a [&'a AttemptJournalRecord],
20}
21
22/// Derived local attempt condition, without fresh permission or backend qualification.
23#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
24#[serde(rename_all = "snake_case")]
25pub enum OperationProgressState {
26    /// At least one declared prerequisite lacks retained Applied evidence.
27    AwaitingDependencies,
28    /// Prerequisites are Applied and original mutation allowance remains.
29    MutationAvailable,
30    /// No unresolved mutation or Applied receipt, and mutation allowance is exhausted.
31    MutationExhausted,
32    /// A mutation is unresolved and original reconciliation allowance remains.
33    MutationUnresolved,
34    /// An observation reservation remains unresolved, even if its allowance is exhausted.
35    ObservationUnresolved,
36    /// A mutation remains unresolved with no pending observation or remaining observation allowance.
37    ReconciliationExhausted,
38    /// This operation has retained integration-qualified Applied evidence.
39    Applied,
40}
41
42/// Read-only local progress for one exact operation in graph planning order.
43#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
44pub struct OperationProgressView {
45    /// Original opaque operation identity, never an array index.
46    pub operation_sequence: u64,
47    /// Derived local condition; none of these values authorize dispatch.
48    pub state: OperationProgressState,
49    /// Exact retained accounting, authority digest and unresolved attempt identities.
50    pub attempts: AttemptJournalView,
51}
52
53/// Sums over original assigned allowances only; unused plan headroom is excluded.
54#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
55pub struct ExecutionAttemptTotalsView {
56    /// Mutation reservations consumed across all original journals, without refunds.
57    pub mutations_used: u32,
58    /// Observation reservations consumed across all original journals, without refunds.
59    pub observations_used: u32,
60    /// Sum of remaining originally assigned mutation allowances.
61    pub mutations_remaining: u32,
62    /// Sum of remaining originally assigned observation allowances.
63    pub observations_remaining: u32,
64}
65
66/// Read-only projection bound to the complete original declaration and retained journals.
67///
68/// Applied evidence is caller-qualified and does not prove full run completion,
69/// current IC state, artifact durability, application safety or reference release.
70#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
71pub struct ExecutionProgressView {
72    /// Full canonical original plan intent.
73    pub intent: ArtifactChecksumRecord,
74    /// Number of operations with retained Applied receipts, not a terminal proof.
75    pub applied_operations: usize,
76    /// Derived totals over the original per-operation ceilings.
77    pub attempts: ExecutionAttemptTotalsView,
78    /// Exact journal conditions in deterministic graph planning order.
79    pub operations: Vec<OperationProgressView>,
80}
81
82impl ExecutionProgressView {
83    pub(crate) const fn is_unattempted(&self) -> bool {
84        self.attempts.mutations_used == 0 && self.attempts.observations_used == 0
85    }
86
87    pub(crate) fn all_applied(&self) -> bool {
88        self.applied_operations == self.operations.len()
89    }
90}
91
92/// Admit exact complete journal coverage and project causal retained local progress.
93///
94/// Missing journals are errors, never fresh zero-consumption declarations. Any
95/// attempted operation requires Applied evidence for every declared prerequisite.
96/// This validates retained causality, not cross-journal dispatch chronology: no
97/// remote observations, authority probes, writes or scheduling occur.
98///
99/// # Errors
100/// Rejects excessive, duplicate, unknown, missing or mismatched journals, premature
101/// attempts and accounting overflow. Unresolved/exhausted states remain visible.
102pub fn progress(
103    request: &ExecutionProgressRequest<'_>,
104) -> Result<ExecutionProgressView, ExecutionProgressError> {
105    admit_progress(request.plan, request.journals.iter().copied())?.project()
106}
107
108// One complete original admission serves projections, reservations and settlements.
109pub(crate) struct AdmittedProgress<'a> {
110    plan: &'a OperationPlanRecord,
111    intent: ArtifactChecksumRecord,
112    journals: BTreeMap<u64, &'a AttemptJournalRecord>,
113}
114
115impl AdmittedProgress<'_> {
116    pub(crate) fn dependencies_applied(&self, dependencies: &[u64]) -> bool {
117        dependencies
118            .iter()
119            .all(|sequence| self.journals[sequence].applied_receipt().is_some())
120    }
121
122    pub(super) fn journals(&self) -> &BTreeMap<u64, &AttemptJournalRecord> {
123        &self.journals
124    }
125
126    pub(crate) fn project(self) -> Result<ExecutionProgressView, ExecutionProgressError> {
127        let mut totals = ExecutionAttemptTotalsView {
128            mutations_used: 0,
129            observations_used: 0,
130            mutations_remaining: 0,
131            observations_remaining: 0,
132        };
133        let mut operations = Vec::with_capacity(self.journals.len());
134        for node in self.plan.ordered_operations() {
135            let sequence = node.operation_sequence();
136            let attempts = self.journals[&sequence].view();
137            totals.add(&attempts)?;
138            operations.push(OperationProgressView {
139                operation_sequence: sequence,
140                state: condition(&attempts, !self.dependencies_applied(node.depends_on())),
141                attempts,
142            });
143        }
144        Ok(ExecutionProgressView {
145            intent: self.intent,
146            applied_operations: operations
147                .iter()
148                .filter(|operation| operation.attempts.applied)
149                .count(),
150            attempts: totals,
151            operations,
152        })
153    }
154}
155
156pub(crate) fn admit_progress<'a>(
157    plan: &'a OperationPlanRecord,
158    originals: impl ExactSizeIterator<Item = &'a AttemptJournalRecord>,
159) -> Result<AdmittedProgress<'a>, ExecutionProgressError> {
160    // Admit complete original coverage before deriving causal state or totals.
161    if originals.len() > MAX_PLAN_OPERATIONS {
162        return Err(ExecutionProgressError::TooManyJournals);
163    }
164    let intent = plan.digest();
165    let mut journals = BTreeMap::new();
166    for journal in originals {
167        let sequence = journal.authority().binding().operation_sequence();
168        let operation = plan
169            .operation(sequence)
170            .map_err(|_| ExecutionProgressError::UnknownOperation(sequence))?;
171        if journals.contains_key(&sequence) {
172            return Err(ExecutionProgressError::DuplicateJournal(sequence));
173        }
174        if !plan.matches_authority(operation, &intent, journal.authority()) {
175            return Err(ExecutionProgressError::AuthorityMismatch(sequence));
176        }
177        journals.insert(sequence, journal);
178    }
179    for operation in plan.operations() {
180        if !journals.contains_key(&operation.operation_sequence()) {
181            return Err(ExecutionProgressError::MissingJournal(
182                operation.operation_sequence(),
183            ));
184        }
185    }
186    // Exact original per-operation budgets already fit the bounded plan totals.
187    // Admission needs no projected authority hashes or allocated operation views.
188    for node in plan.ordered_operations() {
189        let sequence = node.operation_sequence();
190        if journals[&sequence].mutations_used() != 0
191            && let Some(prerequisite) = node
192                .depends_on()
193                .iter()
194                .find(|dependency| journals[*dependency].applied_receipt().is_none())
195        {
196            return Err(ExecutionProgressError::PrematureAttempt {
197                operation_sequence: sequence,
198                prerequisite: *prerequisite,
199            });
200        }
201    }
202    Ok(AdmittedProgress {
203        plan,
204        intent,
205        journals,
206    })
207}
208
209impl ExecutionAttemptTotalsView {
210    fn add(&mut self, attempts: &AttemptJournalView) -> Result<(), ExecutionProgressError> {
211        self.mutations_used = sum(self.mutations_used, attempts.mutations_used)?;
212        self.observations_used = sum(self.observations_used, attempts.observations_used)?;
213        self.mutations_remaining = sum(self.mutations_remaining, attempts.mutations_remaining)?;
214        self.observations_remaining =
215            sum(self.observations_remaining, attempts.observations_remaining)?;
216        Ok(())
217    }
218}
219fn sum(left: u32, right: u32) -> Result<u32, ExecutionProgressError> {
220    left.checked_add(right)
221        .ok_or(ExecutionProgressError::AccountingOverflow)
222}
223fn condition(attempts: &AttemptJournalView, unmet_dependencies: bool) -> OperationProgressState {
224    if attempts.applied {
225        OperationProgressState::Applied
226    } else if attempts.pending_observation.is_some() {
227        OperationProgressState::ObservationUnresolved
228    } else if attempts.pending_mutation.is_some() {
229        if attempts.observations_remaining == 0 {
230            OperationProgressState::ReconciliationExhausted
231        } else {
232            OperationProgressState::MutationUnresolved
233        }
234    } else if unmet_dependencies {
235        OperationProgressState::AwaitingDependencies
236    } else if attempts.mutations_remaining == 0 {
237        OperationProgressState::MutationExhausted
238    } else {
239        OperationProgressState::MutationAvailable
240    }
241}
242
243/// Typed original-plan journal admission, retained causality or accounting failure.
244#[derive(Debug, Error, Eq, PartialEq)]
245pub enum ExecutionProgressError {
246    /// The journal input exceeds the original bounded operation count.
247    #[error("execution progress exceeds {MAX_PLAN_OPERATIONS} journals")]
248    TooManyJournals,
249    /// Multiple supplied journals claim the same original operation identity.
250    #[error("duplicate journal for operation {0}")]
251    DuplicateJournal(u64),
252    /// A supplied journal's operation is absent from the original plan.
253    #[error("journal operation {0} is absent from the original plan")]
254    UnknownOperation(u64),
255    /// Retained evidence for an original operation was not supplied.
256    #[error("missing original journal for operation {0}")]
257    MissingJournal(u64),
258    /// Intent, context, target, request or original allowance differs from the plan.
259    #[error("original journal authority mismatch for operation {0}")]
260    AuthorityMismatch(u64),
261    /// A reservation exists while a declared prerequisite lacks Applied evidence.
262    #[error(
263        "operation {operation_sequence} was attempted without applied prerequisite {prerequisite}"
264    )]
265    PrematureAttempt {
266        /// Operation with retained consumed mutation allowance.
267        operation_sequence: u64,
268        /// Exact declared prerequisite lacking retained Applied evidence.
269        prerequisite: u64,
270    },
271    /// Derived accounting could not be represented without overflow.
272    #[error("execution attempt accounting overflow")]
273    AccountingOverflow,
274}
275
276#[cfg(test)]
277mod tests;