Skip to main content

ic_backup/ops/persistence/execution_settlement/
mod.rs

1//! Immutable original all-Applied journal checkpoint publication and local replay.
2
3use super::json::check_json_size;
4use super::{
5    AttemptJournalError, BackupLayoutGuard, JournalLock, JournalLockError,
6    OperationPlanPersistenceError, PersistenceError, create_json_durable, read_json,
7    read_operation_plan,
8};
9use crate::{
10    model::{
11        artifacts::ArtifactChecksumRecord,
12        attempt_journal::AttemptJournalRecord,
13        execution_settlement::{
14            ExecutionSettlementError, ExecutionSettlementJournalRecord, ExecutionSettlementRecord,
15            MAX_EXECUTION_SETTLEMENT_BYTES,
16        },
17        operation_plan::OperationPlanRecord,
18    },
19    policy::execution_settlement::{ExecutionSettlementPolicyError, validate},
20};
21use std::path::Path;
22use thiserror::Error;
23
24/// Derive and publish an all-Applied checkpoint from the exact retained original journals.
25///
26/// Reads every original journal sequentially, then delegates immutable publication
27/// to [`create_execution_settlement`], which rechecks the complete original histories.
28/// Hold no journal guards at admission. This creates no receipts, spending allowance,
29/// product terminal proof or release permission. An occupied checkpoint is never replaced;
30/// use [`read_execution_settlement`] with its retained identity for local replay.
31/// # Errors
32/// Rejects missing, held, changed or unsettled originals and publication failures.
33pub fn checkpoint_execution_settlement(
34    layout: &BackupLayoutGuard,
35    expected_plan: &ArtifactChecksumRecord,
36) -> Result<ExecutionSettlementRecord, ExecutionSettlementCheckpointError> {
37    let record = derive_execution_settlement(layout, expected_plan)?;
38    create_execution_settlement(layout, &record)?;
39    Ok(record)
40}
41
42/// Reconcile a lost checkpoint response from complete original journals and the
43/// existing immutable checkpoint, without publishing or changing any evidence.
44///
45/// The derived digest is checked against the retained checkpoint, then its full
46/// original histories are admitted again by the existing reader. This local
47/// sequential replay supplies no authenticated receipt, terminal proof or release.
48/// # Errors
49/// Rejects absent/changed checkpoints, missing/held/unsettled journals and drift.
50pub fn replay_execution_settlement(
51    layout: &BackupLayoutGuard,
52    expected_plan: &ArtifactChecksumRecord,
53) -> Result<ExecutionSettlementRecord, ExecutionSettlementCheckpointError> {
54    let derived = derive_execution_settlement(layout, expected_plan)?;
55    Ok(read_execution_settlement(
56        layout,
57        expected_plan,
58        &derived.digest(),
59    )?)
60}
61
62fn derive_execution_settlement(
63    layout: &BackupLayoutGuard,
64    expected_plan: &ArtifactChecksumRecord,
65) -> Result<ExecutionSettlementRecord, ExecutionSettlementCheckpointError> {
66    let (plan, journals) = read_retained_journals(layout, expected_plan)?;
67    let rows = journals
68        .iter()
69        .map(ExecutionSettlementJournalRecord::from_journal)
70        .collect();
71    Ok(ExecutionSettlementRecord::new(plan.digest(), rows)?)
72}
73
74/// Publish fixed `execution-settlement.json` under original retained plan/journal evidence.
75///
76/// The exclusive layout owns cooperating write exclusion. Journal locks are acquired
77/// sequentially in canonical sequence order, bounding descriptor use; every admitted
78/// Applied journal rejects further owner transitions. Hold no journal guards when
79/// invoking this operation. Noncooperating byte custody and authentic receipts remain
80/// integration-owned. This creates no journal, budget, product terminal or release permit.
81/// # Errors
82/// Rejects missing/unsafe/oversized originals, contention, unsettled/changed evidence or existing publication.
83pub fn create_execution_settlement(
84    layout: &BackupLayoutGuard,
85    record: &ExecutionSettlementRecord,
86) -> Result<(), ExecutionSettlementPersistenceError> {
87    create_with(layout, record, create_json_durable)
88}
89fn create_with(
90    layout: &BackupLayoutGuard,
91    record: &ExecutionSettlementRecord,
92    writer: impl FnOnce(&Path, &ExecutionSettlementRecord) -> Result<(), PersistenceError>,
93) -> Result<(), ExecutionSettlementPersistenceError> {
94    layout.check_root()?;
95    let path = layout.root().join("execution-settlement.json");
96    let _lock = JournalLock::acquire(&path)?;
97    check_json_size(record, MAX_EXECUTION_SETTLEMENT_BYTES)?;
98    validate_retained(layout, record)?;
99    writer(&path, record)?;
100    Ok(())
101}
102/// Reopen exact checkpoint and validate complete retained original evidence using local IO only.
103///
104/// A lost publication reply can be reconciled without rewriting evidence or observing
105/// remote state. This is original journal settlement replay, not fresh verification
106/// of artifacts/application state, full run completion or release admission.
107/// # Errors
108/// Rejects changed expected identity, absent/invalid/unsafe evidence, contention or journal drift.
109pub fn read_execution_settlement(
110    layout: &BackupLayoutGuard,
111    expected_plan: &ArtifactChecksumRecord,
112    expected: &ArtifactChecksumRecord,
113) -> Result<ExecutionSettlementRecord, ExecutionSettlementPersistenceError> {
114    layout.check_root()?;
115    let path = layout.root().join("execution-settlement.json");
116    let _lock = JournalLock::acquire(&path)?;
117    let record: ExecutionSettlementRecord = read_json(&path, MAX_EXECUTION_SETTLEMENT_BYTES)?;
118    check_json_size(&record, MAX_EXECUTION_SETTLEMENT_BYTES)?;
119    if record.plan_intent() != expected_plan || &record.digest() != expected {
120        return Err(ExecutionSettlementPersistenceError::DigestMismatch);
121    }
122    validate_retained(layout, &record)?;
123    Ok(record)
124}
125fn validate_retained(
126    layout: &BackupLayoutGuard,
127    record: &ExecutionSettlementRecord,
128) -> Result<(), ExecutionSettlementPersistenceError> {
129    let (plan, journals) = read_retained_journals(layout, record.plan_intent())?;
130    let references: Vec<_> = journals.iter().collect();
131    validate(&plan, &references, record)?;
132    layout.check_root()?;
133    Ok(())
134}
135fn read_retained_journals(
136    layout: &BackupLayoutGuard,
137    expected_plan: &ArtifactChecksumRecord,
138) -> Result<(OperationPlanRecord, Vec<AttemptJournalRecord>), ExecutionSettlementPersistenceError> {
139    let plan = read_operation_plan(layout, expected_plan)?;
140    let authorities = plan.attempt_authorities()?;
141    let journals = super::attempt_journal::read_original_journals(layout, &authorities, None)?;
142    Ok((plan, journals))
143}
144/// Failure deriving, publishing or replaying a checkpoint; originals remain retained.
145#[derive(Debug, Error)]
146pub enum ExecutionSettlementCheckpointError {
147    /// Original local evidence or immutable publication cannot be admitted.
148    #[error(transparent)]
149    Persistence(#[from] ExecutionSettlementPersistenceError),
150    /// The derived checkpoint cannot satisfy the existing bounded record schema.
151    #[error(transparent)]
152    Record(#[from] ExecutionSettlementError),
153}
154/// Typed immutable publication/replay failure, preserving all original journals and obligations.
155#[derive(Debug, Error)]
156pub enum ExecutionSettlementPersistenceError {
157    /// Expected original plan/checkpoint identity differs.
158    #[error("execution settlement digest mismatch")]
159    DigestMismatch,
160    /// Original retained plan cannot be admitted.
161    #[error(transparent)]
162    Plan(#[from] OperationPlanPersistenceError),
163    /// Original plan authority derivation failed.
164    #[error(transparent)]
165    Authority(#[from] crate::model::operation_plan::OperationPlanError),
166    /// An original journal is absent, unsafe, mismatched or held by another owner.
167    #[error(transparent)]
168    Journal(#[from] AttemptJournalError),
169    /// Complete original settlement evidence failed pure policy.
170    #[error(transparent)]
171    Policy(#[from] ExecutionSettlementPolicyError),
172    /// Publication/replay checkpoint lock failed.
173    #[error(transparent)]
174    Lock(#[from] JournalLockError),
175    /// Bounded local IO or canonical encoding failed.
176    #[error(transparent)]
177    Persistence(#[from] PersistenceError),
178}
179#[cfg(all(test, unix))]
180mod tests;