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, ReplicateScheduling, StudyManifest,
10};
11use crate::persistence::PersistencePlan;
12use crate::task::{
13    ExecutionUnitCatalog, ExecutionUnitTaskProvenance, Task, TaskDefinition, TaskKind,
14};
15
16use super::compilation;
17use super::error::StudyError;
18
19/// A complete immutable and effect-free execution declaration.
20#[derive(Clone)]
21pub struct Study {
22    inner: Arc<StudyInner>,
23}
24
25impl Study {
26    /// Loads project declarations and binds all linked `#[execution_unit]` registrations.
27    ///
28    /// This performs complete preflight without creating output or initializing
29    /// an execution unit. Config is the only file reader and JSON parser.
30    pub fn load(project_root: &Path) -> Result<Self, StudyError> {
31        let project = ProjectSpecification::load(project_root)?;
32        let catalog = ExecutionUnitCatalog::discovered()?;
33        compilation::compile(project, &catalog)
34    }
35
36    pub(crate) fn from_parts(project: ProjectSpecification, phases: Box<[StudyPhase]>) -> Self {
37        let project_root = project.project_root().to_path_buf();
38        let config = project.config().clone();
39        let output_root = project_root.join("output");
40        let manifest: StudyManifest = *project.manifest();
41        let workflow_schema = manifest.workflow_schema();
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        Self {
51            inner: Arc::new(StudyInner {
52                project_root,
53                config,
54                phases,
55                output_root,
56                workflow_schema,
57                threads,
58                master_seed,
59                replicate_policy,
60                persistence_plan,
61            }),
62        }
63    }
64
65    /// Returns the canonical project root loaded by config.
66    pub fn project_root(&self) -> &Path {
67        &self.inner.project_root
68    }
69
70    /// Returns the inferred output root, `<project-root>/output`.
71    pub fn output_root(&self) -> &Path {
72        &self.inner.output_root
73    }
74
75    /// Returns the required study-wide global compute budget.
76    pub fn threads(&self) -> usize {
77        self.inner.threads
78    }
79
80    /// Returns a read-only view of the fully compiled deterministic plan.
81    ///
82    /// The view borrows this Study and exposes planning facts only. It does not
83    /// expose constants payloads, executable task handles, or mutable policy.
84    pub fn plan_summary(&self) -> PlanSummary<'_> {
85        PlanSummary { study: self }
86    }
87
88    /// Returns the frozen language-neutral configuration supplied to programs.
89    pub(crate) fn config_snapshot(&self) -> ConfigSnapshot {
90        self.inner.config.snapshot()
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 `wf_configs/study.json`.
99    pub(crate) fn replicate_policy(&self) -> ReplicatePolicy {
100        self.inner.replicate_policy
101    }
102
103    /// Returns the study-wide optional deterministic seed.
104    pub(crate) fn master_seed(&self) -> Option<u64> {
105        self.inner.master_seed
106    }
107
108    /// Returns the immutable effective persistence plan compiled from
109    /// `wf_configs/study.json`.
110    pub(crate) fn persistence_plan(&self) -> PersistencePlan {
111        self.inner.persistence_plan
112    }
113}
114
115impl std::fmt::Debug for Study {
116    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        formatter
118            .debug_struct("Study")
119            .field("project_root", &self.project_root())
120            .field("output_root", &self.output_root())
121            .field("threads", &self.threads())
122            .field("config", &self.inner.config)
123            .field("persistence", &self.persistence_plan())
124            .field("phases", &self.phases().len())
125            .finish_non_exhaustive()
126    }
127}
128
129struct StudyInner {
130    project_root: PathBuf,
131    config: Config,
132    phases: Box<[StudyPhase]>,
133    output_root: PathBuf,
134    workflow_schema: u64,
135    threads: usize,
136    master_seed: Option<u64>,
137    replicate_policy: ReplicatePolicy,
138    persistence_plan: PersistencePlan,
139}
140
141/// A read-only view of one fully compiled [`Study`].
142#[derive(Clone, Copy)]
143pub struct PlanSummary<'a> {
144    study: &'a Study,
145}
146
147impl std::fmt::Debug for PlanSummary<'_> {
148    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        formatter
150            .debug_struct("PlanSummary")
151            .field("workflow_schema", &self.workflow_schema())
152            .field("threads", &self.threads())
153            .field("replicate_count", &self.replicate_count())
154            .field("phases", &self.study.phases().len())
155            .finish_non_exhaustive()
156    }
157}
158
159impl<'a> PlanSummary<'a> {
160    /// Returns the validated project-configuration schema generation.
161    pub fn workflow_schema(self) -> u64 {
162        self.study.inner.workflow_schema
163    }
164
165    /// Returns the study-wide authored global compute budget.
166    pub fn threads(self) -> usize {
167        self.study.threads()
168    }
169
170    /// Returns the positive number of isolated replicates.
171    pub fn replicate_count(self) -> u64 {
172        self.study.replicate_policy().count()
173    }
174
175    /// Returns the effective replicate admission mode.
176    pub fn replicate_scheduling(self) -> PlanReplicateScheduling {
177        match self.study.replicate_policy().scheduling() {
178            ReplicateScheduling::Sequential => PlanReplicateScheduling::Sequential,
179            ReplicateScheduling::Parallel => PlanReplicateScheduling::Parallel,
180        }
181    }
182
183    /// Returns the effective failed-replicate response.
184    pub fn replicate_failure_policy(self) -> PlanFailurePolicy {
185        public_failure_policy(self.study.replicate_policy().failure_policy())
186    }
187
188    /// Reports whether this plan retains a study-wide master seed.
189    ///
190    /// The value itself remains outside the inspection view so diagnostics do
191    /// not accidentally publish it.
192    pub fn has_master_seed(self) -> bool {
193        self.study.master_seed().is_some()
194    }
195
196    /// Returns the effective local chunk rollover target in bytes.
197    pub fn persistence_chunk_target_bytes(self) -> u64 {
198        self.study.persistence_plan().chunk_target().get()
199    }
200
201    /// Returns the effective bounded persistence queue capacity in bytes.
202    pub fn persistence_queue_capacity_bytes(self) -> u64 {
203        self.study.persistence_plan().queue_capacity().get()
204    }
205
206    /// Iterates compiled phases in manifest declaration order.
207    pub fn phases(self) -> impl ExactSizeIterator<Item = PhasePlanSummary<'a>> {
208        self.study
209            .phases()
210            .iter()
211            .map(|phase| PhasePlanSummary { phase })
212    }
213}
214
215/// The effective replicate scheduling mode reported by [`PlanSummary`].
216#[derive(Clone, Copy, Debug, Eq, PartialEq)]
217pub enum PlanReplicateScheduling {
218    /// Complete one replicate before admitting the next.
219    Sequential,
220    /// Admit eligible replicates concurrently.
221    Parallel,
222}
223
224/// An effective fail-fast or finish-all decision in a compiled plan.
225#[derive(Clone, Copy, Debug, Eq, PartialEq)]
226pub enum PlanFailurePolicy {
227    /// Stop admitting sibling work after the first failure.
228    FailFast,
229    /// Allow declared sibling work to finish after a failure.
230    FinishAll,
231}
232
233/// A read-only view of one compiled phase.
234#[derive(Clone, Copy)]
235pub struct PhasePlanSummary<'a> {
236    phase: &'a StudyPhase,
237}
238
239impl std::fmt::Debug for PhasePlanSummary<'_> {
240    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241        formatter
242            .debug_struct("PhasePlanSummary")
243            .field("name", &self.name())
244            .field("dependencies", &self.phase.dependencies.len())
245            .field("tasks", &self.phase.tasks.len())
246            .finish_non_exhaustive()
247    }
248}
249
250impl<'a> PhasePlanSummary<'a> {
251    /// Returns the stable manifest phase key.
252    pub fn name(self) -> &'a str {
253        self.phase.name()
254    }
255
256    /// Iterates dependency phase keys in declaration order.
257    pub fn dependencies(self) -> impl ExactSizeIterator<Item = &'a str> {
258        self.phase.dependencies()
259    }
260
261    /// Returns the positive maximum number of concurrently admitted tasks.
262    pub fn max_concurrency(self) -> usize {
263        self.phase.max_concurrency()
264    }
265
266    /// Returns the minimum interval between successive task admissions.
267    pub fn start_interval(self) -> Duration {
268        self.phase.start_interval()
269    }
270
271    /// Returns the optional phase-wide timeout.
272    pub fn timeout(self) -> Option<Duration> {
273        self.phase.timeout()
274    }
275
276    /// Returns the effective sibling-task failure policy.
277    pub fn failure_policy(self) -> PlanFailurePolicy {
278        public_failure_policy(self.phase.failure_policy())
279    }
280
281    /// Iterates compiled tasks in deterministic plan order.
282    pub fn tasks(self) -> impl ExactSizeIterator<Item = TaskPlanSummary<'a>> {
283        self.phase
284            .tasks()
285            .iter()
286            .map(|task| TaskPlanSummary { task })
287    }
288}
289
290/// A read-only view of one compiled task.
291#[derive(Clone, Copy)]
292pub struct TaskPlanSummary<'a> {
293    task: &'a StudyTask,
294}
295
296impl std::fmt::Debug for TaskPlanSummary<'_> {
297    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
298        formatter
299            .debug_struct("TaskPlanSummary")
300            .field("identity", &self.identity())
301            .field("label", &self.label())
302            .field("kind", &self.kind())
303            .finish_non_exhaustive()
304    }
305}
306
307impl<'a> TaskPlanSummary<'a> {
308    /// Returns the deterministic study-wide task identity.
309    pub fn identity(self) -> &'a str {
310        self.task.identity()
311    }
312
313    /// Returns the inferred human-readable task label.
314    pub fn label(self) -> &'a str {
315        self.task.label()
316    }
317
318    /// Returns the global deterministic output ordinal.
319    pub fn output_ordinal(self) -> u64 {
320        self.task.output_ordinal()
321    }
322
323    /// Returns the optional task-specific timeout.
324    pub fn timeout(self) -> Option<Duration> {
325        self.task.timeout()
326    }
327
328    /// Returns the optional semantic seed purpose declared by an external task.
329    pub fn seed_purpose(self) -> Option<&'a str> {
330        self.task.program_seed_purpose()
331    }
332
333    /// Returns the workload-specific immutable planning facts.
334    pub fn kind(self) -> PlannedTaskKind<'a> {
335        if let Some(provenance) = self.task.execution_unit_provenance() {
336            PlannedTaskKind::ExecutionUnit {
337                execution_unit: provenance.execution_unit(),
338                state: provenance.state(),
339                parameter_ordinal: provenance.parameter_ordinal(),
340                parameter_source: provenance.parameter_source(),
341            }
342        } else if let Some(script) = self.task.python_script() {
343            PlannedTaskKind::Python {
344                launcher: self
345                    .task
346                    .program_path()
347                    .expect("a compiled Python task has a resolved launcher"),
348                script,
349                threads: self.task.program_threads(),
350            }
351        } else {
352            PlannedTaskKind::Program {
353                executable: self
354                    .task
355                    .program_path()
356                    .expect("a compiled program task has a resolved executable"),
357                threads: self.task.program_threads(),
358            }
359        }
360    }
361}
362
363/// Workload-specific facts for one task in a [`PlanSummary`].
364#[derive(Clone, Copy, Debug, Eq, PartialEq)]
365pub enum PlannedTaskKind<'a> {
366    /// A linked Rust execution-unit invocation.
367    ExecutionUnit {
368        /// Stable linked registration key.
369        execution_unit: &'a str,
370        /// Selected project-state key or standard-provider ID.
371        state: &'a str,
372        /// Zero-based ordinal of the expanded parameter combination.
373        parameter_ordinal: u64,
374        /// Canonical source of the selected parameter namespace.
375        parameter_source: &'a Path,
376    },
377    /// A directly invoked external executable.
378    Program {
379        /// Canonical executable selected during preflight.
380        executable: &'a Path,
381        /// Number of global compute permits reserved while the program runs.
382        threads: usize,
383    },
384    /// A Python script invoked through a resolved environment launcher.
385    Python {
386        /// Canonical executable used to launch the environment or interpreter.
387        launcher: &'a Path,
388        /// Canonical Python script selected during preflight.
389        script: &'a Path,
390        /// Number of global compute permits reserved while the script runs.
391        threads: usize,
392    },
393}
394
395fn public_failure_policy(policy: FailurePolicy) -> PlanFailurePolicy {
396    match policy {
397        FailurePolicy::FailFast => PlanFailurePolicy::FailFast,
398        FailurePolicy::FinishAll => PlanFailurePolicy::FinishAll,
399    }
400}
401
402/// One immutable execution phase compiled from the study manifest.
403#[derive(Clone, Debug)]
404pub(crate) struct StudyPhase {
405    pub(crate) name: Box<str>,
406    pub(crate) dependencies: Box<[Box<str>]>,
407    pub(crate) tasks: Box<[StudyTask]>,
408    pub(crate) max_concurrency: usize,
409    pub(crate) start_interval: Duration,
410    pub(crate) timeout: Option<Duration>,
411    pub(crate) failure_policy: FailurePolicy,
412}
413
414impl StudyPhase {
415    /// Returns the stable phase key from `wf_configs/study.json`.
416    pub(crate) fn name(&self) -> &str {
417        &self.name
418    }
419
420    /// Iterates dependency keys in declaration order.
421    pub(crate) fn dependencies(&self) -> impl ExactSizeIterator<Item = &str> {
422        self.dependencies.iter().map(Box::as_ref)
423    }
424
425    /// Returns bound execution-unit/program invocations in deterministic plan order.
426    pub(crate) fn tasks(&self) -> &[StudyTask] {
427        &self.tasks
428    }
429
430    /// Returns the positive effective concurrency bound.
431    pub(crate) const fn max_concurrency(&self) -> usize {
432        self.max_concurrency
433    }
434
435    /// Returns the effective interval between task admissions.
436    pub(crate) const fn start_interval(&self) -> Duration {
437        self.start_interval
438    }
439
440    /// Returns the optional phase-wide timeout.
441    pub(crate) const fn timeout(&self) -> Option<Duration> {
442        self.timeout
443    }
444
445    /// Returns the effective sibling failure policy.
446    pub(crate) const fn failure_policy(&self) -> FailurePolicy {
447        self.failure_policy
448    }
449}
450
451/// One generic execution-unit or program task compiled from project configuration.
452#[derive(Clone)]
453pub(crate) struct StudyTask {
454    pub(crate) identity: Box<str>,
455    pub(crate) label: Box<str>,
456    pub(crate) output_ordinal: u64,
457    pub(crate) task: Task,
458}
459
460impl StudyTask {
461    /// Returns the inferred stable identity within this study plan.
462    pub(crate) fn identity(&self) -> &str {
463        &self.identity
464    }
465
466    /// Returns the inferred human-readable label.
467    pub(crate) fn label(&self) -> &str {
468        &self.label
469    }
470
471    pub(crate) fn kind(&self) -> TaskKind {
472        self.task.kind()
473    }
474
475    pub(crate) fn kind_name(&self) -> &'static str {
476        self.task.kind_name()
477    }
478
479    /// Returns the registration key when this is an execution-unit task.
480    pub(crate) fn execution_unit(&self) -> Option<&str> {
481        self.task.execution_unit()
482    }
483
484    /// Returns the generic task subject used in lifecycle presentation.
485    pub(crate) fn subject(&self) -> &str {
486        self.task.subject()
487    }
488
489    /// Returns the optional task-specific cooperative timeout.
490    pub(crate) fn timeout(&self) -> Option<Duration> {
491        self.task.timeout()
492    }
493
494    pub(crate) fn output_ordinal(&self) -> u64 {
495        self.output_ordinal
496    }
497
498    pub(crate) fn definition(&self) -> &dyn TaskDefinition {
499        &self.task
500    }
501
502    pub(crate) fn execution_unit_provenance(&self) -> Option<ExecutionUnitTaskProvenance<'_>> {
503        self.task.execution_unit_provenance()
504    }
505
506    pub(crate) fn program_path(&self) -> Option<&Path> {
507        self.task.program_path()
508    }
509
510    pub(crate) fn python_script(&self) -> Option<&Path> {
511        self.task.python_script()
512    }
513
514    pub(crate) fn program_seed_purpose(&self) -> Option<&str> {
515        self.task.program_seed_purpose()
516    }
517
518    pub(crate) fn program_threads(&self) -> usize {
519        self.task
520            .program_threads()
521            .expect("a compiled program task retains its positive thread request")
522    }
523}
524
525impl std::fmt::Debug for StudyTask {
526    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
527        formatter
528            .debug_struct("StudyTask")
529            .field("identity", &self.identity())
530            .field("label", &self.label())
531            .field("kind", &self.kind())
532            .field("subject", &self.subject())
533            .finish_non_exhaustive()
534    }
535}