scientific-workflow 0.18.1

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
//! Full replay through captured, model-linked runners and study-owned comparisons.
use super::launch::{RunHandle, copy_tree, rewrite_paths};
use crate::{
    artifact::{ArtifactRole, RunArchive, StorageLocation},
    seal::{ReproductionEvidence, ReproductionRunner},
    storage::atomic_json,
};
use std::{
    io::{self, Read},
    path::{Path, PathBuf},
    process::{Command, Stdio},
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
    time::{Duration, Instant},
};

pub(crate) struct CapturedReproducer {
    pub(crate) workspace: PathBuf,
}
impl ReproductionRunner for CapturedReproducer {
    fn reproduce(&self, archive: &RunArchive) -> io::Result<ReproductionEvidence> {
        if !self.workspace.is_absolute() {
            return Err(io::Error::other("reproduction workspace must be absolute"));
        }
        crate::provenance::verify_reproduction(archive)?;
        let source_handle: serde_json::Value = archive.store.json(&format!(
            "{}/records/handle.json",
            archive.manifest().run_id
        ))?;
        let old_root = PathBuf::from(
            source_handle["workspace"]
                .as_str()
                .ok_or_else(|| io::Error::other("run has no captured execution binding"))?,
        );
        let keys = archive
            .manifest()
            .artifacts
            .keys()
            .filter(|key| {
                (key.starts_with("reproduction/")
                    && !key.starts_with("reproduction/external-inputs/"))
                    || (archive.manifest().kind == "campaign"
                        && key.starts_with("executions/")
                        && key.contains("/reproduction/")
                        && !key.contains("/reproduction/external-inputs/"))
            })
            .cloned()
            .collect::<Vec<_>>();
        let lease = archive.materialize_keys(
            &keys,
            &self.workspace.join("cache"),
            8 * 1024 * 1024 * 1024,
        )?;
        let root = lease.path();
        let input = root.join("reproduction/effective-inputs");
        if !input.is_dir() {
            return Err(io::Error::other(
                "run lacks its frozen execution input tree",
            ));
        }
        let mut bindings = std::collections::BTreeMap::new();
        bindings.insert(old_root.join("execution-input"), input.clone());
        rewrite_json_tree(&input, &bindings, &old_root, root)?;
        let mut comparisons = Vec::new();
        if archive.manifest().kind == "campaign" {
            let path = input.join("campaign.json");
            let mut campaign: serde_json::Value =
                serde_json::from_reader(std::fs::File::open(&path)?).map_err(io::Error::other)?;
            let members = campaign["studies"]
                .as_array_mut()
                .ok_or_else(|| io::Error::other("captured campaign has no ordered studies"))?;
            for member in members {
                let id = member["id"]
                    .as_str()
                    .ok_or_else(|| io::Error::other("invalid captured member"))?
                    .to_owned();
                let record: serde_json::Value = archive.store.json(&format!(
                    "{}/records/member-{id}.json",
                    archive.manifest().run_id
                ))?;
                let child_id = record["handle"]["run_id"]
                    .as_str()
                    .ok_or_else(|| io::Error::other("member lacks a committed run binding"))?;
                let prefix = format!("executions/{id}/{child_id}/");
                let child_root = root.join(&prefix);
                let frozen = child_root.join("reproduction/effective-inputs");
                let child_old = PathBuf::from(
                    record["handle"]["workspace"]
                        .as_str()
                        .ok_or_else(|| io::Error::other("member lacks its recorded workspace"))?,
                );
                let mut child_bindings = std::collections::BTreeMap::new();
                child_bindings.insert(child_old.join("execution-input"), frozen.clone());
                rewrite_json_tree(&frozen, &child_bindings, &child_old, &child_root)?;
                let target = input.join("replay-studies").join(&id);
                std::fs::create_dir_all(&target)?;
                copy_tree(&frozen, &target)?;
                configure_study(
                    &target,
                    &archive.store.location,
                    &self.workspace.join("runs").join(&id),
                    &archive.manifest().run_id,
                    &prefix,
                )?;
                member["input"] = format!("replay-studies/{id}").into();
                member["runner"] = child_root
                    .join("reproduction/software/runner")
                    .to_string_lossy()
                    .into_owned()
                    .into();
                comparisons.push((id, prefix, target));
            }
            atomic_json(&path, &campaign)?;
            configure_campaign(
                &input,
                &archive.store.location,
                &self.workspace.join("runs"),
            )?;
        } else {
            configure_study(
                &input,
                &archive.store.location,
                &self.workspace.join("runs"),
                &archive.manifest().run_id,
                "",
            )?;
            comparisons.push(("study".into(), String::new(), input.clone()));
        }
        let comparisons = comparisons
            .into_iter()
            .map(|(id, prefix, effective)| {
                let (declaration, program) =
                    crate::config::load_verification(&effective).map_err(|e| {
                        io::Error::other(format!("verification declaration for {id}: {e}"))
                    })?;
                Ok((id, prefix, effective, declaration, program))
            })
            .collect::<io::Result<Vec<_>>>()?;
        // The captured runner owns registration discovery; the generic controller
        // never attempts to recompile or dynamically discover scientific Rust code.
        let numerical = crate::provenance::read_environment(
            &root.join("reproduction/environment/numerical.json"),
        )?;
        let mut launcher = Command::new(root.join("reproduction/software/runner"));
        crate::provenance::apply_environment(&mut launcher, &numerical);
        let output = launcher
            .arg("--workflow-start")
            .arg(&input)
            .current_dir(&input)
            .env("LD_LIBRARY_PATH", root.join("reproduction/libraries"))
            .env("PYTHONDONTWRITEBYTECODE", "1")
            .stdin(Stdio::null())
            .output()?;
        if !output.status.success() {
            return Err(io::Error::other(format!(
                "captured replay failed to start: {}",
                String::from_utf8_lossy(&output.stderr)
            )));
        }
        let handle: RunHandle = serde_json::from_slice(&output.stdout).map_err(io::Error::other)?;
        let status = handle.wait()?;
        if status.outcome != crate::protocol::Outcome::Completed {
            return Err(io::Error::other(format!(
                "full captured replay ended {:?}: {}",
                status.outcome,
                status.message.unwrap_or_default()
            )));
        }
        let replay = RunArchive::open(&handle.storage, &handle.run_id)?;
        let mut reports = Vec::new();
        let mut criteria = serde_json::Map::new();
        for (id, reference_prefix, effective, declaration, program) in comparisons {
            let replay_prefix = if archive.manifest().kind == "campaign" {
                let record: serde_json::Value = replay.store.json(&format!(
                    "{}/records/member-{id}.json",
                    replay.manifest().run_id
                ))?;
                format!(
                    "executions/{id}/{}/",
                    record["handle"]["run_id"]
                        .as_str()
                        .ok_or_else(|| io::Error::other("replay member has no run ID"))?
                )
            } else {
                String::new()
            };
            let directory = self
                .workspace
                .join("comparisons")
                .join(&handle.run_id)
                .join(&id);
            std::fs::create_dir_all(&directory)?;
            let reference_path = directory.join("reference.json");
            let replay_path = directory.join("replay.json");
            let criteria_path = directory.join("criteria.json");
            atomic_json(&reference_path, &products(archive, &reference_prefix))?;
            atomic_json(&replay_path, &products(&replay, &replay_prefix))?;
            atomic_json(&criteria_path, &declaration.criteria)?;
            let mut command = Command::new(program.program());
            command
                .args(program.args())
                .envs(program.environment())
                .current_dir(&effective)
                .env("WORKFLOW_REFERENCE_PRODUCTS_PATH", &reference_path)
                .env("WORKFLOW_REPLAY_PRODUCTS_PATH", &replay_path)
                .env("WORKFLOW_COMPARISON_CRITERIA_PATH", &criteria_path)
                .env("LD_LIBRARY_PATH", root.join("reproduction/libraries"))
                .env("OMP_NUM_THREADS", "1")
                .env("OPENBLAS_NUM_THREADS", "1")
                .env("WORKFLOW_THREADS", "1");
            crate::provenance::apply_environment(&mut command, &numerical);
            if let Some(owner) = &archive.maintenance_owner {
                command.env(
                    "WORKFLOW_MAINTENANCE_OWNER",
                    serde_json::json!({"run_id":archive.manifest().run_id,"owner":owner})
                        .to_string(),
                );
            }
            let result = run_comparison(command, &directory, Duration::from_secs(300))?;
            let passed = result["passed"].as_bool().ok_or_else(|| {
                io::Error::other("scientific comparison must return JSON with a boolean 'passed'")
            })?;
            criteria.insert(id.clone(), declaration.criteria);
            reports.push(serde_json::json!({"study":id,"passed":passed,"comparison":result}));
            if !passed {
                return Ok(ReproductionEvidence {
                    criteria: criteria.into(),
                    passed: false,
                    report: serde_json::json!({"replay":handle,"comparisons":reports}),
                });
            }
        }
        // The verification execution is retained as a sealed processed-result run;
        // optional reproduction does not leave an extra full raw dataset behind.
        let replay_seal = crate::seal::execute(
            &handle.storage,
            &handle.run_id,
            &self.workspace.join("maintenance"),
            None,
        )?;
        Ok(ReproductionEvidence {
            criteria: criteria.into(),
            passed: true,
            report: serde_json::json!({"replay":handle,"comparisons":reports,"replay_seal":replay_seal}),
        })
    }
}
fn configure_study(
    input: &Path,
    storage: &StorageLocation,
    workspace: &Path,
    source_id: &str,
    prefix: &str,
) -> io::Result<()> {
    let path = input.join("wf_configs/runtime.json");
    let mut runtime: serde_json::Value =
        serde_json::from_reader(std::fs::File::open(&path)?).map_err(io::Error::other)?;
    runtime["storage"] = serde_json::to_value(storage).map_err(io::Error::other)?;
    runtime["workspace"]["root"] = workspace.to_string_lossy().into_owned().into();
    runtime["interface"] = "headless".into();
    runtime.as_object_mut().unwrap().remove("reuse_from");
    runtime.as_object_mut().unwrap().remove("active_phases");
    if let Some(bindings) = runtime["input_bindings"].as_object_mut() {
        for (name, binding) in bindings {
            *binding = serde_json::json!({"storage":storage,"run_id":source_id,"prefix":format!("{prefix}reproduction/external-inputs/{name}")});
        }
    }
    atomic_json(&path, &runtime)
}
fn configure_campaign(input: &Path, storage: &StorageLocation, workspace: &Path) -> io::Result<()> {
    let path = input.join("runtime.json");
    let mut runtime: serde_json::Value =
        serde_json::from_reader(std::fs::File::open(&path)?).map_err(io::Error::other)?;
    runtime["storage"] = serde_json::to_value(storage).map_err(io::Error::other)?;
    runtime["workspace"]["root"] = workspace.to_string_lossy().into_owned().into();
    runtime["interface"] = "headless".into();
    atomic_json(&path, &runtime)
}
fn rewrite_json_tree(
    root: &Path,
    bindings: &std::collections::BTreeMap<PathBuf, PathBuf>,
    old: &Path,
    new: &Path,
) -> io::Result<()> {
    for entry in std::fs::read_dir(root)? {
        let entry = entry?;
        if entry.file_type()?.is_dir() {
            rewrite_json_tree(&entry.path(), bindings, old, new)?;
        } else if entry.path().extension().is_some_and(|e| e == "json") {
            rewrite_paths(&entry.path(), bindings, old, new)?;
        }
    }
    Ok(())
}
fn products(archive: &RunArchive, prefix: &str) -> serde_json::Value {
    let products=archive.manifest().artifacts.iter().filter(|(key,r)|r.role==ArtifactRole::Processed && key.starts_with(prefix) && !archive.manifest().removed.contains(key)).map(|(key,r)|{
        let relative=key.strip_prefix(prefix).unwrap();let canonical=relative.split('/').filter(|part|crate::protocol::RunId::try_from((*part).to_owned()).is_err()).collect::<Vec<_>>().join("/");
        serde_json::json!({"key":canonical,"artifact":crate::artifact::ArtifactLocator{storage:archive.store.location.clone(),run_id:archive.manifest().run_id.clone(),prefix:key.clone()},"sha256":r.sha256,"bytes":r.bytes})
    }).collect::<Vec<_>>();
    serde_json::json!({"storage":archive.store.location,"run_id":archive.manifest().run_id,"prefix":prefix,"products":products})
}
fn run_comparison(
    mut command: Command,
    directory: &Path,
    timeout: Duration,
) -> io::Result<serde_json::Value> {
    use std::os::unix::process::CommandExt;
    command
        .process_group(0)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = command.spawn()?;
    let guard = crate::workspace::ProcessGuard::new(child.id())?;
    let overflow = Arc::new(AtomicBool::new(false));
    fn drain(
        mut input: impl Read + Send + 'static,
        overflow: Arc<AtomicBool>,
    ) -> std::thread::JoinHandle<io::Result<Vec<u8>>> {
        std::thread::spawn(move || {
            let mut saved = Vec::new();
            let mut buffer = [0; 8192];
            loop {
                let n = input.read(&mut buffer)?;
                if n == 0 {
                    break;
                }
                if saved.len() + n > 8 * 1024 * 1024 {
                    overflow.store(true, Ordering::Release);
                } else {
                    saved.extend_from_slice(&buffer[..n]);
                }
            }
            Ok(saved)
        })
    }
    let stdout = drain(child.stdout.take().unwrap(), overflow.clone());
    let stderr = drain(child.stderr.take().unwrap(), overflow.clone());
    let start = Instant::now();
    let status = loop {
        if let Some(status) = child.try_wait()? {
            break status;
        }
        if start.elapsed() > timeout || overflow.load(Ordering::Acquire) {
            unsafe {
                libc::kill(-(child.id() as i32), libc::SIGKILL);
            }
            let _ = child.kill();
            break child.wait()?;
        }
        std::thread::sleep(Duration::from_millis(20));
    };
    unsafe {
        libc::kill(-(child.id() as i32), libc::SIGKILL);
    }
    drop(guard);
    let stdout = stdout
        .join()
        .map_err(|_| io::Error::other("comparison output reader panicked"))??;
    let stderr = stderr
        .join()
        .map_err(|_| io::Error::other("comparison error reader panicked"))??;
    std::fs::write(directory.join("stdout.json"), &stdout)?;
    std::fs::write(directory.join("stderr.log"), &stderr)?;
    if overflow.load(Ordering::Acquire) {
        return Err(io::Error::other(
            "comparison output exceeded the bounded 8 MiB channel",
        ));
    }
    if !status.success() {
        return Err(io::Error::other(format!(
            "scientific comparison exited {status}: {}",
            String::from_utf8_lossy(&stderr)
        )));
    }
    serde_json::from_slice(&stdout).map_err(io::Error::other)
}