scientific-workflow 0.17.0

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
//! Configuration-driven scientific workflow execution.
//!
//! An ordinary application defines registered [`ExecutionUnit`]
//! implementations, writes `wf_configs/study.json`, its declared named
//! state-schema documents, `wf_configs/runtime.json`, and the central `wf_configs/parameters.json`, then
//! calls [`run`] with the project root. Workflow infers task
//! instances, phase membership, identities, output paths, progress boundaries,
//! recording lifecycle, and execution mechanics.
//!
//! # Ordinary use
//!
//! ```no_run
//! use std::path::Path;
//!
//! fn main() -> Result<(), scientific_workflow::WorkflowError> {
//!     scientific_workflow::run(Path::new("."))
//! }
//! ```
//!
//! An execution unit carries its stable manifest key at its implementation:
//!
//! ```
//! use serde::Deserialize;
//! use scientific_workflow::prelude::*;
//!
//! #[derive(Deserialize)]
//! struct Constants { initial: u64, steps: u64 }
//!
//! struct ExampleUnit { state: SystemState, target_iteration: u64 }
//!
//! #[scientific_workflow::execution_unit("example")]
//! impl ExecutionUnit for ExampleUnit {
//!     type Constants = Constants;
//!
//!     fn preflight(constants: &Constants, _schema: &SystemStateSchema) -> UnitResult<ObservationPlan> {
//!         constants.initial.checked_add(constants.steps)
//!             .ok_or("initial population plus steps exceeds u64")?;
//!         Ok(ObservationPlan::all_fields())
//!     }
//!
//!     fn initialize(
//!         constants: Constants,
//!         schema: &SystemStateSchema,
//!         _context: &InitializationContext,
//!     ) -> UnitResult<Self> {
//!         let mut state = schema.create_empty_state(StateTime::from_iteration(0));
//!         state.initialize_payload("population", constants.initial)?;
//!         state.initialize_payload("cumulative_births", 0_u64)?;
//!         Ok(Self {
//!             state,
//!             target_iteration: constants.steps,
//!         })
//!     }
//!
//!     fn member_count(&self) -> usize { 1 }
//!     fn member(&self, index: usize) -> Option<MemberView<'_>> {
//!         (index == 0).then(|| MemberView::new(
//!             "example",
//!             &self.state,
//!             (self.state.time().iteration() >= self.target_iteration)
//!                 .then_some(MemberCompletion::without_reason()),
//!             Some(self.target_iteration),
//!         ))
//!     }
//!     fn step(&mut self) -> UnitResult {
//!         let next_time = self.state.time().checked_advance(None)?;
//!         let (population, births) = self.state
//!             .borrow_payloads::<(u64, u64)>(("population", "cumulative_births"))?;
//!         let next_population = population.checked_add(1).ok_or("population exceeds u64")?;
//!         let next_births = births.checked_add(1).ok_or("birth count exceeds u64")?;
//!         let (population, births) = self.state
//!             .borrow_payloads_mut::<(u64, u64)>(("population", "cumulative_births"))?;
//!         *population = next_population;
//!         *births = next_births;
//!         self.state.replace_time(next_time);
//!         Ok(())
//!     }
//! }
//! ```
//!
//! # Ownership boundaries
//!
//! - [`config`] alone reads and parses project JSON and supplies typed execution-unit
//!   constants.
//! - [`study`] composes parsed declarations, state semantics, and compiled execution-unit
//!   registrations into immutable, output-free intent.
//! - The private runtime consumes a completed StudyPlan and owns active execution/output.
//! - [`task`] owns execution-unit contracts and automatic lifecycle observation; the crate root re-exports ordinary authoring types.
//! - [`state`] owns canonical scientific state and schema.
//! - [`observation`] owns scientific observation meaning, not persistence mechanics.
//! - [`persistence`] owns automatic durable output and verified reading.
//! - The engine journals runtime facts and serves the versioned local socket.
//!   Clients and the independent dashboard consume this protocol.
//! - [`WorkflowError`] composes complete-workflow StudyPlan/Runtime failures.
//!
//! The crate-level [`run`] facade performs the sole ordinary transition from
//! project root to StudyPlan to Runtime. `StudyPlan` is the ultimate coordinator of
//! declared intent; runtime is the ultimate coordinator of active execution.
//! Inspection and embedding integrations import APIs directly from their
//! owning module roots. [`prelude`] contains only ordinary unit-authoring APIs
//! and crate conveniences.
//!
//! Persistence write construction and output allocation are internal and are
//! not available to execution-unit authors.
//!
//! This crate is pre-1.0 test software and may make coordinated API changes.

