Skip to main content

scientific_workflow/
seal.rs

1//! Verified retention plans and recoverable raw-data removal.
2use crate::{
3    artifact::{ArtifactRole, RunArchive, StorageLocation},
4    provenance::{ReproductionReport, verify_reproduction},
5    storage::{Store, utc_now},
6};
7use serde::{Deserialize, Serialize};
8use std::{io, path::Path};
9/// Exact preservation and removal inventory, suitable for review before applying.
10#[derive(Clone, Debug, Serialize, Deserialize)]
11pub struct SealPlan {
12    /// Run being sealed.
13    pub run_id: String,
14    /// Content identity of the inventory being acted on.
15    pub manifest_sha256: String,
16    /// Verified reproduction closure.
17    pub reproduction: ReproductionReport,
18    /// Processed objects retained and verified.
19    pub processed: Vec<String>,
20    /// Raw logical keys selected for removal.
21    pub remove: Vec<String>,
22    /// Content objects retained because another live reference still needs them.
23    pub retained_shared_objects: Vec<String>,
24}
25/// Evidence produced by an explicitly requested scientific reproduction check.
26#[derive(Clone, Debug, Serialize, Deserialize)]
27pub struct ReproductionEvidence {
28    /// StudyPlan-defined comparison criteria and tolerance specification.
29    pub criteria: serde_json::Value,
30    /// Comparison outcome.
31    pub passed: bool,
32    /// References and measurements supporting the comparison.
33    pub report: serde_json::Value,
34}
35/// Port for the engine or application to perform a complete scientific replay.
36/// It must execute captured inputs and apply the study's declared criteria.
37pub trait ReproductionRunner {
38    /// Reproduces and compares; Workflow never invents a scientific tolerance.
39    fn reproduce(&self, archive: &RunArchive) -> io::Result<ReproductionEvidence>;
40}
41/// Final seal receipt. Original execution history and outcome are preserved.
42#[derive(Clone, Debug, Serialize, Deserialize)]
43pub struct SealReport {
44    /// Receipt generation.
45    pub format: String,
46    /// UTC completion time.
47    pub sealed_at: String,
48    /// Exact preservation and removal decision.
49    pub plan: SealPlan,
50    /// Optional explicitly requested reproduction evidence.
51    pub reproduction: Option<ReproductionEvidence>,
52    /// Immutable verification evidence record for this invocation, when requested.
53    pub reproduction_record: Option<String>,
54}
55/// Verifies the reproduction closure and processed products and prepares removal.
56pub fn preview(archive: &RunArchive) -> io::Result<SealPlan> {
57    let m = archive.manifest();
58    if !m.outcome.terminal() {
59        return Err(io::Error::other(
60            "cannot seal a run without a terminal outcome",
61        ));
62    }
63    let reproduction = verify_reproduction(archive)?;
64    let processed = m
65        .artifacts
66        .iter()
67        .filter(|(k, r)| r.role == ArtifactRole::Processed && !m.removed.contains(k))
68        .map(|(k, _)| k.clone())
69        .collect::<Vec<_>>();
70    if processed.is_empty() {
71        return Err(io::Error::other(
72            "sealing requires declared processed products",
73        ));
74    }
75    for key in &processed {
76        archive.verify(key)?;
77    }
78    let mut required = std::collections::HashSet::new();
79    for key in archive.store.backend.list("")? {
80        if key.ends_with("/manifest.json") && key.split('/').count() == 2 {
81            let other: crate::artifact::RunManifest = archive.store.json(&key)?;
82            for (key, r) in other.artifacts {
83                if !other.removed.contains(&key)
84                    && (other.run_id != m.run_id || r.role != ArtifactRole::Raw)
85                {
86                    required.insert(r.sha256);
87                }
88            }
89        }
90    }
91    required.extend(crate::storage::live_pins(&*archive.store.backend)?);
92    let remove = m
93        .artifacts
94        .iter()
95        .filter(|(key, r)| r.role == ArtifactRole::Raw && !m.removed.contains(key))
96        .map(|(key, _)| key.clone())
97        .collect::<Vec<_>>();
98    let retained_shared_objects = remove
99        .iter()
100        .filter_map(|key| {
101            let sha = &m.artifacts[key].sha256;
102            required.contains(sha).then(|| sha.clone())
103        })
104        .collect::<std::collections::BTreeSet<_>>()
105        .into_iter()
106        .collect();
107    Ok(SealPlan {
108        run_id: m.run_id.clone(),
109        manifest_sha256: crate::artifact::digest_bytes(
110            &serde_json::to_vec(m).map_err(io::Error::other)?,
111        ),
112        reproduction,
113        processed,
114        remove,
115        retained_shared_objects,
116    })
117}
118
119pub(crate) fn execute(
120    location: &StorageLocation,
121    id: &str,
122    workspace: &Path,
123    reproducer: Option<&dyn ReproductionRunner>,
124) -> io::Result<SealReport> {
125    let store = Store::open(location)?;
126    let guard = crate::artifact::MaintenanceLease::acquire(&store, id)?;
127    let mut archive = RunArchive::open(location, id)?;
128    archive.maintenance_owner = Some(guard.owner().into());
129    if let Ok(mut report) = store.json::<SealReport>(&format!("{id}/seal.json")) {
130        verify_reproduction(&archive)?;
131        for key in &report.plan.processed {
132            archive.verify(key)?;
133        }
134        if let Some(runner) = reproducer {
135            let evidence = runner.reproduce(&archive)?;
136            if !evidence.passed {
137                return Err(io::Error::other(
138                    "scientific reproduction comparison failed",
139                ));
140            }
141            let key = format!(
142                "{id}/records/reproduction-check-{}.json",
143                crate::storage::run_id()
144            );
145            store.put_json(&key, &evidence, workspace, true)?;
146            report.reproduction = Some(evidence);
147            report.reproduction_record = Some(key);
148        }
149        return Ok(report);
150    }
151    let preservation: Option<serde_json::Value> =
152        match store.json(&format!("{id}/records/seal-preservation.json")) {
153            Ok(value) => Some(value),
154            Err(e) if e.kind() == io::ErrorKind::NotFound => None,
155            Err(e) => return Err(e),
156        };
157    let (plan, reproduction, reproduction_record) = if let Some(value) = preservation {
158        let plan =
159            serde_json::from_value::<SealPlan>(value["plan"].clone()).map_err(io::Error::other)?;
160        let mut original = archive.manifest.clone();
161        original.removed.clear();
162        if crate::artifact::digest_bytes(&serde_json::to_vec(&original).map_err(io::Error::other)?)
163            != plan.manifest_sha256
164        {
165            return Err(io::Error::other(
166                "run inventory changed after its preservation evidence was committed",
167            ));
168        }
169        verify_reproduction(&archive)?;
170        for key in &plan.processed {
171            archive.verify(key)?;
172        }
173        (
174            plan,
175            serde_json::from_value::<Option<ReproductionEvidence>>(value["reproduction"].clone())
176                .map_err(io::Error::other)?,
177            value["reproduction_record"].as_str().map(str::to_owned),
178        )
179    } else {
180        let plan = preview(&archive)?;
181        let reproduction = reproducer.map(|r| r.reproduce(&archive)).transpose()?;
182        if reproduction.as_ref().is_some_and(|e| !e.passed) {
183            return Err(io::Error::other(
184                "scientific reproduction comparison failed; no raw data removed",
185            ));
186        }
187        let record = if let Some(evidence) = &reproduction {
188            let key = format!(
189                "{id}/records/reproduction-check-{}.json",
190                crate::storage::run_id()
191            );
192            store.put_json(&key, evidence, workspace, true)?;
193            Some(key)
194        } else {
195            None
196        };
197        (plan, reproduction, record)
198    };
199    // Preservation is committed before any availability or deletion transition.
200    store.put_json(&format!("{id}/records/seal-preservation.json"),&serde_json::json!({"plan":plan,"reproduction":reproduction,"reproduction_record":reproduction_record}),workspace,false)?;
201    guard.check_consumers(id)?;
202    if archive.manifest().kind == "campaign" {
203        // Member namespaces are owned executions of this campaign. Their seals
204        // commit first while the parent inventory still protects shared bytes.
205        // The parent's final removal can then release the last raw reference.
206        for key in store.backend.list(&format!("{id}/records/member-"))? {
207            let binding: serde_json::Value = store.json(&key)?;
208            let member = binding["handle"]["run_id"].as_str().ok_or_else(|| {
209                io::Error::other("campaign member lacks its committed run identity")
210            })?;
211            if member == id {
212                return Err(io::Error::other("campaign cannot own itself as a member"));
213            }
214            execute(
215                location,
216                member,
217                &workspace.join("members").join(member),
218                None,
219            )?;
220        }
221    }
222
223    let mut manifest = archive.manifest.clone();
224    let previous: Vec<String> = match store.json(&format!("{id}/records/seal-deletions.json")) {
225        Ok(value) => value,
226        Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
227        Err(e) => return Err(e),
228    };
229    for key in &plan.remove {
230        if !manifest.removed.contains(key) {
231            manifest.removed.push(key.clone());
232        }
233    }
234    store.put_json(&format!("{id}/manifest.json"), &manifest, workspace, false)?;
235    // Publication pins and this root-wide fence prevent a concurrent capture
236    // from losing a deduplicated blob between readback and manifest commit.
237    let _gc = crate::artifact::MaintenanceLease::acquire_gc(&store)?;
238    let mut required = crate::storage::live_pins(&*store.backend)?;
239    for key in store.backend.list("")? {
240        if key.ends_with("/manifest.json") && key.split('/').count() == 2 {
241            let other: crate::artifact::RunManifest = store.json(&key)?;
242            for (key, r) in other.artifacts {
243                if !other.removed.contains(&key) {
244                    required.insert(r.sha256);
245                }
246            }
247        }
248    }
249    let mut removed = previous;
250    for key in &plan.remove {
251        if removed.contains(key) {
252            continue;
253        }
254        let reference = &manifest.artifacts[key];
255        store.backend.remove(&format!("{id}/{key}"))?;
256        if !required.contains(&reference.sha256) {
257            store
258                .backend
259                .remove(&format!("objects/{}", reference.sha256))?;
260        }
261        removed.push(key.clone());
262        store.put_json(
263            &format!("{id}/records/seal-deletions.json"),
264            &removed,
265            workspace,
266            false,
267        )?;
268    }
269    let handle: serde_json::Value = store.json(&format!("{id}/records/handle.json"))?;
270    if handle["host_id"] == crate::workspace::host_id()
271        && let Some(root) = handle["workspace"].as_str()
272    {
273        crate::workspace::remove_sealed_cache(Path::new(root), &plan, &manifest)?;
274    }
275    let report = SealReport {
276        format: "scientific-workflow-seal.v1".into(),
277        sealed_at: utc_now(),
278        plan,
279        reproduction,
280        reproduction_record,
281    };
282    store.put_json(&format!("{id}/seal.json"), &report, workspace, true)?;
283    crate::registry::index_manifest(&store, &manifest, workspace)?;
284    Ok(report)
285}