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