scientific_workflow/lib.rs
1//! Configuration-driven scientific workflow execution.
2//!
3//! An ordinary application defines registered [`ExecutionUnit`]
4//! implementations, writes `wf_configs/study.json`, its declared named
5//! state-schema documents, `wf_configs/runtime.json`, and the central `wf_configs/parameters.json`, then
6//! calls [`run`] with the project root. Workflow infers task
7//! instances, phase membership, identities, output paths, progress boundaries,
8//! recording lifecycle, and execution mechanics.
9//!
10//! # Ordinary use
11//!
12//! ```no_run
13//! use std::path::Path;
14//!
15//! fn main() -> Result<(), scientific_workflow::WorkflowError> {
16//! scientific_workflow::run(Path::new("."))
17//! }
18//! ```
19//!
20//! An execution unit carries its stable manifest key at its implementation:
21//!
22//! ```
23//! use serde::Deserialize;
24//! use scientific_workflow::prelude::*;
25//!
26//! #[derive(Deserialize)]
27//! struct Constants { initial: u64, steps: u64 }
28//!
29//! struct ExampleUnit { state: SystemState, target_iteration: u64 }
30//!
31//! #[scientific_workflow::execution_unit("example")]
32//! impl ExecutionUnit for ExampleUnit {
33//! type Constants = Constants;
34//!
35//! fn preflight(constants: &Constants, _schema: &SystemStateSchema) -> UnitResult<ObservationPlan> {
36//! constants.initial.checked_add(constants.steps)
37//! .ok_or("initial population plus steps exceeds u64")?;
38//! Ok(ObservationPlan::all_fields())
39//! }
40//!
41//! fn initialize(
42//! constants: Constants,
43//! schema: &SystemStateSchema,
44//! _context: &InitializationContext,
45//! ) -> UnitResult<Self> {
46//! let mut state = schema.create_empty_state(StateTime::from_iteration(0));
47//! state.initialize_payload("population", constants.initial)?;
48//! state.initialize_payload("cumulative_births", 0_u64)?;
49//! Ok(Self {
50//! state,
51//! target_iteration: constants.steps,
52//! })
53//! }
54//!
55//! fn member_count(&self) -> usize { 1 }
56//! fn member(&self, index: usize) -> Option<MemberView<'_>> {
57//! (index == 0).then(|| MemberView::new(
58//! "example",
59//! &self.state,
60//! (self.state.time().iteration() >= self.target_iteration)
61//! .then_some(MemberCompletion::without_reason()),
62//! Some(self.target_iteration),
63//! ))
64//! }
65//! fn step(&mut self) -> UnitResult {
66//! let next_time = self.state.time().checked_advance(None)?;
67//! let (population, births) = self.state
68//! .borrow_payloads::<(u64, u64)>(("population", "cumulative_births"))?;
69//! let next_population = population.checked_add(1).ok_or("population exceeds u64")?;
70//! let next_births = births.checked_add(1).ok_or("birth count exceeds u64")?;
71//! let (population, births) = self.state
72//! .borrow_payloads_mut::<(u64, u64)>(("population", "cumulative_births"))?;
73//! *population = next_population;
74//! *births = next_births;
75//! self.state.replace_time(next_time);
76//! Ok(())
77//! }
78//! }
79//! ```
80//!
81//! # Ownership boundaries
82//!
83//! - [`config`] alone reads and parses project JSON and supplies typed execution-unit
84//! constants.
85//! - [`study`] composes parsed declarations, state semantics, and compiled execution-unit
86//! registrations into immutable, output-free intent.
87//! - The private runtime consumes a completed StudyPlan and owns active execution/output.
88//! - [`task`] owns execution-unit contracts and automatic lifecycle observation; the crate root re-exports ordinary authoring types.
89//! - [`state`] owns canonical scientific state and schema.
90//! - [`observation`] owns scientific observation meaning, not persistence mechanics.
91//! - [`persistence`] owns automatic durable output and verified reading.
92//! - The engine journals runtime facts and serves the versioned local socket.
93//! Clients and the independent dashboard consume this protocol.
94//! - [`WorkflowError`] composes complete-workflow StudyPlan/Runtime failures.
95//!
96//! The crate-level [`run`] facade performs the sole ordinary transition from
97//! project root to StudyPlan to Runtime. `StudyPlan` is the ultimate coordinator of
98//! declared intent; runtime is the ultimate coordinator of active execution.
99//! Inspection and embedding integrations import APIs directly from their
100//! owning module roots. [`prelude`] contains only ordinary unit-authoring APIs
101//! and crate conveniences.
102//!
103//! Persistence write construction and output allocation are internal and are
104//! not available to execution-unit authors.
105//!
106//! This crate is pre-1.0 test software and may make coordinated API changes.
107
108#![deny(missing_docs, rustdoc::broken_intra_doc_links)]
109
110extern crate self as scientific_workflow;
111
112#[cfg(test)]
113mod composition;
114mod error;
115#[cfg(test)]
116mod test_support;
117
118pub mod config;
119pub mod observation;
120pub mod persistence;
121pub mod prelude;
122mod runtime;
123pub use runtime::RuntimeError;
124pub mod artifact;
125pub mod campaign;
126mod engine;
127pub mod provenance;
128pub mod registry;
129pub mod seal;
130pub mod state;
131mod storage;
132pub mod study;
133pub mod task;
134mod workspace;
135pub use engine::RunHandle;
136
137pub use error::WorkflowError;
138pub use scientific_workflow_macros::execution_unit;
139pub use task::{
140 ExecutionUnit, InitializationContext, MemberCompletion, MemberView, SeedError, UnitResult,
141};
142
143/// Starts an independent engine for the input folder after complete validation and capture.
144///
145/// The explicit runtime interface selects headless launch or a separate dashboard.
146/// `--wait` waits for the actual terminal outcome; ordinary launch returns after
147/// socket readiness. Model-linked runners also accept `--workflow-check INPUT`
148/// and `--workflow-start INPUT`. Authored inputs remain unchanged.
149pub fn run(project_root: &std::path::Path) -> Result<(), WorkflowError> {
150 engine::application(project_root)
151}
152
153/// Validates and expands a study without executing tasks or creating output.
154pub fn check(input: &std::path::Path) -> Result<CheckReport, WorkflowError> {
155 if input.join("campaign.json").is_file() {
156 let plan = campaign::CampaignPlan::load(input)?;
157 plan.check()?;
158 return Ok(CheckReport {
159 kind: "campaign".into(),
160 studies: plan.studies().map(str::to_owned).collect(),
161 tasks: None,
162 threads: None,
163 });
164 }
165 let study = study::StudyPlan::load(input)?;
166 runtime::check_prerequisites(&study)?;
167 Ok(CheckReport {
168 kind: "study".into(),
169 studies: vec!["study".into()],
170 tasks: Some(study.plan_summary().phases().map(|p| p.tasks().len()).sum()),
171 threads: Some(study.threads()),
172 })
173}
174/// Validation-only summary. No execution or destination allocation occurs.
175#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
176pub struct CheckReport {
177 /// StudyPlan or campaign.
178 pub kind: String,
179 /// Validated member identifiers, in declaration order.
180 pub studies: Vec<String>,
181 /// Expanded standalone task count.
182 pub tasks: Option<usize>,
183 /// Standalone budget; campaigns have no shared compute budget.
184 pub threads: Option<usize>,
185}
186
187/// Captures inputs and starts an independent engine, returning after socket readiness.
188pub fn start(input: &std::path::Path) -> Result<RunHandle, WorkflowError> {
189 engine::start(input)
190}
191
192/// Opens an authoritative run for verified artifact access.
193pub fn open_run(
194 location: &artifact::StorageLocation,
195 id: &str,
196) -> std::io::Result<artifact::RunArchive> {
197 artifact::RunArchive::open(location, id)
198}
199
200/// Implementation details used by Workflow's declaration macros.
201///
202/// This namespace is public only because procedural macro expansion occurs in
203/// the application crate. It is not a supported application API.
204#[doc(hidden)]
205pub mod __private {
206 pub use crate::task::ExecutionUnitRegistration;
207 pub use inventory;
208}
209
210/// Applies guarded sealing after verifying preservation evidence. Optional replay
211/// uses an explicitly supplied scientific reproduction service.
212pub fn seal_run(
213 location: &artifact::StorageLocation,
214 id: &str,
215 workspace: &std::path::Path,
216 reproducer: Option<&dyn seal::ReproductionRunner>,
217) -> std::io::Result<seal::SealReport> {
218 seal::execute(location, id, workspace, reproducer)
219}
220
221/// Executes the complete captured graph and applies study-defined comparisons.
222/// The verification run is itself retained and sealed after a successful comparison.
223pub fn reproduce_run(
224 location: &artifact::StorageLocation,
225 id: &str,
226 workspace: &std::path::Path,
227) -> std::io::Result<seal::ReproductionEvidence> {
228 use seal::ReproductionRunner;
229 engine::CapturedReproducer {
230 workspace: workspace.into(),
231 }
232 .reproduce(&open_run(location, id)?)
233}
234
235/// Seals after an explicitly requested full captured reproduction and scientific comparison.
236pub fn seal_run_with_reproduction(
237 location: &artifact::StorageLocation,
238 id: &str,
239 workspace: &std::path::Path,
240) -> std::io::Result<seal::SealReport> {
241 let runner = engine::CapturedReproducer {
242 workspace: workspace.join("reproduction-check"),
243 };
244 seal::execute(location, id, workspace, Some(&runner))
245}