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