Skip to main content

scientific_workflow/study/
plan.rs

1//! Immutable study, phase, and task views.
2
3use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::time::Duration;
7
8use crate::config::{
9    ComputeMode, Config, ConfigSnapshot, FailurePolicy, PersistenceSpecification,
10    ProjectSpecification, ReplicatePolicy, ReplicateScheduling, StudyManifest,
11};
12use crate::persistence::PersistencePlan;
13use crate::task::{
14    ExecutionUnitCatalog, ExecutionUnitTaskProvenance, Task, TaskDefinition, TaskKind,
15};
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().clone();
42        let workflow_schema = manifest.workflow_schema();
43        let threads = manifest.threads();
44        let compute_mode = manifest.compute_mode();
45        let replicate_policy = manifest.replicate_policy();
46        let master_seed = manifest.master_seed();
47        let persistence: PersistenceSpecification = manifest.persistence();
48        let persistence_plan = PersistencePlan::local(
49            persistence.chunk_target_bytes(),
50            persistence.queue_capacity_bytes(),
51        );
52        Self {
53            inner: Arc::new(StudyInner {
54                disk_pause_at: manifest.disk_pause_at(),
55                active_phases: manifest.active_phases().into(),
56                reuse_from: manifest.reuse_from().map(Path::to_path_buf),
57                phase_order: topological_positions(&phases).into_boxed_slice(),
58                project_root,
59                config,
60                phases,
61                output_root,
62                workflow_schema,
63                threads,
64                compute_mode,
65                master_seed,
66                replicate_policy,
67                persistence_plan,
68            }),
69        }
70    }
71
72    /// Returns the canonical project root loaded by config.
73    pub fn project_root(&self) -> &Path {
74        &self.inner.project_root
75    }
76
77    /// Returns the inferred output root, `<project-root>/output`.
78    pub fn output_root(&self) -> &Path {
79        &self.inner.output_root
80    }
81
82    /// Returns the required study-wide global compute budget.
83    pub fn threads(&self) -> usize {
84        self.inner.threads
85    }
86
87    pub(crate) fn disk_pause_at(&self) -> Option<f64> {
88        self.inner.disk_pause_at
89    }
90
91    pub(crate) fn compute_mode(&self) -> ComputeMode {
92        self.inner.compute_mode
93    }
94
95    /// Returns a read-only view of the fully compiled deterministic plan.
96    ///
97    /// The view borrows this Study and exposes planning facts only. It does not
98    /// expose constants payloads, executable task handles, or mutable policy.
99    pub fn plan_summary(&self) -> PlanSummary<'_> {
100        PlanSummary { study: self }
101    }
102
103    /// Returns the deterministic dependency traversal of the complete phase graph.
104    pub(crate) fn phase_order(&self) -> &[usize] {
105        &self.inner.phase_order
106    }
107
108    /// Reports explicit selection by dependency-order index.
109    pub(crate) fn phase_is_active(&self, index: usize) -> bool {
110        self.inner.active_phases.contains(&index)
111    }
112
113    /// Returns the explicit completed-output source, if configured.
114    pub(crate) fn reuse_from(&self) -> Option<&Path> {
115        self.inner.reuse_from.as_deref()
116    }
117
118    /// Returns immutable phases in manifest declaration order.
119    pub(crate) fn phases(&self) -> &[StudyPhase] {
120        &self.inner.phases
121    }
122
123    /// Returns the effective replicate policy parsed from `wf_configs/study.json`.
124    pub(crate) fn replicate_policy(&self) -> ReplicatePolicy {
125        self.inner.replicate_policy
126    }
127
128    /// Returns the study-wide optional deterministic seed.
129    pub(crate) fn master_seed(&self) -> Option<u64> {
130        self.inner.master_seed
131    }
132
133    /// Returns the immutable effective persistence plan compiled from
134    /// `wf_configs/study.json`.
135    pub(crate) fn persistence_plan(&self) -> PersistencePlan {
136        self.inner.persistence_plan
137    }
138}
139
140impl std::fmt::Debug for Study {
141    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        formatter
143            .debug_struct("Study")
144            .field("project_root", &self.project_root())
145            .field("output_root", &self.output_root())
146            .field("threads", &self.threads())
147            .field("compute_mode", &self.plan_summary().compute_mode())
148            .field("config", &self.inner.config)
149            .field("persistence", &self.persistence_plan())
150            .field("phases", &self.phases().len())
151            .finish_non_exhaustive()
152    }
153}
154
155struct StudyInner {
156    disk_pause_at: Option<f64>,
157    active_phases: Box<[usize]>,
158    reuse_from: Option<PathBuf>,
159    phase_order: Box<[usize]>,
160    project_root: PathBuf,
161    config: Config,
162    phases: Box<[StudyPhase]>,
163    output_root: PathBuf,
164    workflow_schema: u64,
165    threads: usize,
166    compute_mode: ComputeMode,
167    master_seed: Option<u64>,
168    replicate_policy: ReplicatePolicy,
169    persistence_plan: PersistencePlan,
170}
171
172/// A read-only view of one fully compiled [`Study`].
173#[derive(Clone, Copy)]
174pub struct PlanSummary<'a> {
175    study: &'a Study,
176}
177
178impl std::fmt::Debug for PlanSummary<'_> {
179    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180        formatter
181            .debug_struct("PlanSummary")
182            .field("workflow_schema", &self.workflow_schema())
183            .field("threads", &self.threads())
184            .field("compute_mode", &self.compute_mode())
185            .field("replicate_count", &self.replicate_count())
186            .field("phases", &self.study.phases().len())
187            .finish_non_exhaustive()
188    }
189}
190
191impl<'a> PlanSummary<'a> {
192    /// Returns the validated project-configuration schema generation.
193    pub fn workflow_schema(self) -> u64 {
194        self.study.inner.workflow_schema
195    }
196
197    /// Returns the study-wide authored global compute budget.
198    pub fn threads(self) -> usize {
199        self.study.threads()
200    }
201
202    /// Returns the global execution-unit compute allocation mode.
203    pub fn compute_mode(self) -> PlanComputeMode {
204        match self.study.compute_mode() {
205            ComputeMode::Auto => PlanComputeMode::Auto,
206            ComputeMode::Isolated => PlanComputeMode::Isolated,
207        }
208    }
209
210    /// Returns the positive number of isolated replicates.
211    pub fn replicate_count(self) -> u64 {
212        self.study.replicate_policy().count()
213    }
214
215    /// Returns the effective replicate admission mode.
216    pub fn replicate_scheduling(self) -> PlanReplicateScheduling {
217        match self.study.replicate_policy().scheduling() {
218            ReplicateScheduling::Sequential => PlanReplicateScheduling::Sequential,
219            ReplicateScheduling::Parallel => PlanReplicateScheduling::Parallel,
220        }
221    }
222
223    /// Returns the effective failed-replicate response.
224    pub fn replicate_failure_policy(self) -> PlanFailurePolicy {
225        public_failure_policy(self.study.replicate_policy().failure_policy())
226    }
227
228    /// Reports whether this plan retains a study-wide master seed.
229    ///
230    /// The value itself remains outside the inspection view so diagnostics do
231    /// not accidentally publish it.
232    pub fn has_master_seed(self) -> bool {
233        self.study.master_seed().is_some()
234    }
235
236    /// Returns the effective local chunk rollover target in bytes.
237    pub fn persistence_chunk_target_bytes(self) -> u64 {
238        self.study.persistence_plan().chunk_target().get()
239    }
240
241    /// Returns the effective bounded persistence queue capacity in bytes.
242    pub fn persistence_queue_capacity_bytes(self) -> u64 {
243        self.study.persistence_plan().queue_capacity().get()
244    }
245
246    /// Iterates every compiled phase in deterministic dependency order.
247    pub fn phases(self) -> impl ExactSizeIterator<Item = PhasePlanSummary<'a>> {
248        self.study
249            .phase_order()
250            .iter()
251            .enumerate()
252            .map(|(index, &position)| PhasePlanSummary {
253                phase: &self.study.phases()[position],
254                index,
255                active: self.study.phase_is_active(index),
256            })
257    }
258}
259
260/// The effective replicate scheduling mode reported by [`PlanSummary`].
261#[derive(Clone, Copy, Debug, Eq, PartialEq)]
262pub enum PlanReplicateScheduling {
263    /// Complete one replicate before admitting the next.
264    Sequential,
265    /// Admit eligible replicates concurrently.
266    Parallel,
267}
268
269/// Global execution-unit compute allocation mode reported by [`PlanSummary`].
270#[derive(Clone, Copy, Debug, Eq, PartialEq)]
271pub enum PlanComputeMode {
272    /// Equal dynamic allocations across working invariant units.
273    Auto,
274    /// Fixed authored per-task allocations.
275    Isolated,
276}
277
278/// An effective fail-fast or finish-all decision in a compiled plan.
279#[derive(Clone, Copy, Debug, Eq, PartialEq)]
280pub enum PlanFailurePolicy {
281    /// Stop admitting sibling work after the first failure.
282    FailFast,
283    /// Allow declared sibling work to finish after a failure.
284    FinishAll,
285}
286
287/// A read-only view of one compiled phase.
288#[derive(Clone, Copy)]
289pub struct PhasePlanSummary<'a> {
290    index: usize,
291    active: bool,
292    phase: &'a StudyPhase,
293}
294
295impl std::fmt::Debug for PhasePlanSummary<'_> {
296    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297        formatter
298            .debug_struct("PhasePlanSummary")
299            .field("name", &self.name())
300            .field("dependencies", &self.phase.dependencies.len())
301            .field("tasks", &self.phase.tasks.len())
302            .finish_non_exhaustive()
303    }
304}
305
306impl<'a> PhasePlanSummary<'a> {
307    /// Returns the stable zero-based index used by `active_phases`.
308    pub fn index(self) -> usize {
309        self.index
310    }
311
312    /// Reports whether this phase will execute during this invocation.
313    pub fn is_active(self) -> bool {
314        self.active
315    }
316
317    /// Returns the stable manifest phase key.
318    pub fn name(self) -> &'a str {
319        self.phase.name()
320    }
321
322    /// Iterates dependency phase keys in declaration order.
323    pub fn dependencies(self) -> impl ExactSizeIterator<Item = &'a str> {
324        self.phase.dependencies()
325    }
326
327    /// Returns the positive maximum number of concurrently admitted tasks.
328    pub fn max_concurrency(self) -> usize {
329        self.phase.max_concurrency()
330    }
331
332    /// Returns the minimum interval between successive task admissions.
333    pub fn start_interval(self) -> Duration {
334        self.phase.start_interval()
335    }
336
337    /// Returns the optional phase-wide timeout.
338    pub fn timeout(self) -> Option<Duration> {
339        self.phase.timeout()
340    }
341
342    /// Returns the effective sibling-task failure policy.
343    pub fn failure_policy(self) -> PlanFailurePolicy {
344        public_failure_policy(self.phase.failure_policy())
345    }
346
347    /// Iterates compiled tasks in deterministic plan order.
348    pub fn tasks(self) -> impl ExactSizeIterator<Item = TaskPlanSummary<'a>> {
349        self.phase.tasks().iter().map(move |task| TaskPlanSummary {
350            task,
351            active: self.active && task.is_active(),
352        })
353    }
354}
355
356/// A read-only view of one compiled task.
357#[derive(Clone, Copy)]
358pub struct TaskPlanSummary<'a> {
359    task: &'a StudyTask,
360    active: bool,
361}
362
363impl std::fmt::Debug for TaskPlanSummary<'_> {
364    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
365        formatter
366            .debug_struct("TaskPlanSummary")
367            .field("identity", &self.identity())
368            .field("label", &self.label())
369            .field("active", &self.is_active())
370            .field("kind", &self.kind())
371            .finish_non_exhaustive()
372    }
373}
374
375impl<'a> TaskPlanSummary<'a> {
376    /// Returns the deterministic study-wide task identity.
377    pub fn identity(self) -> &'a str {
378        self.task.identity()
379    }
380
381    /// Returns the inferred human-readable task label.
382    pub fn label(self) -> &'a str {
383        self.task.label()
384    }
385
386    /// Returns the global deterministic output ordinal.
387    pub fn output_ordinal(self) -> u64 {
388        self.task.output_ordinal()
389    }
390
391    /// Reports whether this task is selected within an active phase.
392    pub fn is_active(self) -> bool {
393        self.active
394    }
395
396    /// Returns the optional task-specific timeout.
397    pub fn timeout(self) -> Option<Duration> {
398        self.task.timeout()
399    }
400
401    /// Returns the optional semantic seed purpose declared by an external task.
402    pub fn seed_purpose(self) -> Option<&'a str> {
403        self.task.program_seed_purpose()
404    }
405
406    /// Returns the workload-specific immutable planning facts.
407    pub fn kind(self) -> PlannedTaskKind<'a> {
408        if let Some(provenance) = self.task.execution_unit_provenance() {
409            PlannedTaskKind::ExecutionUnit {
410                execution_unit: provenance.execution_unit(),
411                state: provenance.state(),
412                parameter_ordinal: provenance.parameter_ordinal(),
413                parameter_source: provenance.parameter_source(),
414                threads: self.task.threads,
415            }
416        } else if let Some(script) = self.task.python_script() {
417            PlannedTaskKind::Python {
418                launcher: self
419                    .task
420                    .program_path()
421                    .expect("a compiled Python task has a resolved launcher"),
422                script,
423                threads: self.task.program_threads(),
424            }
425        } else {
426            PlannedTaskKind::Program {
427                executable: self
428                    .task
429                    .program_path()
430                    .expect("a compiled program task has a resolved executable"),
431                threads: self.task.program_threads(),
432            }
433        }
434    }
435}
436
437/// Workload-specific facts for one task in a [`PlanSummary`].
438#[derive(Clone, Copy, Debug, Eq, PartialEq)]
439pub enum PlannedTaskKind<'a> {
440    /// A linked Rust execution-unit invocation.
441    ExecutionUnit {
442        /// Stable linked registration key.
443        execution_unit: &'a str,
444        /// Selected project-state key or standard-provider ID.
445        state: &'a str,
446        /// Zero-based ordinal of the expanded parameter combination.
447        parameter_ordinal: u64,
448        /// Canonical source of the selected parameter namespace.
449        parameter_source: &'a Path,
450        /// Fixed thread allocation in isolated mode; absent in automatic mode.
451        threads: Option<usize>,
452    },
453    /// A directly invoked external executable.
454    Program {
455        /// Canonical executable selected during preflight.
456        executable: &'a Path,
457        /// Number of global compute permits reserved while the program runs.
458        threads: usize,
459    },
460    /// A Python script invoked through a resolved environment launcher.
461    Python {
462        /// Canonical executable used to launch the environment or interpreter.
463        launcher: &'a Path,
464        /// Canonical Python script selected during preflight.
465        script: &'a Path,
466        /// Number of global compute permits reserved while the script runs.
467        threads: usize,
468    },
469}
470
471fn public_failure_policy(policy: FailurePolicy) -> PlanFailurePolicy {
472    match policy {
473        FailurePolicy::FailFast => PlanFailurePolicy::FailFast,
474        FailurePolicy::FinishAll => PlanFailurePolicy::FinishAll,
475    }
476}
477
478/// One immutable execution phase compiled from the study manifest.
479#[derive(Clone, Debug)]
480pub(crate) struct StudyPhase {
481    pub(crate) name: Box<str>,
482    pub(crate) dependencies: Box<[Box<str>]>,
483    pub(crate) tasks: Box<[StudyTask]>,
484    pub(crate) max_concurrency: usize,
485    pub(crate) start_interval: Duration,
486    pub(crate) timeout: Option<Duration>,
487    pub(crate) failure_policy: FailurePolicy,
488}
489
490impl StudyPhase {
491    /// Returns the stable phase key from `wf_configs/study.json`.
492    pub(crate) fn name(&self) -> &str {
493        &self.name
494    }
495
496    /// Iterates dependency keys in declaration order.
497    pub(crate) fn dependencies(&self) -> impl ExactSizeIterator<Item = &str> {
498        self.dependencies.iter().map(Box::as_ref)
499    }
500
501    /// Returns bound execution-unit/program invocations in deterministic plan order.
502    pub(crate) fn tasks(&self) -> &[StudyTask] {
503        &self.tasks
504    }
505
506    /// Returns the positive effective concurrency bound.
507    pub(crate) const fn max_concurrency(&self) -> usize {
508        self.max_concurrency
509    }
510
511    /// Returns the effective interval between task admissions.
512    pub(crate) const fn start_interval(&self) -> Duration {
513        self.start_interval
514    }
515
516    /// Returns the optional phase-wide timeout.
517    pub(crate) const fn timeout(&self) -> Option<Duration> {
518        self.timeout
519    }
520
521    /// Returns the effective sibling failure policy.
522    pub(crate) const fn failure_policy(&self) -> FailurePolicy {
523        self.failure_policy
524    }
525}
526
527/// One generic execution-unit or program task compiled from project configuration.
528#[derive(Clone)]
529pub(crate) struct StudyTask {
530    pub(crate) active: bool,
531    pub(crate) identity: Box<str>,
532    pub(crate) label: Box<str>,
533    pub(crate) output_ordinal: u64,
534    pub(crate) configuration: usize,
535    pub(crate) config_snapshot: ConfigSnapshot,
536    pub(crate) task: Task,
537    pub(crate) threads: Option<usize>,
538}
539
540impl StudyTask {
541    /// Reports whether this task is selected within an active phase.
542    pub(crate) const fn is_active(&self) -> bool {
543        self.active
544    }
545
546    /// Returns the inferred stable identity within this study plan.
547    pub(crate) fn identity(&self) -> &str {
548        &self.identity
549    }
550
551    /// Returns the inferred human-readable label.
552    pub(crate) fn label(&self) -> &str {
553        &self.label
554    }
555
556    pub(crate) fn kind(&self) -> TaskKind {
557        self.task.kind()
558    }
559
560    pub(crate) fn kind_name(&self) -> &'static str {
561        self.task.kind_name()
562    }
563
564    /// Returns the registration key when this is an execution-unit task.
565    pub(crate) fn execution_unit(&self) -> Option<&str> {
566        self.task.execution_unit()
567    }
568
569    /// Returns the generic task subject used in lifecycle presentation.
570    pub(crate) fn subject(&self) -> &str {
571        self.task.subject()
572    }
573
574    /// Returns the optional task-specific cooperative timeout.
575    pub(crate) fn timeout(&self) -> Option<Duration> {
576        self.task.timeout()
577    }
578
579    pub(crate) fn output_ordinal(&self) -> u64 {
580        self.output_ordinal
581    }
582
583    pub(crate) const fn configuration(&self) -> usize {
584        self.configuration
585    }
586
587    pub(crate) fn config_snapshot(&self) -> ConfigSnapshot {
588        self.config_snapshot.clone()
589    }
590
591    pub(crate) fn definition(&self) -> &dyn TaskDefinition {
592        &self.task
593    }
594
595    pub(crate) fn execution_unit_provenance(&self) -> Option<ExecutionUnitTaskProvenance<'_>> {
596        self.task.execution_unit_provenance()
597    }
598
599    pub(crate) fn program_path(&self) -> Option<&Path> {
600        self.task.program_path()
601    }
602
603    pub(crate) fn python_script(&self) -> Option<&Path> {
604        self.task.python_script()
605    }
606
607    pub(crate) fn program_seed_purpose(&self) -> Option<&str> {
608        self.task.program_seed_purpose()
609    }
610
611    pub(crate) fn program_threads(&self) -> usize {
612        self.task
613            .program_threads()
614            .expect("a compiled program task retains its positive thread request")
615    }
616
617    pub(crate) const fn execution_unit_threads(&self) -> Option<usize> {
618        self.threads
619    }
620
621    pub(crate) fn is_npy(&self) -> bool {
622        self.task.is_npy()
623    }
624}
625
626impl std::fmt::Debug for StudyTask {
627    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
628        formatter
629            .debug_struct("StudyTask")
630            .field("identity", &self.identity())
631            .field("label", &self.label())
632            .field("kind", &self.kind())
633            .field("subject", &self.subject())
634            .finish_non_exhaustive()
635    }
636}
637
638fn topological_positions(phases: &[StudyPhase]) -> Vec<usize> {
639    fn visit(
640        index: usize,
641        phases: &[StudyPhase],
642        by_name: &std::collections::HashMap<&str, usize>,
643        visited: &mut [bool],
644        positions: &mut Vec<usize>,
645    ) {
646        if visited[index] {
647            return;
648        }
649        for dependency in phases[index].dependencies() {
650            visit(by_name[dependency], phases, by_name, visited, positions);
651        }
652        visited[index] = true;
653        positions.push(index);
654    }
655
656    let by_name = phases
657        .iter()
658        .enumerate()
659        .map(|(index, phase)| (phase.name(), index))
660        .collect::<HashMap<_, _>>();
661    let mut visited = vec![false; phases.len()];
662    let mut positions = Vec::with_capacity(phases.len());
663    for index in 0..phases.len() {
664        visit(index, phases, &by_name, &mut visited, &mut positions);
665    }
666    positions
667}