scientific-workflow 0.14.1

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! Immutable study, phase, and task views.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use crate::config::{
    ComputeMode, Config, ConfigSnapshot, FailurePolicy, PersistenceSpecification,
    ProjectSpecification, ReplicatePolicy, ReplicateScheduling, StudyManifest,
};
use crate::persistence::PersistencePlan;
use crate::task::{
    ExecutionUnitCatalog, ExecutionUnitTaskProvenance, Task, TaskDefinition, TaskKind,
};

use super::compilation;
use super::error::StudyError;

/// A complete immutable and effect-free execution declaration.
#[derive(Clone)]
pub struct Study {
    inner: Arc<StudyInner>,
}

impl Study {
    /// Loads project declarations and binds all linked `#[execution_unit]` registrations.
    ///
    /// This performs complete preflight without creating output or initializing
    /// an execution unit. Config is the only file reader and JSON parser.
    pub fn load(project_root: &Path) -> Result<Self, StudyError> {
        let project = ProjectSpecification::load(project_root)?;
        let catalog = ExecutionUnitCatalog::discovered()?;
        compilation::compile(project, &catalog)
    }

    pub(crate) fn from_parts(project: ProjectSpecification, phases: Box<[StudyPhase]>) -> Self {
        let project_root = project.project_root().to_path_buf();
        let config = project.config().clone();
        let output_root = project_root.join("output");
        let manifest: StudyManifest = project.manifest().clone();
        let workflow_schema = manifest.workflow_schema();
        let threads = manifest.threads();
        let compute_mode = manifest.compute_mode();
        let replicate_policy = manifest.replicate_policy();
        let master_seed = manifest.master_seed();
        let persistence: PersistenceSpecification = manifest.persistence();
        let persistence_plan = PersistencePlan::local(
            persistence.chunk_target_bytes(),
            persistence.queue_capacity_bytes(),
        );
        Self {
            inner: Arc::new(StudyInner {
                active_phases: manifest.active_phases().into(),
                reuse_from: manifest.reuse_from().map(Path::to_path_buf),
                phase_order: topological_positions(&phases).into_boxed_slice(),
                project_root,
                config,
                phases,
                output_root,
                workflow_schema,
                threads,
                compute_mode,
                master_seed,
                replicate_policy,
                persistence_plan,
            }),
        }
    }

    /// Returns the canonical project root loaded by config.
    pub fn project_root(&self) -> &Path {
        &self.inner.project_root
    }

    /// Returns the inferred output root, `<project-root>/output`.
    pub fn output_root(&self) -> &Path {
        &self.inner.output_root
    }

    /// Returns the required study-wide global compute budget.
    pub fn threads(&self) -> usize {
        self.inner.threads
    }

    pub(crate) fn compute_mode(&self) -> ComputeMode {
        self.inner.compute_mode
    }

    /// Returns a read-only view of the fully compiled deterministic plan.
    ///
    /// The view borrows this Study and exposes planning facts only. It does not
    /// expose constants payloads, executable task handles, or mutable policy.
    pub fn plan_summary(&self) -> PlanSummary<'_> {
        PlanSummary { study: self }
    }

    /// Returns the deterministic dependency traversal of the complete phase graph.
    pub(crate) fn phase_order(&self) -> &[usize] {
        &self.inner.phase_order
    }

    /// Reports explicit selection by dependency-order index.
    pub(crate) fn phase_is_active(&self, index: usize) -> bool {
        self.inner.active_phases.contains(&index)
    }

    /// Returns the explicit completed-output source, if configured.
    pub(crate) fn reuse_from(&self) -> Option<&Path> {
        self.inner.reuse_from.as_deref()
    }

    /// Returns immutable phases in manifest declaration order.
    pub(crate) fn phases(&self) -> &[StudyPhase] {
        &self.inner.phases
    }

    /// Returns the effective replicate policy parsed from `wf_configs/study.json`.
    pub(crate) fn replicate_policy(&self) -> ReplicatePolicy {
        self.inner.replicate_policy
    }

    /// Returns the study-wide optional deterministic seed.
    pub(crate) fn master_seed(&self) -> Option<u64> {
        self.inner.master_seed
    }

    /// Returns the immutable effective persistence plan compiled from
    /// `wf_configs/study.json`.
    pub(crate) fn persistence_plan(&self) -> PersistencePlan {
        self.inner.persistence_plan
    }
}

