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