Skip to main content

scientific_workflow/study/
plan.rs

1//! Immutable study, phase, and task views.
2
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::time::Duration;
6
7use crate::config::{
8    Config, ConfigSnapshot, FailurePolicy, PersistenceSpecification, ProjectSpecification,
9    ReplicatePolicy, StudyManifest,
10};
11use crate::persistence::PersistencePlan;
12use crate::task::{
13    ExecutionUnitCatalog, ExecutionUnitTaskProvenance, Task, TaskDefinition, TaskKind,
14};
15use crate::ui::UiPlan;
16
17use super::compilation;
18use super::error::StudyError;
19
20/// A complete immutable and effect-free execution declaration.
21#[derive(Clone)]
22pub struct Study {
23    inner: Arc<StudyInner>,
24}
25
26impl Study {
27    /// Loads project declarations and binds all linked `#[execution_unit]` registrations.
28    ///
29    /// This performs complete preflight without creating output or initializing
30    /// an execution unit. Config is the only file reader and JSON parser.
31    pub fn load(project_root: &Path) -> Result<Self, StudyError> {
32        let project = ProjectSpecification::load(project_root)?;
33        let catalog = ExecutionUnitCatalog::discovered()?;
34        compilation::compile(project, &catalog)
35    }
36
37    pub(crate) fn from_parts(project: ProjectSpecification, phases: Box<[StudyPhase]>) -> Self {
38        let project_root = project.project_root().to_path_buf();
39        let config = project.config().clone();
40        let output_root = project_root.join("output");
41        let manifest: StudyManifest = *project.manifest();
42        let replicate_policy = manifest.replicate_policy();
43        let master_seed = manifest.master_seed();
44        let persistence: PersistenceSpecification = manifest.persistence();
45        let persistence_plan = PersistencePlan::local(
46            persistence.chunk_target_bytes(),
47            persistence.queue_capacity_bytes(),
48        );
49        let ui_plan = UiPlan::automatic();
50        Self {
51            inner: Arc::new(StudyInner {
52                project_root,
53                config,
54                phases,
55                output_root,
56                master_seed,
57                replicate_policy,
58                persistence_plan,
59                ui_plan,
60            }),
61        }
62    }
63
64    /// Returns the canonical project root loaded by config.
65    pub fn project_root(&self) -> &Path {
66        &self.inner.project_root
67    }
68
69    /// Returns the inferred output root, `<project-root>/output`.
70    pub fn output_root(&self) -> &Path {
71        &self.inner.output_root
72    }
73
74    /// Returns the frozen language-neutral configuration supplied to programs.
75    pub(crate) fn config_snapshot(&self) -> ConfigSnapshot {
76        self.inner.config.snapshot()
77    }
78
79    /// Returns immutable phases in manifest declaration order.
80    pub(crate) fn phases(&self) -> &[StudyPhase] {
81        &self.inner.phases
82    }
83
84    /// Returns the effective replicate policy parsed from `wf_configs/study.json`.
85    pub(crate) fn replicate_policy(&self) -> ReplicatePolicy {
86        self.inner.replicate_policy
87    }
88
89    /// Returns the study-wide optional deterministic seed.
90    pub(crate) fn master_seed(&self) -> Option<u64> {
91        self.inner.master_seed
92    }
93
94    /// Returns the immutable effective persistence plan compiled from
95    /// `wf_configs/study.json`.
96    pub(crate) fn persistence_plan(&self) -> PersistencePlan {
97        self.inner.persistence_plan
98    }
99
100    /// Returns the immutable inferred UI plan.
101    pub(crate) fn ui_plan(&self) -> UiPlan {
102        self.inner.ui_plan
103    }
104}
105
106impl std::fmt::Debug for Study {
107    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        formatter
109            .debug_struct("Study")
110            .field("project_root", &self.project_root())
111            .field("output_root", &self.output_root())
112            .field("config", &self.inner.config)
113            .field("persistence", &self.persistence_plan())
114            .field("ui", &self.ui_plan())
115            .field("phases", &self.phases().len())
116            .finish_non_exhaustive()
117    }
118}
119
120struct StudyInner {
121    project_root: PathBuf,
122    config: Config,
123    phases: Box<[StudyPhase]>,
124    output_root: PathBuf,
125    master_seed: Option<u64>,
126    replicate_policy: ReplicatePolicy,
127    persistence_plan: PersistencePlan,
128    ui_plan: UiPlan,
129}
130
131/// One immutable execution phase compiled from the study manifest.
132#[derive(Clone, Debug)]
133pub(crate) struct StudyPhase {
134    pub(crate) name: Box<str>,
135    pub(crate) dependencies: Box<[Box<str>]>,
136    pub(crate) tasks: Box<[StudyTask]>,
137    pub(crate) max_concurrency: usize,
138    pub(crate) start_interval: Duration,
139    pub(crate) timeout: Option<Duration>,
140    pub(crate) failure_policy: FailurePolicy,
141}
142
143impl StudyPhase {
144    /// Returns the stable phase key from `wf_configs/study.json`.
145    pub(crate) fn name(&self) -> &str {
146        &self.name
147    }
148
149    /// Iterates dependency keys in declaration order.
150    pub(crate) fn dependencies(&self) -> impl ExactSizeIterator<Item = &str> {
151        self.dependencies.iter().map(Box::as_ref)
152    }
153
154    /// Returns bound execution-unit/program invocations in deterministic plan order.
155    pub(crate) fn tasks(&self) -> &[StudyTask] {
156        &self.tasks
157    }
158
159    /// Returns the positive effective concurrency bound.
160    pub(crate) const fn max_concurrency(&self) -> usize {
161        self.max_concurrency
162    }
163
164    /// Returns the effective interval between task admissions.
165    pub(crate) const fn start_interval(&self) -> Duration {
166        self.start_interval
167    }
168
169    /// Returns the optional phase-wide timeout.
170    pub(crate) const fn timeout(&self) -> Option<Duration> {
171        self.timeout
172    }
173
174    /// Returns the effective sibling failure policy.
175    pub(crate) const fn failure_policy(&self) -> FailurePolicy {
176        self.failure_policy
177    }
178}
179
180/// One generic execution-unit or program task compiled from project configuration.
181#[derive(Clone)]
182pub(crate) struct StudyTask {
183    pub(crate) identity: Box<str>,
184    pub(crate) label: Box<str>,
185    pub(crate) output_ordinal: u64,
186    pub(crate) task: Task,
187}
188
189impl StudyTask {
190    /// Returns the inferred stable identity within this study plan.
191    pub(crate) fn identity(&self) -> &str {
192        &self.identity
193    }
194
195    /// Returns the inferred human-readable label.
196    pub(crate) fn label(&self) -> &str {
197        &self.label
198    }
199
200    pub(crate) fn kind(&self) -> TaskKind {
201        self.task.kind()
202    }
203
204    pub(crate) fn kind_name(&self) -> &'static str {
205        self.task.kind_name()
206    }
207
208    /// Returns the registration key when this is an execution-unit task.
209    pub(crate) fn execution_unit(&self) -> Option<&str> {
210        self.task.execution_unit()
211    }
212
213    /// Returns the generic task subject used in lifecycle presentation.
214    pub(crate) fn subject(&self) -> &str {
215        self.task.subject()
216    }
217
218    /// Returns the optional task-specific cooperative timeout.
219    pub(crate) fn timeout(&self) -> Option<Duration> {
220        self.task.timeout()
221    }
222
223    pub(crate) fn output_ordinal(&self) -> u64 {
224        self.output_ordinal
225    }
226
227    pub(crate) fn definition(&self) -> &dyn TaskDefinition {
228        &self.task
229    }
230
231    pub(crate) fn execution_unit_provenance(&self) -> Option<ExecutionUnitTaskProvenance<'_>> {
232        self.task.execution_unit_provenance()
233    }
234
235    pub(crate) fn program_path(&self) -> Option<&Path> {
236        self.task.program_path()
237    }
238
239    pub(crate) fn python_script(&self) -> Option<&Path> {
240        self.task.python_script()
241    }
242}
243
244impl std::fmt::Debug for StudyTask {
245    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246        formatter
247            .debug_struct("StudyTask")
248            .field("identity", &self.identity())
249            .field("label", &self.label())
250            .field("kind", &self.kind())
251            .field("subject", &self.subject())
252            .finish_non_exhaustive()
253    }
254}