impl std::fmt::Debug for Study {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Study")
            .field("project_root", &self.project_root())
            .field("output_root", &self.output_root())
            .field("threads", &self.threads())
            .field("compute_mode", &self.plan_summary().compute_mode())
            .field("config", &self.inner.config)
            .field("persistence", &self.persistence_plan())
            .field("phases", &self.phases().len())
            .finish_non_exhaustive()
    }
}

struct StudyInner {
    active_phases: Box<[usize]>,
    reuse_from: Option<PathBuf>,
    phase_order: Box<[usize]>,
    project_root: PathBuf,
    config: Config,
    phases: Box<[StudyPhase]>,
    output_root: PathBuf,
    workflow_schema: u64,
    threads: usize,
    compute_mode: ComputeMode,
    master_seed: Option<u64>,
    replicate_policy: ReplicatePolicy,
    persistence_plan: PersistencePlan,
}

/// A read-only view of one fully compiled [`Study`].
#[derive(Clone, Copy)]
pub struct PlanSummary<'a> {
    study: &'a Study,
}

impl std::fmt::Debug for PlanSummary<'_> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PlanSummary")
            .field("workflow_schema", &self.workflow_schema())
            .field("threads", &self.threads())
            .field("compute_mode", &self.compute_mode())
            .field("replicate_count", &self.replicate_count())
            .field("phases", &self.study.phases().len())
            .finish_non_exhaustive()
    }
}

impl<'a> PlanSummary<'a> {
    /// Returns the validated project-configuration schema generation.
    pub fn workflow_schema(self) -> u64 {
        self.study.inner.workflow_schema
    }

    /// Returns the study-wide authored global compute budget.
    pub fn threads(self) -> usize {
        self.study.threads()
    }

    /// Returns the global execution-unit compute allocation mode.
    pub fn compute_mode(self) -> PlanComputeMode {
        match self.study.compute_mode() {
            ComputeMode::Auto => PlanComputeMode::Auto,
            ComputeMode::Isolated => PlanComputeMode::Isolated,
        }
    }

    /// Returns the positive number of isolated replicates.
    pub fn replicate_count(self) -> u64 {
        self.study.replicate_policy().count()
    }

    /// Returns the effective replicate admission mode.
    pub fn replicate_scheduling(self) -> PlanReplicateScheduling {
        match self.study.replicate_policy().scheduling() {
            ReplicateScheduling::Sequential => PlanReplicateScheduling::Sequential,
            ReplicateScheduling::Parallel => PlanReplicateScheduling::Parallel,
        }
    }

    /// Returns the effective failed-replicate response.
    pub fn replicate_failure_policy(self) -> PlanFailurePolicy {
        public_failure_policy(self.study.replicate_policy().failure_policy())
    }

    /// Reports whether this plan retains a study-wide master seed.
    ///
    /// The value itself remains outside the inspection view so diagnostics do
    /// not accidentally publish it.
    pub fn has_master_seed(self) -> bool {
        self.study.master_seed().is_some()
    }

    /// Returns the effective local chunk rollover target in bytes.
    pub fn persistence_chunk_target_bytes(self) -> u64 {
        self.study.persistence_plan().chunk_target().get()
    }

    /// Returns the effective bounded persistence queue capacity in bytes.
    pub fn persistence_queue_capacity_bytes(self) -> u64 {
        self.study.persistence_plan().queue_capacity().get()
    }

    /// Iterates every compiled phase in deterministic dependency order.
    pub fn phases(self) -> impl ExactSizeIterator<Item = PhasePlanSummary<'a>> {
        self.study
            .phase_order()
            .iter()
            .enumerate()
            .map(|(index, &position)| PhasePlanSummary {
                phase: &self.study.phases()[position],
                index,
                active: self.study.phase_is_active(index),
            })
    }
}

