scientific-workflow 0.18.0

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
//! Loading one project root into an immutable resolved specification.

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::time::Duration;

use serde_json::Value;

use super::document::{StateSchemaDocument, child_pointer};
use super::error::ConfigError;
use super::expansion;
use super::manifest::{self, FailurePolicy, ParsedTask, StudyManifest};
use super::parameters::ResolvedExecutionUnitParameters;
use super::program::{ResolvedProgramTask, resolve_active_python, resolve_executable};
use super::python;
use super::store::Config;

const PARAMETERS: &str = "parameters.json";

/// One centrally resolved generic task declaration.
#[derive(Clone, Debug)]
pub(crate) enum ResolvedTask {
    ExecutionUnit {
        artifacts: crate::artifact::ArtifactDeclarations,
        active: bool,
        configuration: usize,
        snapshot: super::store::ConfigSnapshot,
        parameters: ResolvedExecutionUnitParameters,
        state: Option<Box<str>>,
        threads: Option<usize>,
    },
    Program {
        artifacts: crate::artifact::ArtifactDeclarations,
        configuration: usize,
        snapshot: super::store::ConfigSnapshot,
        program: ResolvedProgramTask,
    },
}

impl ResolvedTask {
    pub(crate) fn artifacts(&self) -> &crate::artifact::ArtifactDeclarations {
        match self {
            Self::ExecutionUnit { artifacts, .. } | Self::Program { artifacts, .. } => artifacts,
        }
    }

    pub(crate) const fn configuration(&self) -> usize {
        match self {
            Self::ExecutionUnit { configuration, .. } | Self::Program { configuration, .. } => {
                *configuration
            }
        }
    }

    pub(crate) fn snapshot(&self) -> &super::store::ConfigSnapshot {
        match self {
            Self::ExecutionUnit { snapshot, .. } | Self::Program { snapshot, .. } => snapshot,
        }
    }
}

/// One validated phase with resolved generic tasks and effective policy.
#[derive(Clone, Debug)]
pub(crate) struct PhaseSpecification {
    pub(crate) auto_name_prefix: Option<Box<str>>,
    pub(crate) name: Box<str>,
    pub(crate) dependencies: Box<[Box<str>]>,
    pub(crate) tasks: Box<[ResolvedTask]>,
    pub(crate) max_concurrency: usize,
    pub(crate) start_interval: Duration,
    pub(crate) timeout: Option<Duration>,
    pub(crate) failure_policy: FailurePolicy,
}

impl PhaseSpecification {
    pub(crate) fn name(&self) -> &str {
        &self.name
    }

    pub(crate) fn dependencies(&self) -> impl ExactSizeIterator<Item = &str> {
        self.dependencies.iter().map(Box::as_ref)
    }

    pub(crate) fn tasks(&self) -> &[ResolvedTask] {
        &self.tasks
    }

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

    pub(crate) const fn start_interval(&self) -> Duration {
        self.start_interval
    }

    pub(crate) const fn timeout(&self) -> Option<Duration> {
        self.timeout
    }

    pub(crate) const fn failure_policy(&self) -> FailurePolicy {
        self.failure_policy
    }
}

/// A complete immutable project declaration compiled from one project root.
#[derive(Debug)]
pub(crate) struct ProjectSpecification {
    config: Config,
    manifest: StudyManifest,
    state_schemas: BTreeMap<Box<str>, StateSchemaDocument>,
    phases: Box<[PhaseSpecification]>,
}

