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