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