scientific-workflow 0.17.1

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
//! Verified retention plans and recoverable raw-data removal.
use crate::{
    artifact::{ArtifactRole, RunArchive, StorageLocation},
    provenance::{ReproductionReport, verify_reproduction},
    storage::{Store, utc_now},
};
use serde::{Deserialize, Serialize};
use std::{io, path::Path};
/// Exact preservation and removal inventory, suitable for review before applying.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SealPlan {
    /// Run being sealed.
    pub run_id: String,
    /// Content identity of the inventory being acted on.
    pub manifest_sha256: String,
    /// Verified reproduction closure.
    pub reproduction: ReproductionReport,
    /// Processed objects retained and verified.
    pub processed: Vec<String>,
    /// Raw logical keys selected for removal.
    pub remove: Vec<String>,
    /// Content objects retained because another live reference still needs them.
    pub retained_shared_objects: Vec<String>,
}
/// Evidence produced by an explicitly requested scientific reproduction check.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ReproductionEvidence {
    /// StudyPlan-defined comparison criteria and tolerance specification.
    pub criteria: serde_json::Value,
    /// Comparison outcome.
    pub passed: bool,
    /// References and measurements supporting the comparison.
    pub report: serde_json::Value,
}
/// Port for the engine or application to perform a complete scientific replay.
/// It must execute captured inputs and apply the study's declared criteria.
pub trait ReproductionRunner {
    /// Reproduces and compares; Workflow never invents a scientific tolerance.
    fn reproduce(&self, archive: &RunArchive) -> io::Result<ReproductionEvidence>;
}
/// Final seal receipt. Original execution history and outcome are preserved.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SealReport {
    /// Receipt generation.
    pub format: String,
    /// UTC completion time.
    pub sealed_at: String,
    /// Exact preservation and removal decision.
    pub plan: SealPlan,
    /// Optional explicitly requested reproduction evidence.
    pub reproduction: Option<ReproductionEvidence>,
    /// Immutable verification evidence record for this invocation, when requested.
    pub reproduction_record: Option<String>,
}
/// Verifies the reproduction closure and processed products and prepares removal.
pub fn preview(archive: &RunArchive) -> io::Result<SealPlan> {
    let m = archive.manifest();
    if !m.outcome.terminal() {
        return Err(io::Error::other(
            "cannot seal a run without a terminal outcome",
        ));
    }
    let reproduction = verify_reproduction(archive)?;
    let processed = m
        .artifacts
        .iter()
        .filter(|(k, r)| r.role == ArtifactRole::Processed && !m.removed.contains(k))
        .map(|(k, _)| k.clone())
        .collect::<Vec<_>>();
    if processed.is_empty() {
        return Err(io::Error::other(
            "sealing requires declared processed products",
        ));
    }
    for key in &processed {
        archive.verify(key)?;
    }
    let mut required = std::collections::HashSet::new();
    for key in archive.store.backend.list("")? {
        if key.ends_with("/manifest.json") && key.split('/').count() == 2 {
            let other: crate::artifact::RunManifest = archive.store.json(&key)?;
            for (key, r) in other.artifacts {
                if !other.removed.contains(&key)
                    && (other.run_id != m.run_id || r.role != ArtifactRole::Raw)
                {
                    required.insert(r.sha256);
                }
            }
        }
    }
    required.extend(crate::storage::live_pins(&*archive.store.backend)?);
    let remove = m
        .artifacts
        .iter()
        .filter(|(key, r)| r.role == ArtifactRole::Raw && !m.removed.contains(key))
        .map(|(key, _)| key.clone())
        .collect::<Vec<_>>();
    let retained_shared_objects = remove
        .iter()
        .filter_map(|key| {
            let sha = &m.artifacts[key].sha256;
            required.contains(sha).then(|| sha.clone())
        })
        .collect::<std::collections::BTreeSet<_>>()
        .into_iter()
        .collect();
    Ok(SealPlan {
        run_id: m.run_id.clone(),
        manifest_sha256: crate::artifact::digest_bytes(
            &serde_json::to_vec(m).map_err(io::Error::other)?,
        ),
        reproduction,
        processed,
        remove,
        retained_shared_objects,
    })
}

