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 threads = manifest.threads();
43        let replicate_policy = manifest.replicate_policy();
44        let master_seed = manifest.master_seed();
45        let persistence: PersistenceSpecification = manifest.persistence();
46        let persistence_plan = PersistencePlan::local(
47            persistence.chunk_target_bytes(),
48            persistence.queue_capacity_bytes(),
49        );
50        let ui_plan = UiPlan::automatic();
51        Self {
52            inner: Arc::new(StudyInner {
53                project_root,
54                config,
55                phases,
56                output_root,
57                threads,
58                master_seed,
59                replicate_policy,
60                persistence_plan,
61                ui_plan,
62            }),
63        }
64    }
65
66    /// Returns the canonical project root loaded by config.
67    pub fn project_root(&self) -> &Path {
68        &self.inner.project_root
69    }
70
71    /// Returns the inferred output root, `<project-root>/output`.
72    pub fn output_root(&self) -> &Path {
73        &self.inner.output_root
74    }
75
76    /// Returns the required study-wide compute worker count.
77    pub fn threads(&self) -> usize {
78        self.inner.threads
79    }
80
81    /// Returns the frozen language-neutral configuration supplied to programs.
82    pub(crate) fn config_snapshot(&self) -> ConfigSnapshot {
83        self.inner.config.snapshot()
84    }
85
86    /// Returns immutable phases in manifest declaration order.
87    pub(crate) fn phases(&self) -> &[StudyPhase] {
88        &self.inner.phases
89    }
90
91    /// Returns the effective replicate policy parsed from `wf_configs/study.json`.
92    pub(crate) fn replicate_policy(&self) -> ReplicatePolicy {
93        self.inner.replicate_policy
94    }
95
96    /// Returns the study-wide optional deterministic seed.
97    pub(crate) fn master_seed(&self) -> Option<u64> {
98        self.inner.master_seed
99    }
100
101    /// Returns the immutable effective persistence plan compiled from
102    /// `wf_configs/study.json`.
103    pub(crate) fn persistence_plan(&self) -> PersistencePlan {
104        self.inner.persistence_plan
105    }
106
107    /// Returns the immutable inferred UI plan.
108    pub(crate) fn ui_plan(&self) -> UiPlan {
109        self.inner.ui_plan
110    }
111}
112
113impl std::fmt::Debug for Study {
114    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115        formatter
116            .debug_struct("Study")
117            .field("project_root", &self.project_root())
118            .field("output_root", &self.output_root())
119            .field("threads", &self.threads())
120            .field("config", &self.inner.config)
121            .field("persistence", &self.persistence_plan())
122            .field("ui", &self.ui_plan())
123            .field("phases", &self.phases().len())
124            .finish_non_exhaustive()
125    }
126}
127
128struct StudyInner {
129    project_root: PathBuf,
130    config: Config,
131    phases: Box<[StudyPhase]>,
132    output_root: PathBuf,
133    threads: usize,
134    master_seed: Option<u64>,
135    replicate_policy: ReplicatePolicy,
136    persistence_plan: PersistencePlan,
137    ui_plan: UiPlan,
138}
139
140/// One immutable execution phase compiled from the study manifest.
141#[derive(Clone, Debug)]
142pub(crate) struct StudyPhase {
143    pub(crate) name: Box<str>,
144    pub(crate) dependencies: Box<[Box<str>]>,
145    pub(crate) tasks: Box<[StudyTask]>,
146    pub(crate) max_concurrency: usize,
147    pub(crate) start_interval: Duration,
148    pub(crate) timeout: Option<Duration>,
149    pub(crate) failure_policy: FailurePolicy,
150}
151
152impl StudyPhase {
153    /// Returns the stable phase key from `wf_configs/study.json`.
154    pub(crate) fn name(&self) -> &str {
155        &self.name
156    }
157
158    /// Iterates dependency keys in declaration order.
159    pub(crate) fn dependencies(&self) -> impl ExactSizeIterator<Item = &str> {
160        self.dependencies.iter().map(Box::as_ref)
161    }
162
163    /// Returns bound execution-unit/program invocations in deterministic plan order.
164    pub(crate) fn tasks(&self) -> &[StudyTask] {
165        &self.tasks
166    }
167
168    /// Returns the positive effective concurrency bound.
169    pub(crate) const fn max_concurrency(&self) -> usize {
170        self.max_concurrency
171    }
172
173    /// Returns the effective interval between task admissions.
174    pub(crate) const fn start_interval(&self) -> Duration {
175        self.start_interval
176    }
177
178    /// Returns the optional phase-wide timeout.
179    pub(crate) const fn timeout(&self) -> Option<Duration> {
180        self.timeout
181    }
182
183    /// Returns the effective sibling failure policy.
184    pub(crate) const fn failure_policy(&self) -> FailurePolicy {
185        self.failure_policy
186    }
187}
188
189/// One generic execution-unit or program task compiled from project configuration.
190#[derive(Clone)]
191pub(crate) struct StudyTask {
192    pub(crate) identity: Box<str>,
193    pub(crate) label: Box<str>,
194    pub(crate) output_ordinal: u64,
195    pub(crate) task: Task,
196}
197
198impl StudyTask {
199    /// Returns the inferred stable identity within this study plan.
200    pub(crate) fn identity(&self) -> &str {
201        &self.identity
202    }
203
204    /// Returns the inferred human-readable label.
205    pub(crate) fn label(&self) -> &str {
206        &self.label
207    }
208
209    pub(crate) fn kind(&self) -> TaskKind {
210        self.task.kind()
211    }
212
213    pub(crate) fn kind_name(&self) -> &'static str {
214        self.task.kind_name()
215    }
216
217    /// Returns the registration key when this is an execution-unit task.
218    pub(crate) fn execution_unit(&self) -> Option<&str> {
219        self.task.execution_unit()
220    }
221
222    /// Returns the generic task subject used in lifecycle presentation.
223    pub(crate) fn subject(&self) -> &str {
224        self.task.subject()
225    }
226
227    /// Returns the optional task-specific cooperative timeout.
228    pub(crate) fn timeout(&self) -> Option<Duration> {
229        self.task.timeout()
230    }
231
232    pub(crate) fn output_ordinal(&self) -> u64 {
233        self.output_ordinal
234    }
235
236    pub(crate) fn definition(&self) -> &dyn TaskDefinition {
237        &self.task
238    }
239
240    pub(crate) fn execution_unit_provenance(&self) -> Option<ExecutionUnitTaskProvenance<'_>> {
241        self.task.execution_unit_provenance()
242    }
243
244    pub(crate) fn program_path(&self) -> Option<&Path> {
245        self.task.program_path()
246    }
247
248    pub(crate) fn python_script(&self) -> Option<&Path> {
249        self.task.python_script()
250    }
251
252    pub(crate) fn program_seed_purpose(&self) -> Option<&str> {
253        self.task.program_seed_purpose()
254    }
255}
256
257impl std::fmt::Debug for StudyTask {
258    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
259        formatter
260            .debug_struct("StudyTask")
261            .field("identity", &self.identity())
262            .field("label", &self.label())
263            .field("kind", &self.kind())
264            .field("subject", &self.subject())
265            .finish_non_exhaustive()
266    }
267}