Skip to main content

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, 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//! - [`runtime`] consumes a completed Study 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//! - Runtime owns lifecycle facts; the private UI subsystem implements their
93//!   automatically composed terminal presentation.
94//! - [`WorkflowError`] composes complete-workflow Study/Runtime failures.
95//!
96//! The crate-level [`run`] facade performs the sole ordinary transition from
97//! project root to Study to Runtime. `Study` 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
112mod composition;
113mod error;
114
115pub mod config;
116pub mod observation;
117pub mod persistence;
118pub mod prelude;
119pub mod runtime;
120pub mod state;
121pub mod study;
122pub mod task;
123mod ui;
124
125pub use error::WorkflowError;
126pub use scientific_workflow_macros::execution_unit;
127pub use task::{
128    ExecutionUnit, InitializationContext, MemberCompletion, MemberView, SeedError, UnitResult,
129};
130
131/// Loads, preflights, and executes the Workflow project rooted at
132/// `project_root`.
133///
134/// This is the sole ordinary application entry point. Project loading and
135/// Study compilation finish before Runtime receives the validated immutable
136/// Study. Successful completion returns `()`; embedding integrations can load
137/// a [`study::Study`] and call [`runtime::execute`] to retain a read-only run summary.
138///
139/// Recognizes `--clean` in process arguments before an optional `--` delimiter.
140/// After preflight, this clears `<project_root>/output` while holding exclusive
141/// project ownership. Symlink output roots, active runs, and reuse sources in
142/// that directory are rejected. Other application arguments are ignored.
143/// Embedding through [`runtime::execute`] never reads process arguments.
144/// Execution requires terminal stdin and stderr for the dashboard; use screen
145/// or tmux. A missing terminal fails before output creation or cleanup.
146pub fn run(project_root: &std::path::Path) -> Result<(), WorkflowError> {
147    let study = study::Study::load(project_root)?;
148    let clean = std::env::args_os()
149        .skip(1)
150        .take_while(|arg| arg != "--")
151        .any(|arg| arg == "--clean");
152    composition::execute_options(study, clean)?;
153    Ok(())
154}
155
156/// Implementation details used by Workflow's declaration macros.
157///
158/// This namespace is public only because procedural macro expansion occurs in
159/// the application crate. It is not a supported application API.
160#[doc(hidden)]
161pub mod __private {
162    pub use crate::task::ExecutionUnitRegistration;
163    pub use inventory;
164}