#![deny(missing_docs, rustdoc::broken_intra_doc_links)]

extern crate self as scientific_workflow;

#[cfg(test)]
mod composition;
mod error;
#[cfg(test)]
mod test_support;

pub mod config;
pub mod observation;
pub mod persistence;
pub mod prelude;
mod runtime;
pub use runtime::RuntimeError;
pub mod artifact;
pub mod campaign;
mod engine;
pub mod provenance;
pub mod registry;
pub mod seal;
pub mod state;
mod storage;
pub mod study;
pub mod task;
mod workspace;
pub use engine::RunHandle;

pub use error::WorkflowError;
pub use scientific_workflow_macros::execution_unit;
pub use task::{
    ExecutionUnit, InitializationContext, MemberCompletion, MemberView, SeedError, UnitResult,
};

/// Starts an independent engine for the input folder after complete validation and capture.
///
/// The explicit runtime interface selects headless launch or a separate dashboard.
/// `--wait` waits for the actual terminal outcome; ordinary launch returns after
/// socket readiness. Model-linked runners also accept `--workflow-check INPUT`
/// and `--workflow-start INPUT`. Authored inputs remain unchanged.
pub fn run(project_root: &std::path::Path) -> Result<(), WorkflowError> {
    engine::application(project_root)
}

/// Validates and expands a study without executing tasks or creating output.
pub fn check(input: &std::path::Path) -> Result<CheckReport, WorkflowError> {
    if input.join("campaign.json").is_file() {
        let plan = campaign::CampaignPlan::load(input)?;
        plan.check()?;
        return Ok(CheckReport {
            kind: "campaign".into(),
            studies: plan.studies().map(str::to_owned).collect(),
            tasks: None,
            threads: None,
        });
    }
    let study = study::StudyPlan::load(input)?;
    runtime::check_prerequisites(&study)?;
    Ok(CheckReport {
        kind: "study".into(),
        studies: vec!["study".into()],
        tasks: Some(study.plan_summary().phases().map(|p| p.tasks().len()).sum()),
        threads: Some(study.threads()),
    })
}
/// Validation-only summary. No execution or destination allocation occurs.
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct CheckReport {
    /// StudyPlan or campaign.
    pub kind: String,
    /// Validated member identifiers, in declaration order.
    pub studies: Vec<String>,
    /// Expanded standalone task count.
    pub tasks: Option<usize>,
    /// Standalone budget; campaigns have no shared compute budget.
    pub threads: Option<usize>,
}

/// Captures inputs and starts an independent engine, returning after socket readiness.
pub fn start(input: &std::path::Path) -> Result<RunHandle, WorkflowError> {
    engine::start(input)
}

/// Opens an authoritative run for verified artifact access.
pub fn open_run(
    location: &artifact::StorageLocation,
    id: &str,
) -> std::io::Result<artifact::RunArchive> {
    artifact::RunArchive::open(location, id)
}

/// Implementation details used by Workflow's declaration macros.
///
/// This namespace is public only because procedural macro expansion occurs in
/// the application crate. It is not a supported application API.
#[doc(hidden)]
pub mod __private {
    pub use crate::task::ExecutionUnitRegistration;
    pub use inventory;
}

/// Applies guarded sealing after verifying preservation evidence. Optional replay
/// uses an explicitly supplied scientific reproduction service.
pub fn seal_run(
    location: &artifact::StorageLocation,
    id: &str,
    workspace: &std::path::Path,
    reproducer: Option<&dyn seal::ReproductionRunner>,
) -> std::io::Result<seal::SealReport> {
    seal::execute(location, id, workspace, reproducer)
}

/// Executes the complete captured graph and applies study-defined comparisons.
/// The verification run is itself retained and sealed after a successful comparison.
pub fn reproduce_run(
    location: &artifact::StorageLocation,
    id: &str,
    workspace: &std::path::Path,
) -> std::io::Result<seal::ReproductionEvidence> {
    use seal::ReproductionRunner;
    engine::CapturedReproducer {
        workspace: workspace.into(),
    }
    .reproduce(&open_run(location, id)?)
}

/// Seals after an explicitly requested full captured reproduction and scientific comparison.
pub fn seal_run_with_reproduction(
    location: &artifact::StorageLocation,
    id: &str,
    workspace: &std::path::Path,
) -> std::io::Result<seal::SealReport> {
    let runner = engine::CapturedReproducer {
        workspace: workspace.join("reproduction-check"),
    };
    seal::execute(location, id, workspace, Some(&runner))
}