impl ProjectSpecification {
    /// Loads and validates all declarations and parameters beneath `project_root`.
    ///
    /// The root is canonicalized once. `wf_configs/study.json` and every other
    /// JSON document beneath `wf_configs` are captured centrally. Reserved views,
    /// execution-unit parameter sections, and executable paths are resolved from that
    /// snapshot. Loading creates no output and executes no task.
    pub(crate) fn load(project_root: &Path) -> Result<Self, ConfigError> {
        let config = Config::load(project_root)?;
        let parsed = manifest::parse(
            config.study_path(),
            config.study_value().clone(),
            config.runtime(),
        )?;

        let mut state_schemas = BTreeMap::new();
        for (name, authored_path) in &parsed.state_paths {
            let (state_path, state_value) = config
                .project_document(authored_path)?
                .ok_or_else(|| missing_document(config.project_root(), authored_path))?;
            state_schemas.insert(
                name.clone(),
                StateSchemaDocument::new(state_path.to_path_buf(), state_value.clone()),
            );
        }

        let parameters_relative = Path::new(PARAMETERS);
        let (parameters_path, parameters_value) =
            config
                .document(parameters_relative)
                .ok_or_else(|| ConfigError::Read {
                    path: config.config_root().join(parameters_relative),
                    source: std::io::Error::new(
                        std::io::ErrorKind::NotFound,
                        "required project parameters document was not loaded",
                    ),
                })?;
        let parameter_sections = parameters_value.as_object().ok_or_else(|| {
            ConfigError::invalid(
                parameters_path,
                "/",
                "project parameters must be a JSON object keyed by workload",
            )
        })?;

        let execution_units = parsed
            .phases
            .iter()
            .flat_map(|phase| phase.tasks.iter())
            .filter_map(|task| match task {
                ParsedTask::ExecutionUnit { execution_unit, .. } => {
                    Some(execution_unit.to_string())
                }
                ParsedTask::Program { .. } | ParsedTask::Python { .. } | ParsedTask::Npy { .. } => {
                    None
                }
            })
            .collect::<BTreeSet<_>>();
        let shared = parameter_sections
            .iter()
            .filter(|(key, _)| !execution_units.contains(key.as_str()))
            .map(|(key, value)| (key.clone(), value.clone()))
            .collect();
        // Unit sections do not depend on global selections. Expand each once,
        // then bind their ordered values to each task's configuration snapshot.
        let expanded_units = execution_units
            .iter()
            .map(|key| {
                let value = parameter_sections.get(key).ok_or_else(|| {
                    ConfigError::invalid(
                        parameters_path,
                        child_pointer("/", key),
                        format!("registered execution unit `{key}` has no parameter section"),
                    )
                })?;
                Ok((key.clone(), expansion::expand(parameters_path, value)?))
            })
            .collect::<Result<BTreeMap<_, _>, ConfigError>>()?;
        let expanded_shared = expansion::expand(parameters_path, &Value::Object(shared))?;
        let mut resolved_snapshots = Vec::with_capacity(expanded_shared.len());
        for shared in expanded_shared {
            let Value::Object(mut resolved) = shared else {
                unreachable!("expanding an object produces objects");
            };
            for key in &execution_units {
                if let Some(value) = parameter_sections.get(key) {
                    resolved.insert(key.clone(), value.clone());
                }
            }
            let value = Value::Object(resolved);
            let snapshot = config.snapshot_with_parameters(&value, parsed.manifest.active_phases());
            resolved_snapshots.push(snapshot);
        }

        let mut phases = Vec::with_capacity(parsed.phases.len());
        for phase in parsed.phases {
            let mut tasks = Vec::new();
            for (task, artifacts) in phase.tasks.into_iter().zip(phase.artifact_roles) {
                match task {
                    ParsedTask::ExecutionUnit {
                        execution_unit,
                        active,
                        state,
                        timeout,
                        threads,
                    } => {
                        if let Some(state) = state.as_deref()
                            && !state_schemas.contains_key(state)
                        {
                            return Err(ConfigError::UnknownState {
                                phase: phase.name.to_string(),
                                execution_unit: execution_unit.to_string(),
                                state: state.to_owned(),
                            });
                        }
                        let expanded = &expanded_units[execution_unit.as_ref()];
                        for (configuration, snapshot) in resolved_snapshots.iter().enumerate() {
                            tasks.try_reserve(expanded.len()).map_err(|_| {
                                ConfigError::ExpansionOverflow {
                                    path: parameters_path.to_path_buf(),
                                }
                            })?;
                            for (ordinal, value) in expanded.iter().enumerate() {
                                let ordinal = u64::try_from(ordinal).map_err(|_| {
                                    ConfigError::ExpansionOverflow {
                                        path: parameters_path.to_path_buf(),
                                    }
                                })?;
                                let mut task_parameters = snapshot.parameters().clone();
                                task_parameters
                                    .as_object_mut()
                                    .expect("resolved project parameters are an object")
                                    .insert(execution_unit.to_string(), value.clone());
                                let task_snapshot = config.snapshot_with_parameters(
                                    &task_parameters,
                                    parsed.manifest.active_phases(),
                                );
                                tasks.push(ResolvedTask::ExecutionUnit {
                                    artifacts: artifacts.clone(),
                                    active,
                                    configuration,
                                    snapshot: task_snapshot,
                                    parameters: ResolvedExecutionUnitParameters::new(
                                        execution_unit.clone(),
                                        parameters_path.to_path_buf(),
                                        ordinal,
                                        value.clone(),
                                        timeout,
                                    ),
                                    state: state.clone(),
                                    threads,
                                });
                            }
                        }
                    }
                    ParsedTask::Program {
                        program,
                        args,
                        seed_purpose,
                        timeout,
                        threads,
                    } => {
                        let program = resolve_executable(config.project_root(), &program)?;
                        let program =
                            ResolvedProgramTask::new(program, args, seed_purpose, timeout, threads);
                        for (configuration, snapshot) in resolved_snapshots.iter().enumerate() {
                            tasks.push(ResolvedTask::Program {
                                artifacts: artifacts.clone(),
                                configuration,
                                snapshot: snapshot.clone(),
                                program: program.clone(),
                            });
                        }
                    }
                    ParsedTask::Python {
                        declaration,
                        seed_purpose,
                        timeout,
                        threads,
                    } => {
                        let program = python::resolve(
                            config.project_root(),
                            declaration,
                            seed_purpose,
                            timeout,
                            threads,
                        )?;
                        for (configuration, snapshot) in resolved_snapshots.iter().enumerate() {
                            tasks.push(ResolvedTask::Program {
                                artifacts: artifacts.clone(),
                                configuration,
                                snapshot: snapshot.clone(),
                                program: program.clone(),
                            });
                        }
                    }
                    ParsedTask::Npy {
                        exclude_streams,
                        threads,
                        auto,
                    } => {
                        let program = ResolvedProgramTask::for_npy(
                            resolve_active_python()?,
                            &exclude_streams,
                            threads,
                            auto,
                        );
                        let program = if let Some(snapshot) = &config.runtime().npy_environment {
                            program.with_python_snapshot(snapshot).map_err(|e| {
                                ConfigError::invalid(
                                    config.study_path(),
                                    "/npy_environment",
                                    e.to_string(),
                                )
                            })?
                        } else {
                            program
                        };
                        let snapshot = resolved_snapshots
                            .first()
                            .expect("parameter expansion always produces one configuration")
                            .clone();
                        tasks.push(ResolvedTask::Program {
                            artifacts: artifacts.clone(),
                            configuration: 0,
                            snapshot,
                            program,
                        });
                    }
                }
            }
            phases.push(PhaseSpecification {
                auto_name_prefix: phase.auto_name_prefix,
                name: phase.name,
                dependencies: phase.dependencies,
                tasks: tasks.into_boxed_slice(),
                max_concurrency: phase.max_concurrency,
                start_interval: phase.start_interval,
                timeout: phase.timeout,
                failure_policy: phase.failure_policy,
            });
        }

        Ok(Self {
            config,
            manifest: parsed.manifest,
            state_schemas,
            phases: phases.into_boxed_slice(),
        })
    }

    /// Returns the canonical project root supplied to [`Self::load`].
    pub(crate) fn project_root(&self) -> &Path {
        self.config.project_root()
    }

    /// Returns the immutable central configuration snapshot.
    pub(crate) fn config(&self) -> &Config {
        &self.config
    }

    /// Returns the validated Workflow-owned study manifest.
    pub(crate) fn manifest(&self) -> &StudyManifest {
        &self.manifest
    }

    /// Returns centrally parsed state-schema documents by manifest key.
    pub(crate) fn state_schemas(&self) -> &BTreeMap<Box<str>, StateSchemaDocument> {
        &self.state_schemas
    }

    /// Returns validated phases and resolved generic tasks in declaration order.
    pub(crate) fn phases(&self) -> &[PhaseSpecification] {
        &self.phases
    }
}

fn missing_document(project_root: &Path, authored_path: &Path) -> ConfigError {
    let path = if authored_path.is_absolute() {
        authored_path.to_path_buf()
    } else {
        project_root.join(authored_path)
    };
    ConfigError::Read {
        path,
        source: std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "declared state schema was not captured as a JSON config document",
        ),
    }
}