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