pub(crate) fn execute(
    location: &StorageLocation,
    id: &str,
    workspace: &Path,
    reproducer: Option<&dyn ReproductionRunner>,
) -> io::Result<SealReport> {
    let store = Store::open(location)?;
    let guard = crate::artifact::MaintenanceLease::acquire(&store, id)?;
    let mut archive = RunArchive::open(location, id)?;
    archive.maintenance_owner = Some(guard.owner().into());
    if let Ok(mut report) = store.json::<SealReport>(&format!("{id}/seal.json")) {
        verify_reproduction(&archive)?;
        for key in &report.plan.processed {
            archive.verify(key)?;
        }
        if let Some(runner) = reproducer {
            let evidence = runner.reproduce(&archive)?;
            if !evidence.passed {
                return Err(io::Error::other(
                    "scientific reproduction comparison failed",
                ));
            }
            let key = format!(
                "{id}/records/reproduction-check-{}.json",
                crate::storage::run_id()
            );
            store.put_json(&key, &evidence, workspace, true)?;
            report.reproduction = Some(evidence);
            report.reproduction_record = Some(key);
        }
        return Ok(report);
    }
    let preservation: Option<serde_json::Value> =
        match store.json(&format!("{id}/records/seal-preservation.json")) {
            Ok(value) => Some(value),
            Err(e) if e.kind() == io::ErrorKind::NotFound => None,
            Err(e) => return Err(e),
        };
    let (plan, reproduction, reproduction_record) = if let Some(value) = preservation {
        let plan =
            serde_json::from_value::<SealPlan>(value["plan"].clone()).map_err(io::Error::other)?;
        let mut original = archive.manifest.clone();
        original.removed.clear();
        if crate::artifact::digest_bytes(&serde_json::to_vec(&original).map_err(io::Error::other)?)
            != plan.manifest_sha256
        {
            return Err(io::Error::other(
                "run inventory changed after its preservation evidence was committed",
            ));
        }
        verify_reproduction(&archive)?;
        for key in &plan.processed {
            archive.verify(key)?;
        }
        (
            plan,
            serde_json::from_value::<Option<ReproductionEvidence>>(value["reproduction"].clone())
                .map_err(io::Error::other)?,
            value["reproduction_record"].as_str().map(str::to_owned),
        )
    } else {
        let plan = preview(&archive)?;
        let reproduction = reproducer.map(|r| r.reproduce(&archive)).transpose()?;
        if reproduction.as_ref().is_some_and(|e| !e.passed) {
            return Err(io::Error::other(
                "scientific reproduction comparison failed; no raw data removed",
            ));
        }
        let record = if let Some(evidence) = &reproduction {
            let key = format!(
                "{id}/records/reproduction-check-{}.json",
                crate::storage::run_id()
            );
            store.put_json(&key, evidence, workspace, true)?;
            Some(key)
        } else {
            None
        };
        (plan, reproduction, record)
    };
    // Preservation is committed before any availability or deletion transition.
    store.put_json(&format!("{id}/records/seal-preservation.json"),&serde_json::json!({"plan":plan,"reproduction":reproduction,"reproduction_record":reproduction_record}),workspace,false)?;
    guard.check_consumers(id)?;
    if archive.manifest().kind == "campaign" {
        // Member namespaces are owned executions of this campaign. Their seals
        // commit first while the parent inventory still protects shared bytes.
        // The parent's final removal can then release the last raw reference.
        for key in store.backend.list(&format!("{id}/records/member-"))? {
            let binding: serde_json::Value = store.json(&key)?;
            let member = binding["handle"]["run_id"].as_str().ok_or_else(|| {
                io::Error::other("campaign member lacks its committed run identity")
            })?;
            if member == id {
                return Err(io::Error::other("campaign cannot own itself as a member"));
            }
            execute(
                location,
                member,
                &workspace.join("members").join(member),
                None,
            )?;
        }
    }

    let mut manifest = archive.manifest.clone();
    let previous: Vec<String> = match store.json(&format!("{id}/records/seal-deletions.json")) {
        Ok(value) => value,
        Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
        Err(e) => return Err(e),
    };
    for key in &plan.remove {
        if !manifest.removed.contains(key) {
            manifest.removed.push(key.clone());
        }
    }
    store.put_json(&format!("{id}/manifest.json"), &manifest, workspace, false)?;
    // Publication pins and this root-wide fence prevent a concurrent capture
    // from losing a deduplicated blob between readback and manifest commit.
    let _gc = crate::artifact::MaintenanceLease::acquire_gc(&store)?;
    let mut required = crate::storage::live_pins(&*store.backend)?;
    for key in store.backend.list("")? {
        if key.ends_with("/manifest.json") && key.split('/').count() == 2 {
            let other: crate::artifact::RunManifest = store.json(&key)?;
            for (key, r) in other.artifacts {
                if !other.removed.contains(&key) {
                    required.insert(r.sha256);
                }
            }
        }
    }
    let mut removed = previous;
    for key in &plan.remove {
        if removed.contains(key) {
            continue;
        }
        let reference = &manifest.artifacts[key];
        store.backend.remove(&format!("{id}/{key}"))?;
        if !required.contains(&reference.sha256) {
            store
                .backend
                .remove(&format!("objects/{}", reference.sha256))?;
        }
        removed.push(key.clone());
        store.put_json(
            &format!("{id}/records/seal-deletions.json"),
            &removed,
            workspace,
            false,
        )?;
    }
    let handle: serde_json::Value = store.json(&format!("{id}/records/handle.json"))?;
    if handle["host_id"] == crate::workspace::host_id()
        && let Some(root) = handle["workspace"].as_str()
    {
        crate::workspace::remove_sealed_cache(Path::new(root), &plan, &manifest)?;
    }
    let report = SealReport {
        format: "scientific-workflow-seal.v1".into(),
        sealed_at: utc_now(),
        plan,
        reproduction,
        reproduction_record,
    };
    store.put_json(&format!("{id}/seal.json"), &report, workspace, true)?;
    crate::registry::index_manifest(&store, &manifest, workspace)?;
    Ok(report)
}