/// The effective replicate scheduling mode reported by [`PlanSummary`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PlanReplicateScheduling {
    /// Complete one replicate before admitting the next.
    Sequential,
    /// Admit eligible replicates concurrently.
    Parallel,
}

/// Global execution-unit compute allocation mode reported by [`PlanSummary`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PlanComputeMode {
    /// Equal dynamic allocations across working invariant units.
    Auto,
    /// Fixed authored per-task allocations.
    Isolated,
}

/// An effective fail-fast or finish-all decision in a compiled plan.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PlanFailurePolicy {
    /// Stop admitting sibling work after the first failure.
    FailFast,
    /// Allow declared sibling work to finish after a failure.
    FinishAll,
}

/// A read-only view of one compiled phase.
#[derive(Clone, Copy)]
pub struct PhasePlanSummary<'a> {
    index: usize,
    active: bool,
    phase: &'a StudyPhase,
}

impl std::fmt::Debug for PhasePlanSummary<'_> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PhasePlanSummary")
            .field("name", &self.name())
            .field("dependencies", &self.phase.dependencies.len())
            .field("tasks", &self.phase.tasks.len())
            .finish_non_exhaustive()
    }
}

impl<'a> PhasePlanSummary<'a> {
    /// Returns the stable zero-based index used by `active_phases`.
    pub fn index(self) -> usize {
        self.index
    }

    /// Reports whether this phase will execute during this invocation.
    pub fn is_active(self) -> bool {
        self.active
    }

    /// Returns the stable manifest phase key.
    pub fn name(self) -> &'a str {
        self.phase.name()
    }

    /// Iterates dependency phase keys in declaration order.
    pub fn dependencies(self) -> impl ExactSizeIterator<Item = &'a str> {
        self.phase.dependencies()
    }

    /// Returns the positive maximum number of concurrently admitted tasks.
    pub fn max_concurrency(self) -> usize {
        self.phase.max_concurrency()
    }

    /// Returns the minimum interval between successive task admissions.
    pub fn start_interval(self) -> Duration {
        self.phase.start_interval()
    }

    /// Returns the optional phase-wide timeout.
    pub fn timeout(self) -> Option<Duration> {
        self.phase.timeout()
    }

    /// Returns the effective sibling-task failure policy.
    pub fn failure_policy(self) -> PlanFailurePolicy {
        public_failure_policy(self.phase.failure_policy())
    }

    /// Iterates compiled tasks in deterministic plan order.
    pub fn tasks(self) -> impl ExactSizeIterator<Item = TaskPlanSummary<'a>> {
        self.phase.tasks().iter().map(move |task| TaskPlanSummary {
            task,
            active: self.active && task.is_active(),
        })
    }
}

/// A read-only view of one compiled task.
#[derive(Clone, Copy)]
pub struct TaskPlanSummary<'a> {
    task: &'a StudyTask,
    active: bool,
}

impl std::fmt::Debug for TaskPlanSummary<'_> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("TaskPlanSummary")
            .field("identity", &self.identity())
            .field("label", &self.label())
            .field("active", &self.is_active())
            .field("kind", &self.kind())
            .finish_non_exhaustive()
    }
}

