Skip to main content

ic_backup/model/attempt_journal/
mod.rs

1//! Durable finite local attempt accounting adapted from Canic's pending/receipt contracts.
2
3use crate::model::evidence_digest::EvidenceDigest;
4mod authority;
5mod history;
6pub use authority::{
7    AttemptAuthorityRecord, AttemptBudgetRecord, MAX_OPERATION_ATTEMPTS, OperationBindingRecord,
8    OperationBindingRequest,
9};
10
11use crate::model::{
12    artifacts::{ArtifactChecksumRecord, ChecksumError, canonical_hash},
13    bounded_sequence,
14};
15use history::{AttemptEventRecord, Projection};
16use serde::{Deserialize, Deserializer, Serialize};
17use thiserror::Error;
18
19/// Maximum retained reservation/receipt events in one operation journal.
20pub const MAX_ATTEMPT_EVENTS: usize = 2048;
21/// Maximum encoded input and canonical output bytes admitted by persistence ops.
22pub const MAX_ATTEMPT_JOURNAL_BYTES: u64 = 1024 * 1024;
23
24/// Integration-qualified direct mutation outcome; an invocation failure is insufficient.
25#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
26#[serde(rename_all = "snake_case")]
27pub enum MutationOutcomeRecord {
28    /// Exact requested effect is qualified as applied.
29    Applied,
30    /// Exact requested effect is qualified as not applied; consumed allowance remains spent.
31    NotApplied,
32}
33
34/// Integration-qualified observation outcome for its exact reserved mutation.
35#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
36#[serde(rename_all = "snake_case")]
37pub enum ObservationOutcomeRecord {
38    /// Observation qualifies exact requested effect as applied.
39    Applied,
40    /// Observation qualifies exact requested effect as not applied.
41    NotApplied,
42    /// Settled observation cannot resolve the mutation; no allowance is restored.
43    Uncertain,
44}
45
46/// Passive exact direct-reply evidence supplied by its qualified owner.
47#[derive(Clone, Debug)]
48pub struct MutationReceiptRequest {
49    /// Previously reserved mutation attempt number.
50    pub attempt: u32,
51    /// Exact mutating request digest, checked against immutable authority.
52    pub request: String,
53    /// Qualified effect outcome; local process exit alone cannot produce it.
54    pub outcome: MutationOutcomeRecord,
55    /// Canonical digest of retained owner evidence.
56    pub evidence: String,
57}
58
59/// Passive exact reconciliation-reply evidence supplied by its qualified owner.
60///
61/// The owner qualifies observation completion, custody and paid-effect settlement.
62/// A lost observation reply stays pending; it cannot be recorded as `Uncertain`
63/// merely because the local invocation failed or its response was lost.
64#[derive(Clone, Debug)]
65pub struct ObservationReceiptRequest {
66    /// Previously reserved observation attempt number.
67    pub attempt: u32,
68    /// Exact observation request digest, checked against its reservation.
69    pub request: String,
70    /// Qualified outcome, including explicit unresolved evidence.
71    pub outcome: ObservationOutcomeRecord,
72    /// Canonical digest of retained owner evidence.
73    pub evidence: String,
74}
75
76/// Read-only derived local accounting; does not schedule or authorize effects.
77#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
78pub struct AttemptJournalView {
79    /// Exact immutable authority digest including original budgets.
80    pub authority: ArtifactChecksumRecord,
81    /// Mutation attempts already consumed, without refunds.
82    pub mutations_used: u32,
83    /// Reconciliation observations already consumed, without refunds.
84    pub observations_used: u32,
85    /// Original mutation allowance still unconsumed.
86    pub mutations_remaining: u32,
87    /// Original observation allowance still unconsumed.
88    pub observations_remaining: u32,
89    /// Exact unresolved mutation attempt, if any.
90    pub pending_mutation: Option<u32>,
91    /// Exact unresolved observation attempt, if any.
92    pub pending_observation: Option<u32>,
93    /// Retained qualified application of this operation, not full run completion.
94    pub applied: bool,
95    /// Number of retained reservation and receipt events.
96    pub history_len: usize,
97}
98
99/// Exact locally retained evidence for an Applied operation.
100///
101/// The integration owns the evidence's meaning and qualification. In particular,
102/// observation evidence is not the original mutation reply or retry authority.
103#[derive(Clone, Copy, Debug, Eq, PartialEq)]
104pub enum AppliedReceiptEvidence<'a> {
105    /// The original mutation was settled by its direct qualified receipt.
106    Mutation {
107        /// Original mutation attempt number.
108        attempt: u32,
109        /// Digest of the retained integration-qualified direct evidence.
110        evidence: &'a str,
111    },
112    /// A separately budgeted observation settled the original mutation.
113    Observation {
114        /// Separately reserved observation attempt number.
115        attempt: u32,
116        /// Exact observation request digest from its reservation.
117        request: &'a str,
118        /// Digest of retained integration-qualified observation evidence.
119        evidence: &'a str,
120    },
121}
122
123/// Maintained v1 append-only local reservations and receipts for one exact operation.
124#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
125#[serde(try_from = "JournalFields")]
126pub struct AttemptJournalRecord {
127    version: u16,
128    authority: AttemptAuthorityRecord,
129    events: Vec<AttemptEventRecord>,
130    #[serde(skip)]
131    projection: Projection,
132}
133
134#[derive(Deserialize)]
135#[serde(deny_unknown_fields)]
136struct JournalFields {
137    version: u16,
138    authority: AttemptAuthorityRecord,
139    #[serde(deserialize_with = "bounded_events")]
140    events: Vec<AttemptEventRecord>,
141}
142
143impl TryFrom<JournalFields> for AttemptJournalRecord {
144    type Error = AttemptJournalRecordError;
145    fn try_from(mut fields: JournalFields) -> Result<Self, Self::Error> {
146        if fields.version != 1 {
147            return Err(AttemptJournalRecordError::UnsupportedVersion(
148                fields.version,
149            ));
150        }
151        let mut projection = Projection::empty();
152        for event in &mut fields.events {
153            event.normalize()?;
154            projection.apply(event, fields.authority.budget())?;
155        }
156        Ok(Self {
157            version: 1,
158            authority: fields.authority,
159            events: fields.events,
160            projection,
161        })
162    }
163}
164
165impl AttemptJournalRecord {
166    /// Retain an exact validated authority with no consumed attempts.
167    #[must_use]
168    pub const fn new(authority: AttemptAuthorityRecord) -> Self {
169        Self {
170            version: 1,
171            authority,
172            events: Vec::new(),
173            projection: Projection::empty(),
174        }
175    }
176    /// Read exact declared identity and immutable ceilings.
177    #[must_use]
178    pub const fn authority(&self) -> &AttemptAuthorityRecord {
179        &self.authority
180    }
181    /// Read the exact canonical request of the unresolved observation, if any.
182    ///
183    /// This projects existing validated history. It creates no reservation or
184    /// repeat-dispatch permission and returns None after a settled observation.
185    #[must_use]
186    pub fn pending_observation_request(&self) -> Option<&str> {
187        self.projection
188            .pending_observation
189            .as_ref()
190            .map(|pending| pending.request.as_str())
191    }
192    /// Read the terminal Applied receipt from validated original history.
193    ///
194    /// This does not authenticate evidence or grant dispatch, retry or release.
195    #[must_use]
196    pub fn applied_receipt(&self) -> Option<AppliedReceiptEvidence<'_>> {
197        match self.events.last()? {
198            AttemptEventRecord::MutationResolved {
199                mutation,
200                outcome: MutationOutcomeRecord::Applied,
201                evidence,
202            } => Some(AppliedReceiptEvidence::Mutation {
203                attempt: *mutation,
204                evidence,
205            }),
206            AttemptEventRecord::ObservationRecorded {
207                observation,
208                request,
209                outcome: ObservationOutcomeRecord::Applied,
210                evidence,
211            } => Some(AppliedReceiptEvidence::Observation {
212                attempt: *observation,
213                request,
214                evidence,
215            }),
216            _ => None,
217        }
218    }
219    /// Project local evidence without IO or replenishing authority.
220    ///
221    /// Use `Self::applied_receipt` for the terminal receipt or `Self::digest`
222    /// for exact full-history identity.
223    #[must_use]
224    pub fn view(&self) -> AttemptJournalView {
225        AttemptJournalView {
226            authority: self.authority.digest(),
227            mutations_used: self.projection.mutations_used,
228            observations_used: self.projection.observations_used,
229            mutations_remaining: self.authority.budget().mutations()
230                - self.projection.mutations_used,
231            observations_remaining: self.authority.budget().observations()
232                - self.projection.observations_used,
233            pending_mutation: self.projection.pending_mutation,
234            pending_observation: self
235                .projection
236                .pending_observation
237                .as_ref()
238                .map(|pending| pending.attempt),
239            applied: self.projection.applied,
240            history_len: self.events.len(),
241        }
242    }
243    /// Hash full original authority and every canonical chronological reservation/receipt.
244    ///
245    /// The NUL-terminated v1 domain precedes 64 ASCII authority hash bytes, a
246    /// big-endian u64 event count and closed tagged event bytes. Derived projections,
247    /// JSON formatting and filesystem paths are excluded. This authenticates no receipt.
248    #[must_use]
249    pub fn digest(&self) -> ArtifactChecksumRecord {
250        let mut bytes = EvidenceDigest::new(b"ic-backup/attempt-journal-history/v1\0");
251        bytes.append(self.authority.digest().hash().as_bytes());
252        bytes.append(&(self.events.len() as u64).to_be_bytes());
253        for event in &self.events {
254            event.append_digest_bytes(&mut bytes);
255        }
256        bytes.finish()
257    }
258    pub(crate) fn reserve_mutation(&mut self) -> Result<u32, AttemptJournalRecordError> {
259        let attempt = self.projection.next_attempt;
260        self.append(AttemptEventRecord::MutationReserved { attempt })?;
261        Ok(attempt)
262    }
263    pub(crate) fn reserve_observation(
264        &mut self,
265        mutation: u32,
266        request: &str,
267    ) -> Result<u32, AttemptJournalRecordError> {
268        let attempt = self.projection.next_attempt;
269        self.append(AttemptEventRecord::ObservationReserved {
270            attempt,
271            mutation,
272            request: request.to_owned(),
273        })?;
274        Ok(attempt)
275    }
276    pub(crate) fn record_mutation(
277        &mut self,
278        receipt: MutationReceiptRequest,
279    ) -> Result<(), AttemptJournalRecordError> {
280        if canonical_hash(&receipt.request)? != self.authority.binding().request() {
281            return Err(AttemptJournalRecordError::RequestMismatch);
282        }
283        self.append(AttemptEventRecord::MutationResolved {
284            mutation: receipt.attempt,
285            outcome: receipt.outcome,
286            evidence: receipt.evidence,
287        })
288    }
289    pub(crate) fn record_observation(
290        &mut self,
291        receipt: ObservationReceiptRequest,
292    ) -> Result<(), AttemptJournalRecordError> {
293        self.append(AttemptEventRecord::ObservationRecorded {
294            observation: receipt.attempt,
295            request: receipt.request,
296            outcome: receipt.outcome,
297            evidence: receipt.evidence,
298        })
299    }
300    fn append(&mut self, mut event: AttemptEventRecord) -> Result<(), AttemptJournalRecordError> {
301        if self.events.len() == MAX_ATTEMPT_EVENTS {
302            return Err(AttemptJournalRecordError::HistoryTooLarge);
303        }
304        event.normalize()?;
305        let mut projection = self.projection.clone();
306        projection.apply(&event, self.authority.budget())?;
307        self.events.push(event);
308        self.projection = projection;
309        Ok(())
310    }
311}
312
313fn bounded_events<'de, D: Deserializer<'de>>(
314    deserializer: D,
315) -> Result<Vec<AttemptEventRecord>, D::Error> {
316    bounded_sequence::deserialize::<_, _, MAX_ATTEMPT_EVENTS>(
317        deserializer,
318        "a bounded chronological attempt event list",
319        AttemptJournalRecordError::HistoryTooLarge,
320    )
321}
322
323/// Typed exact identity, finite accounting or chronological state rejection.
324#[derive(Debug, Error)]
325pub enum AttemptJournalRecordError {
326    /// Other product generations are not maintained.
327    #[error("unsupported attempt journal version {0}")]
328    UnsupportedVersion(u16),
329    /// Original limits overflow or exceed the bounded total.
330    #[error("attempt allowance exceeds {MAX_OPERATION_ATTEMPTS}")]
331    BudgetTooLarge,
332    /// The chronological metadata count exceeds its finite bound.
333    #[error("attempt history exceeds {MAX_ATTEMPT_EVENTS} events")]
334    HistoryTooLarge,
335    /// A selected principal is not admitted by its owning boundary.
336    #[error("invalid attempt operation principal")]
337    InvalidPrincipal,
338    /// A digest fails exact canonical admission.
339    #[error(transparent)]
340    Checksum(#[from] ChecksumError),
341    /// An unresolved paid mutation blocks another mutation.
342    #[error("mutation attempt {attempt} remains unresolved")]
343    MutationPending {
344        /// Retained unresolved attempt number.
345        attempt: u32,
346    },
347    /// An observation is still unsettled locally.
348    #[error("observation attempt {attempt} remains unresolved")]
349    ObservationPending {
350        /// Retained unresolved attempt number.
351        attempt: u32,
352    },
353    /// A receipt or reconciliation has no corresponding unresolved mutation.
354    #[error("no pending mutation attempt")]
355    NoPendingMutation,
356    /// A reply has no corresponding unresolved observation.
357    #[error("no pending observation attempt")]
358    NoPendingObservation,
359    /// A receipt or sequence targets another attempt.
360    #[error("attempt identity mismatch: expected {expected}, actual {actual}")]
361    AttemptMismatch {
362        /// Expected exact attempt number.
363        expected: u32,
364        /// Rejected attempt number.
365        actual: u32,
366    },
367    /// Reply/request identity differs from its retained exact reservation.
368    #[error("attempt request digest mismatch")]
369    RequestMismatch,
370    /// Original mutation authority has been consumed.
371    #[error("mutation attempt allowance exhausted")]
372    MutationBudgetExhausted,
373    /// Original observation authority has been consumed.
374    #[error("observation attempt allowance exhausted")]
375    ObservationBudgetExhausted,
376    /// This exact operation is already qualified as applied.
377    #[error("operation application already retained")]
378    AlreadyApplied,
379}
380
381#[cfg(test)]
382mod tests;