Skip to main content

scientific_workflow/task/
dependencies.rs

1//! Typed, immutable results supplied to a task by its declared dependencies.
2//!
3//! Selectors preserve snapshot order and never read scientific files. Runtime
4//! owns dependency scope; this API cannot discover unrelated output directories.
5
6use serde::Deserialize;
7use serde_json::Value;
8use std::path::{Path, PathBuf};
9use thiserror::Error;
10
11/// Invalid input or a dependency selection with unexpected cardinality.
12#[derive(Debug, Error)]
13#[non_exhaustive]
14pub enum DependencyError {
15    /// An environment variable required by the standard launch contract is absent.
16    #[error("missing {variable}; run this program through Workflow's standard study layout")]
17    MissingEnvironment {
18        /// Required variable name.
19        variable: &'static str,
20    },
21    /// A snapshot could not be read.
22    #[error("cannot read dependency snapshot `{path}`")]
23    Io {
24        /// Expected snapshot path.
25        path: PathBuf,
26        /// Underlying filesystem failure.
27        #[source]
28        source: std::io::Error,
29    },
30    /// A known result or the snapshot structure is malformed.
31    #[error("invalid dependency snapshot: {0}")]
32    Invalid(String),
33    /// No result satisfies the selection.
34    #[error("no dependency matches {selection}")]
35    Missing {
36        /// Applied filters.
37        selection: String,
38    },
39    /// Several results satisfy a selection requiring at most one.
40    #[error("ambiguous dependency selection {selection}: {matches:?}; select a phase or task")]
41    Ambiguous {
42        /// Applied filters.
43        selection: String,
44        /// Candidate source identifiers in snapshot order.
45        matches: Vec<String>,
46    },
47}
48
49/// One validated dependency snapshot. Unknown workload kinds remain in raw JSON.
50#[derive(Clone, Debug)]
51pub struct Dependencies {
52    raw: Value,
53    recordings: Vec<RecordingDependency>,
54    programs: Vec<ProgramDependency>,
55    npy_batches: Vec<NpyDependency>,
56}
57
58#[derive(Deserialize)]
59struct Phase {
60    phase: String,
61    tasks: Vec<Task>,
62}
63#[derive(Deserialize)]
64struct Task {
65    identity: String,
66    output_directory: PathBuf,
67    workload: Value,
68}
69#[derive(Deserialize)]
70struct Member {
71    identity: String,
72    final_iteration: u64,
73    output_directory: PathBuf,
74}
75#[derive(Deserialize)]
76struct Unit {
77    execution_unit: String,
78    members: Vec<Member>,
79}
80#[derive(Deserialize)]
81struct Program {
82    executable: PathBuf,
83    python_script: Option<PathBuf>,
84}
85#[derive(Deserialize)]
86struct Npy {
87    processed_directory: PathBuf,
88}
89
90impl Dependencies {
91    /// Validates an owned JSON snapshot without opening its referenced files.
92    pub fn from_json(raw: Value) -> Result<Self, DependencyError> {
93        let phases: Vec<Phase> = decode(raw.clone())?;
94        let mut result = Self {
95            raw,
96            recordings: Vec::new(),
97            programs: Vec::new(),
98            npy_batches: Vec::new(),
99        };
100        let mut phases_seen = std::collections::HashSet::new();
101        for phase in phases {
102            name(&phase.phase)?;
103            if !phases_seen.insert(phase.phase.clone()) {
104                return Err(DependencyError::Invalid("duplicate phase identity".into()));
105            }
106            let mut tasks_seen = std::collections::HashSet::new();
107            for task in phase.tasks {
108                name(&task.identity)?;
109                path(&task.output_directory)?;
110                if !tasks_seen.insert(task.identity.clone()) {
111                    return Err(DependencyError::Invalid(
112                        "duplicate task identity in phase".into(),
113                    ));
114                }
115                let source = Source {
116                    phase: phase.phase.clone(),
117                    task: task.identity,
118                };
119                let kind = task
120                    .workload
121                    .get("kind")
122                    .and_then(Value::as_str)
123                    .ok_or_else(|| {
124                        DependencyError::Invalid("workload.kind must be a nonempty string".into())
125                    })?;
126                name(kind)?;
127                match kind {
128                    "execution_unit" => {
129                        let unit: Unit = decode(task.workload)?;
130                        name(&unit.execution_unit)?;
131                        let mut members_seen = std::collections::HashSet::new();
132                        if unit.members.is_empty() {
133                            return Err(DependencyError::Invalid(
134                                "execution unit has no members".into(),
135                            ));
136                        }
137                        for member in unit.members {
138                            name(&member.identity)?;
139                            path(&member.output_directory)?;
140                            if !members_seen.insert(member.identity.clone()) {
141                                return Err(DependencyError::Invalid(
142                                    "duplicate member identity".into(),
143                                ));
144                            }
145                            result.recordings.push(RecordingDependency {
146                                source: source.clone(),
147                                execution_unit: unit.execution_unit.clone(),
148                                member: member.identity,
149                                final_iteration: member.final_iteration,
150                                directory: member.output_directory,
151                            });
152                        }
153                    }
154                    "program" | "python" => {
155                        let program: Program = decode(task.workload.clone())?;
156                        path(&program.executable)?;
157                        if kind == "python" && program.python_script.is_none() {
158                            return Err(DependencyError::Invalid(
159                                "python workload requires python_script".into(),
160                            ));
161                        }
162                        if let Some(script) = &program.python_script {
163                            path(script)?;
164                        }
165                        result.programs.push(ProgramDependency {
166                            source,
167                            directory: task.output_directory.join("artifacts"),
168                            executable: program.executable,
169                            python_script: program.python_script,
170                        });
171                    }
172                    "npy" => {
173                        let npy: Npy = decode(task.workload)?;
174                        path(&npy.processed_directory)?;
175                        result.npy_batches.push(NpyDependency {
176                            source,
177                            directory: npy.processed_directory,
178                        });
179                    }
180                    _ => {} // Forward-compatible raw access; known kinds are always validated.
181                }
182            }
183        }
184        Ok(result)
185    }
186
187    /// Verifies both task input files and loads a canonical dependency snapshot.
188    ///
189    /// Requires sibling `workflow-inputs.json` checksum evidence; current
190    /// program/receipt references, when present, must agree with that evidence.
191    pub fn load(path: &Path) -> Result<Self, DependencyError> {
192        if path
193            .file_name()
194            .is_none_or(|name| name != "workflow-dependencies.json")
195        {
196            return Err(DependencyError::Invalid(
197                "expected canonical workflow-dependencies.json snapshot path".into(),
198            ));
199        }
200        let directory = path
201            .parent()
202            .ok_or_else(|| DependencyError::Invalid("snapshot path has no parent".into()))?;
203        let inputs =
204            crate::persistence::TaskInputSnapshots::open(directory).map_err(snapshot_error)?;
205        let [_, bytes] = inputs.read_verified().map_err(snapshot_error)?;
206        Self::from_json(
207            serde_json::from_slice(&bytes)
208                .map_err(|error| DependencyError::Invalid(error.to_string()))?,
209        )
210    }
211
212    /// Loads `WORKFLOW_DEPENDENCIES_PATH`, supplied by a Workflow program launch.
213    pub fn from_env() -> Result<Self, DependencyError> {
214        let path = std::env::var_os("WORKFLOW_DEPENDENCIES_PATH").ok_or(
215            DependencyError::MissingEnvironment {
216                variable: "WORKFLOW_DEPENDENCIES_PATH",
217            },
218        )?;
219        Self::load(Path::new(&path))
220    }
221
222    /// Borrows the original snapshot, including unknown extension fields/kinds.
223    pub const fn raw_json(&self) -> &Value {
224        &self.raw
225    }
226    /// Selects completed member recordings in deterministic snapshot order.
227    pub fn recordings(&self) -> Selection<'_, RecordingDependency> {
228        Selection::new(&self.recordings)
229    }
230    /// Selects program and Python task artifact directories.
231    pub fn programs(&self) -> Selection<'_, ProgramDependency> {
232        Selection::new(&self.programs)
233    }
234    /// Selects aggregate NPY batches; this does not filter members within a batch.
235    pub fn npy_batches(&self) -> Selection<'_, NpyDependency> {
236        Selection::new(&self.npy_batches)
237    }
238}
239
240fn snapshot_error(error: crate::persistence::PersistenceError) -> DependencyError {
241    match error {
242        crate::persistence::PersistenceError::Io { path, source, .. } => {
243            DependencyError::Io { path, source }
244        }
245        other => DependencyError::Invalid(other.to_string()),
246    }
247}
248
249fn decode<T: serde::de::DeserializeOwned>(value: Value) -> Result<T, DependencyError> {
250    serde_json::from_value(value).map_err(|error| DependencyError::Invalid(error.to_string()))
251}
252fn name(value: &str) -> Result<(), DependencyError> {
253    if value.is_empty() || value.trim() != value {
254        return Err(DependencyError::Invalid(
255            "identifiers must be nonempty without surrounding whitespace".into(),
256        ));
257    }
258    Ok(())
259}
260fn path(value: &Path) -> Result<(), DependencyError> {
261    if !value.is_absolute() {
262        return Err(DependencyError::Invalid(format!(
263            "expected absolute path, got {}",
264            value.display()
265        )));
266    }
267    Ok(())
268}
269
270#[derive(Clone, Debug)]
271struct Source {
272    phase: String,
273    task: String,
274}
275
276mod sealed {
277    pub trait Sealed {}
278}
279/// Shared identity access for Workflow-owned dependency result types.
280///
281/// This trait is sealed; downstream implementations are not supported.
282pub trait Dependency: sealed::Sealed {
283    /// Declared phase key.
284    fn phase(&self) -> &str;
285    /// Runtime-generated task identity.
286    fn task(&self) -> &str;
287    /// Human-readable source used in ambiguity diagnostics.
288    fn description(&self) -> String;
289}
290
291/// Borrowed, filtered dependency results. Filters combine by intersection.
292#[derive(Clone, Debug)]
293pub struct Selection<'a, T> {
294    entries: Vec<&'a T>,
295    filters: Vec<String>,
296}
297impl<'a, T: Dependency> Selection<'a, T> {
298    fn new(entries: &'a [T]) -> Self {
299        Self {
300            entries: entries.iter().collect(),
301            filters: Vec::new(),
302        }
303    }
304    fn filter(mut self, label: String, predicate: impl Fn(&T) -> bool) -> Self {
305        self.entries.retain(|entry| predicate(entry));
306        self.filters.push(label);
307        self
308    }
309    /// Restricts matches to a declared phase key.
310    pub fn in_phase(self, phase: &str) -> Self {
311        self.filter(format!("phase={phase:?}"), |entry| entry.phase() == phase)
312    }
313    /// Restricts matches to an exact runtime task identity.
314    pub fn task(self, task: &str) -> Self {
315        self.filter(format!("task={task:?}"), |entry| entry.task() == task)
316    }
317    /// Returns exactly one result, reporting missing or ambiguous matches.
318    pub fn one(&self) -> Result<&'a T, DependencyError> {
319        self.optional()?.ok_or_else(|| DependencyError::Missing {
320            selection: self.label(),
321        })
322    }
323    /// Returns zero or one result; several matches produce an ambiguity error.
324    pub fn optional(&self) -> Result<Option<&'a T>, DependencyError> {
325        match self.entries.as_slice() {
326            [] => Ok(None),
327            [entry] => Ok(Some(*entry)),
328            _ => Err(DependencyError::Ambiguous {
329                selection: self.label(),
330                matches: self
331                    .entries
332                    .iter()
333                    .map(|entry| entry.description())
334                    .collect(),
335            }),
336        }
337    }
338    /// Iterates all matching results in snapshot order, including zero matches.
339    pub fn iter(&self) -> impl ExactSizeIterator<Item = &'a T> + '_ {
340        self.entries.iter().copied()
341    }
342    fn label(&self) -> String {
343        format!(
344            "{} [{}]",
345            std::any::type_name::<T>(),
346            self.filters.join(", ")
347        )
348    }
349}
350
351impl Selection<'_, RecordingDependency> {
352    /// Restricts recordings to an exact execution-unit registration key.
353    pub fn execution_unit(self, key: &str) -> Self {
354        self.filter(format!("execution_unit={key:?}"), |entry| {
355            entry.execution_unit == key
356        })
357    }
358    /// Restricts recordings to an exact member identity.
359    pub fn member(self, member: &str) -> Self {
360        self.filter(format!("member={member:?}"), |entry| entry.member == member)
361    }
362}
363
364/// A completed member recording.
365#[derive(Clone, Debug)]
366pub struct RecordingDependency {
367    source: Source,
368    execution_unit: String,
369    member: String,
370    final_iteration: u64,
371    directory: PathBuf,
372}
373impl RecordingDependency {
374    /// Declared phase key.
375    pub fn phase(&self) -> &str {
376        &self.source.phase
377    }
378    /// Runtime-generated task identity.
379    pub fn task(&self) -> &str {
380        &self.source.task
381    }
382    /// Execution-unit registration key.
383    pub fn execution_unit(&self) -> &str {
384        &self.execution_unit
385    }
386    /// Member identity within its execution unit.
387    pub fn member(&self) -> &str {
388        &self.member
389    }
390    /// Final scientific iteration.
391    pub fn final_iteration(&self) -> u64 {
392        self.final_iteration
393    }
394    /// Completed recording directory.
395    pub fn directory(&self) -> &Path {
396        &self.directory
397    }
398}
399impl sealed::Sealed for RecordingDependency {}
400impl Dependency for RecordingDependency {
401    fn phase(&self) -> &str {
402        self.phase()
403    }
404    fn task(&self) -> &str {
405        self.task()
406    }
407    fn description(&self) -> String {
408        format!("{}/{}", self.phase(), self.task()) + &format!("/{}", self.member)
409    }
410}
411
412/// A completed external executable or Python task.
413#[derive(Clone, Debug)]
414pub struct ProgramDependency {
415    source: Source,
416    directory: PathBuf,
417    executable: PathBuf,
418    python_script: Option<PathBuf>,
419}
420impl ProgramDependency {
421    /// Declared phase key.
422    pub fn phase(&self) -> &str {
423        &self.source.phase
424    }
425    /// Runtime-generated task identity.
426    pub fn task(&self) -> &str {
427        &self.source.task
428    }
429    /// Standard artifacts directory, excluding logs and snapshots.
430    pub fn directory(&self) -> &Path {
431        &self.directory
432    }
433    /// Resolved launcher executable.
434    pub fn executable(&self) -> &Path {
435        &self.executable
436    }
437    /// Canonical Python script when this was a Python task.
438    pub fn python_script(&self) -> Option<&Path> {
439        self.python_script.as_deref()
440    }
441}
442impl sealed::Sealed for ProgramDependency {}
443impl Dependency for ProgramDependency {
444    fn phase(&self) -> &str {
445        self.phase()
446    }
447    fn task(&self) -> &str {
448        self.task()
449    }
450    fn description(&self) -> String {
451        format!("{}/{}", self.phase(), self.task())
452    }
453}
454
455/// An aggregate converted NPY batch.
456#[derive(Clone, Debug)]
457pub struct NpyDependency {
458    source: Source,
459    directory: PathBuf,
460}
461impl NpyDependency {
462    /// Declared phase key.
463    pub fn phase(&self) -> &str {
464        &self.source.phase
465    }
466    /// Runtime-generated task identity.
467    pub fn task(&self) -> &str {
468        &self.source.task
469    }
470    /// Verified-reader entry directory containing the batch manifest.
471    pub fn directory(&self) -> &Path {
472        &self.directory
473    }
474}
475impl sealed::Sealed for NpyDependency {}
476impl Dependency for NpyDependency {
477    fn phase(&self) -> &str {
478        self.phase()
479    }
480    fn task(&self) -> &str {
481        self.task()
482    }
483    fn description(&self) -> String {
484        format!("{}/{}", self.phase(), self.task())
485    }
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491    fn snapshot() -> Value {
492        serde_json::json!([
493            {"phase":"initialize", "tasks":[{"identity":"a", "output_directory":"/run/a", "workload":{"kind":"execution_unit","execution_unit":"init","members":[{"identity":"one","final_iteration":4,"output_directory":"/run/a"}]}}]},
494            {"phase":"other", "tasks":[{"identity":"b", "output_directory":"/run/b", "workload":{"kind":"execution_unit","execution_unit":"init","members":[{"identity":"one","final_iteration":5,"output_directory":"/run/b"}]}}]}
495        ])
496    }
497    #[test]
498    fn selection_is_explicit_and_preserves_order_and_source() {
499        let deps = Dependencies::from_json(snapshot()).unwrap();
500        assert!(
501            matches!(deps.recordings().execution_unit("init").one(), Err(DependencyError::Ambiguous { matches, .. }) if matches == ["initialize/a/one", "other/b/one"])
502        );
503        let selected = deps
504            .recordings()
505            .in_phase("initialize")
506            .member("one")
507            .one()
508            .unwrap();
509        assert_eq!(selected.directory(), Path::new("/run/a"));
510        assert_eq!(
511            deps.recordings()
512                .iter()
513                .map(|r| r.final_iteration())
514                .collect::<Vec<_>>(),
515            [4, 5]
516        );
517        assert!(
518            deps.recordings()
519                .in_phase("missing")
520                .optional()
521                .unwrap()
522                .is_none()
523        );
524        assert!(matches!(
525            deps.recordings().in_phase("missing").one(),
526            Err(DependencyError::Missing { .. })
527        ));
528        assert_eq!(deps.raw_json(), &snapshot());
529    }
530    #[test]
531    fn malformed_known_results_fail_and_extensions_remain_available() {
532        let mut value = snapshot();
533        value[0]["tasks"][0]["workload"]["members"][0]["final_iteration"] = "bad".into();
534        assert!(Dependencies::from_json(value).is_err());
535        let value = serde_json::json!([{"phase":"extension","tasks":[{"identity":"task","output_directory":"/output","workload":{"kind":"future","extra":1}}]}]);
536        let deps = Dependencies::from_json(value.clone()).unwrap();
537        assert_eq!(deps.raw_json(), &value);
538        assert_eq!(deps.recordings().iter().len(), 0);
539    }
540}