impl<'a> TaskPlanSummary<'a> {
    /// Returns the deterministic study-wide task identity.
    pub fn identity(self) -> &'a str {
        self.task.identity()
    }

    /// Returns the inferred human-readable task label.
    pub fn label(self) -> &'a str {
        self.task.label()
    }

    /// Returns the global deterministic output ordinal.
    pub fn output_ordinal(self) -> u64 {
        self.task.output_ordinal()
    }

    /// Reports whether this task is selected within an active phase.
    pub fn is_active(self) -> bool {
        self.active
    }

    /// Returns the optional task-specific timeout.
    pub fn timeout(self) -> Option<Duration> {
        self.task.timeout()
    }

    /// Returns the optional semantic seed purpose declared by an external task.
    pub fn seed_purpose(self) -> Option<&'a str> {
        self.task.program_seed_purpose()
    }

    /// Returns the workload-specific immutable planning facts.
    pub fn kind(self) -> PlannedTaskKind<'a> {
        if let Some(provenance) = self.task.execution_unit_provenance() {
            PlannedTaskKind::ExecutionUnit {
                execution_unit: provenance.execution_unit(),
                state: provenance.state(),
                parameter_ordinal: provenance.parameter_ordinal(),
                parameter_source: provenance.parameter_source(),
                threads: self.task.threads,
            }
        } else if let Some(script) = self.task.python_script() {
            PlannedTaskKind::Python {
                launcher: self
                    .task
                    .program_path()
                    .expect("a compiled Python task has a resolved launcher"),
                script,
                threads: self.task.program_threads(),
            }
        } else {
            PlannedTaskKind::Program {
                executable: self
                    .task
                    .program_path()
                    .expect("a compiled program task has a resolved executable"),
                threads: self.task.program_threads(),
            }
        }
    }
}

/// Workload-specific facts for one task in a [`PlanSummary`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PlannedTaskKind<'a> {
    /// A linked Rust execution-unit invocation.
    ExecutionUnit {
        /// Stable linked registration key.
        execution_unit: &'a str,
        /// Selected project-state key or standard-provider ID.
        state: &'a str,
        /// Zero-based ordinal of the expanded parameter combination.
        parameter_ordinal: u64,
        /// Canonical source of the selected parameter namespace.
        parameter_source: &'a Path,
        /// Fixed thread allocation in isolated mode; absent in automatic mode.
        threads: Option<usize>,
    },
    /// A directly invoked external executable.
    Program {
        /// Canonical executable selected during preflight.
        executable: &'a Path,
        /// Number of global compute permits reserved while the program runs.
        threads: usize,
    },
    /// A Python script invoked through a resolved environment launcher.
    Python {
        /// Canonical executable used to launch the environment or interpreter.
        launcher: &'a Path,
        /// Canonical Python script selected during preflight.
        script: &'a Path,
        /// Number of global compute permits reserved while the script runs.
        threads: usize,
    },
}

fn public_failure_policy(policy: FailurePolicy) -> PlanFailurePolicy {
    match policy {
        FailurePolicy::FailFast => PlanFailurePolicy::FailFast,
        FailurePolicy::FinishAll => PlanFailurePolicy::FinishAll,
    }
}

/// One immutable execution phase compiled from the study manifest.
#[derive(Clone, Debug)]
pub(crate) struct StudyPhase {
    pub(crate) name: Box<str>,
    pub(crate) dependencies: Box<[Box<str>]>,
    pub(crate) tasks: Box<[StudyTask]>,
    pub(crate) max_concurrency: usize,
    pub(crate) start_interval: Duration,
    pub(crate) timeout: Option<Duration>,
    pub(crate) failure_policy: FailurePolicy,
}

impl StudyPhase {
    /// Returns the stable phase key from `wf_configs/study.json`.
    pub(crate) fn name(&self) -> &str {
        &self.name
    }

    /// Iterates dependency keys in declaration order.
    pub(crate) fn dependencies(&self) -> impl ExactSizeIterator<Item = &str> {
        self.dependencies.iter().map(Box::as_ref)
    }

    /// Returns bound execution-unit/program invocations in deterministic plan order.
    pub(crate) fn tasks(&self) -> &[StudyTask] {
        &self.tasks
    }

    /// Returns the positive effective concurrency bound.
    pub(crate) const fn max_concurrency(&self) -> usize {
        self.max_concurrency
    }

    /// Returns the effective interval between task admissions.
    pub(crate) const fn start_interval(&self) -> Duration {
        self.start_interval
    }

    /// Returns the optional phase-wide timeout.
    pub(crate) const fn timeout(&self) -> Option<Duration> {
        self.timeout
    }

