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