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    effect_graph::MAX_EFFECT_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    /// Original explicit dependency graph digest.
75    pub graph: ArtifactChecksumRecord,
76    /// Number of operations with retained Applied receipts, not a terminal proof.
77    pub applied_operations: usize,
78    /// Derived totals over the original per-operation ceilings.
79    pub attempts: ExecutionAttemptTotalsView,
80    /// Exact journal conditions in deterministic graph planning order.
81    pub operations: Vec<OperationProgressView>,
82}
83
84impl ExecutionProgressView {
85    pub(crate) const fn is_unattempted(&self) -> bool {
86        self.attempts.mutations_used == 0 && self.attempts.observations_used == 0
87    }
88
89    pub(crate) fn all_applied(&self) -> bool {
90        self.applied_operations == self.operations.len()
91    }
92}
93
94/// Admit exact complete journal coverage and project causal retained local progress.
95///
96/// Missing journals are errors, never fresh zero-consumption declarations. Any
97/// attempted operation requires Applied evidence for every declared prerequisite.
98/// This validates retained causality, not cross-journal dispatch chronology: no
99/// remote observations, authority probes, writes or scheduling occur.
100///
101/// # Errors
102/// Rejects excessive, duplicate, unknown, missing or mismatched journals, premature
103/// attempts and accounting overflow. Unresolved/exhausted states remain visible.
104pub fn progress(
105    request: &ExecutionProgressRequest<'_>,
106) -> Result<ExecutionProgressView, ExecutionProgressError> {
107    Ok(progress_with_journals(request.plan, request.journals.iter().copied())?.0)
108}
109
110// Retain the admitted original index for exact-history settlement, so that it
111// consumes the same coverage/authority proof as the public progress projection.
112pub(crate) fn progress_with_journals<'a>(
113    plan: &OperationPlanRecord,
114    originals: impl ExactSizeIterator<Item = &'a AttemptJournalRecord>,
115) -> Result<
116    (
117        ExecutionProgressView,
118        BTreeMap<u64, &'a AttemptJournalRecord>,
119    ),
120    ExecutionProgressError,
121> {
122    if originals.len() > MAX_EFFECT_OPERATIONS {
123        return Err(ExecutionProgressError::TooManyJournals);
124    }
125    let intent = plan.digest();
126    let mut journals = BTreeMap::new();
127    for journal in originals {
128        let sequence = journal.authority().binding().operation_sequence();
129        let operation = plan
130            .operation(sequence)
131            .map_err(|_| ExecutionProgressError::UnknownOperation(sequence))?;
132        if journals.contains_key(&sequence) {
133            return Err(ExecutionProgressError::DuplicateJournal(sequence));
134        }
135        if !plan.matches_authority(operation, &intent, journal.authority()) {
136            return Err(ExecutionProgressError::AuthorityMismatch(sequence));
137        }
138        journals.insert(sequence, journal);
139    }
140    for operation in plan.operations() {
141        if !journals.contains_key(&operation.operation_sequence()) {
142            return Err(ExecutionProgressError::MissingJournal(
143                operation.operation_sequence(),
144            ));
145        }
146    }
147    let is_applied = |sequence: &u64| {
148        journals
149            .get(sequence)
150            .is_some_and(|journal| journal.applied_receipt().is_some())
151    };
152    let mut totals = ExecutionAttemptTotalsView {
153        mutations_used: 0,
154        observations_used: 0,
155        mutations_remaining: 0,
156        observations_remaining: 0,
157    };
158    let mut operations = Vec::with_capacity(journals.len());
159    for node in plan.graph().ordered_nodes() {
160        let sequence = node.operation_sequence();
161        // Closed graph/table identity and complete coverage were admitted above.
162        let attempts = journals
163            .get(&sequence)
164            .ok_or(ExecutionProgressError::MissingJournal(sequence))?
165            .view();
166        let unmet = node
167            .depends_on()
168            .iter()
169            .find(|dependency| !is_applied(dependency));
170        if attempts.mutations_used != 0
171            && let Some(prerequisite) = unmet
172        {
173            return Err(ExecutionProgressError::PrematureAttempt {
174                operation_sequence: sequence,
175                prerequisite: *prerequisite,
176            });
177        }
178        totals.add(&attempts)?;
179        operations.push(OperationProgressView {
180            operation_sequence: sequence,
181            state: condition(&attempts, unmet.is_some()),
182            attempts,
183        });
184    }
185    let applied_operations = operations
186        .iter()
187        .filter(|operation| operation.attempts.applied)
188        .count();
189    Ok((
190        ExecutionProgressView {
191            intent,
192            graph: plan.graph().digest(),
193            applied_operations,
194            attempts: totals,
195            operations,
196        },
197        journals,
198    ))
199}
200impl ExecutionAttemptTotalsView {
201    fn add(&mut self, attempts: &AttemptJournalView) -> Result<(), ExecutionProgressError> {
202        self.mutations_used = sum(self.mutations_used, attempts.mutations_used)?;
203        self.observations_used = sum(self.observations_used, attempts.observations_used)?;
204        self.mutations_remaining = sum(self.mutations_remaining, attempts.mutations_remaining)?;
205        self.observations_remaining =
206            sum(self.observations_remaining, attempts.observations_remaining)?;
207        Ok(())
208    }
209}
210fn sum(left: u32, right: u32) -> Result<u32, ExecutionProgressError> {
211    left.checked_add(right)
212        .ok_or(ExecutionProgressError::AccountingOverflow)
213}
214fn condition(attempts: &AttemptJournalView, unmet_dependencies: bool) -> OperationProgressState {
215    if attempts.applied {
216        OperationProgressState::Applied
217    } else if attempts.pending_observation.is_some() {
218        OperationProgressState::ObservationUnresolved
219    } else if attempts.pending_mutation.is_some() {
220        if attempts.observations_remaining == 0 {
221            OperationProgressState::ReconciliationExhausted
222        } else {
223            OperationProgressState::MutationUnresolved
224        }
225    } else if unmet_dependencies {
226        OperationProgressState::AwaitingDependencies
227    } else if attempts.mutations_remaining == 0 {
228        OperationProgressState::MutationExhausted
229    } else {
230        OperationProgressState::MutationAvailable
231    }
232}
233
234/// Typed original-plan journal admission, retained causality or accounting failure.
235#[derive(Debug, Error, Eq, PartialEq)]
236pub enum ExecutionProgressError {
237    /// The journal input exceeds the original bounded operation count.
238    #[error("execution progress exceeds {MAX_EFFECT_OPERATIONS} journals")]
239    TooManyJournals,
240    /// Multiple supplied journals claim the same original operation identity.
241    #[error("duplicate journal for operation {0}")]
242    DuplicateJournal(u64),
243    /// A supplied journal's operation is absent from the original plan.
244    #[error("journal operation {0} is absent from the original plan")]
245    UnknownOperation(u64),
246    /// Retained evidence for an original operation was not supplied.
247    #[error("missing original journal for operation {0}")]
248    MissingJournal(u64),
249    /// Intent, context, target, request or original allowance differs from the plan.
250    #[error("original journal authority mismatch for operation {0}")]
251    AuthorityMismatch(u64),
252    /// A reservation exists while a declared prerequisite lacks Applied evidence.
253    #[error(
254        "operation {operation_sequence} was attempted without applied prerequisite {prerequisite}"
255    )]
256    PrematureAttempt {
257        /// Operation with retained consumed mutation allowance.
258        operation_sequence: u64,
259        /// Exact declared prerequisite lacking retained Applied evidence.
260        prerequisite: u64,
261    },
262    /// Derived accounting could not be represented without overflow.
263    #[error("execution attempt accounting overflow")]
264    AccountingOverflow,
265}
266
267#[cfg(test)]
268mod tests;