    /// Returns the effective sibling failure policy.
    pub(crate) const fn failure_policy(&self) -> FailurePolicy {
        self.failure_policy
    }
}

/// One generic execution-unit or program task compiled from project configuration.
#[derive(Clone)]
pub(crate) struct StudyTask {
    pub(crate) active: bool,
    pub(crate) identity: Box<str>,
    pub(crate) label: Box<str>,
    pub(crate) output_ordinal: u64,
    pub(crate) configuration: usize,
    pub(crate) config_snapshot: ConfigSnapshot,
    pub(crate) task: Task,
    pub(crate) threads: Option<usize>,
}

impl StudyTask {
    /// Reports whether this task is selected within an active phase.
    pub(crate) const fn is_active(&self) -> bool {
        self.active
    }

    /// Returns the inferred stable identity within this study plan.
    pub(crate) fn identity(&self) -> &str {
        &self.identity
    }

    /// Returns the inferred human-readable label.
    pub(crate) fn label(&self) -> &str {
        &self.label
    }

    pub(crate) fn kind(&self) -> TaskKind {
        self.task.kind()
    }

    pub(crate) fn kind_name(&self) -> &'static str {
        self.task.kind_name()
    }

    /// Returns the registration key when this is an execution-unit task.
    pub(crate) fn execution_unit(&self) -> Option<&str> {
        self.task.execution_unit()
    }

    /// Returns the generic task subject used in lifecycle presentation.
    pub(crate) fn subject(&self) -> &str {
        self.task.subject()
    }

    /// Returns the optional task-specific cooperative timeout.
    pub(crate) fn timeout(&self) -> Option<Duration> {
        self.task.timeout()
    }

    pub(crate) fn output_ordinal(&self) -> u64 {
        self.output_ordinal
    }

    pub(crate) const fn configuration(&self) -> usize {
        self.configuration
    }

    pub(crate) fn config_snapshot(&self) -> ConfigSnapshot {
        self.config_snapshot.clone()
    }

    pub(crate) fn definition(&self) -> &dyn TaskDefinition {
        &self.task
    }

    pub(crate) fn execution_unit_provenance(&self) -> Option<ExecutionUnitTaskProvenance<'_>> {
        self.task.execution_unit_provenance()
    }

    pub(crate) fn program_path(&self) -> Option<&Path> {
        self.task.program_path()
    }

    pub(crate) fn python_script(&self) -> Option<&Path> {
        self.task.python_script()
    }

    pub(crate) fn program_seed_purpose(&self) -> Option<&str> {
        self.task.program_seed_purpose()
    }

    pub(crate) fn program_threads(&self) -> usize {
        self.task
            .program_threads()
            .expect("a compiled program task retains its positive thread request")
    }

    pub(crate) const fn execution_unit_threads(&self) -> Option<usize> {
        self.threads
    }

    pub(crate) fn is_npy(&self) -> bool {
        self.task.is_npy()
    }
}

impl std::fmt::Debug for StudyTask {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("StudyTask")
            .field("identity", &self.identity())
            .field("label", &self.label())
            .field("kind", &self.kind())
            .field("subject", &self.subject())
            .finish_non_exhaustive()
    }
}

fn topological_positions(phases: &[StudyPhase]) -> Vec<usize> {
    fn visit(
        index: usize,
        phases: &[StudyPhase],
        by_name: &std::collections::HashMap<&str, usize>,
        visited: &mut [bool],
        positions: &mut Vec<usize>,
    ) {
        if visited[index] {
            return;
        }
        for dependency in phases[index].dependencies() {
            visit(by_name[dependency], phases, by_name, visited, positions);
        }
        visited[index] = true;
        positions.push(index);
    }

    let by_name = phases
        .iter()
        .enumerate()
        .map(|(index, phase)| (phase.name(), index))
        .collect::<HashMap<_, _>>();
    let mut visited = vec![false; phases.len()];
    let mut positions = Vec::with_capacity(phases.len());
    for index in 0..phases.len() {
        visit(index, phases, &by_name, &mut visited, &mut positions);
    }
    positions
}