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    /// Loads and validates a standard dependency snapshot from an explicit file.
188    pub fn load(path: &Path) -> Result<Self, DependencyError> {
189        let bytes = std::fs::read(path).map_err(|source| DependencyError::Io {
190            path: path.to_owned(),
191            source,
192        })?;
193        Self::from_json(
194            serde_json::from_slice(&bytes)
195                .map_err(|error| DependencyError::Invalid(error.to_string()))?,
196        )
197    }
198
199    /// Loads `WORKFLOW_DEPENDENCIES_PATH`, supplied by a Workflow program launch.
200    pub fn from_env() -> Result<Self, DependencyError> {
201        let path = std::env::var_os("WORKFLOW_DEPENDENCIES_PATH").ok_or(
202            DependencyError::MissingEnvironment {
203                variable: "WORKFLOW_DEPENDENCIES_PATH",
204            },
205        )?;
206        Self::load(Path::new(&path))
207    }
208
209    /// Borrows the original snapshot, including unknown extension fields/kinds.
210    pub const fn raw_json(&self) -> &Value {
211        &self.raw
212    }
213    /// Selects completed member recordings in deterministic snapshot order.
214    pub fn recordings(&self) -> Selection<'_, RecordingDependency> {
215        Selection::new(&self.recordings)
216    }
217    /// Selects program and Python task artifact directories.
218    pub fn programs(&self) -> Selection<'_, ProgramDependency> {
219        Selection::new(&self.programs)
220    }
221    /// Selects aggregate NPY batches; this does not filter members within a batch.
222    pub fn npy_batches(&self) -> Selection<'_, NpyDependency> {
223        Selection::new(&self.npy_batches)
224    }
225}
226
227fn decode<T: serde::de::DeserializeOwned>(value: Value) -> Result<T, DependencyError> {
228    serde_json::from_value(value).map_err(|error| DependencyError::Invalid(error.to_string()))
229}
230fn name(value: &str) -> Result<(), DependencyError> {
231    if value.is_empty() || value.trim() != value {
232        return Err(DependencyError::Invalid(
233            "identifiers must be nonempty without surrounding whitespace".into(),
234        ));
235    }
236    Ok(())
237}
238fn path(value: &Path) -> Result<(), DependencyError> {
239    if !value.is_absolute() {
240        return Err(DependencyError::Invalid(format!(
241            "expected absolute path, got {}",
242            value.display()
243        )));
244    }
245    Ok(())
246}
247
248#[derive(Clone, Debug)]
249struct Source {
250    phase: String,
251    task: String,
252}
253
254mod sealed {
255    pub trait Sealed {}
256}
257/// Shared identity access for Workflow-owned dependency result types.
258///
259/// This trait is sealed; downstream implementations are not supported.
260pub trait Dependency: sealed::Sealed {
261    /// Declared phase key.
262    fn phase(&self) -> &str;
263    /// Runtime-generated task identity.
264    fn task(&self) -> &str;
265    /// Human-readable source used in ambiguity diagnostics.
266    fn description(&self) -> String;
267}
268
269/// Borrowed, filtered dependency results. Filters combine by intersection.
270#[derive(Clone, Debug)]
271pub struct Selection<'a, T> {
272    entries: Vec<&'a T>,
273    filters: Vec<String>,
274}
275impl<'a, T: Dependency> Selection<'a, T> {
276    fn new(entries: &'a [T]) -> Self {
277        Self {
278            entries: entries.iter().collect(),
279            filters: Vec::new(),
280        }
281    }
282    fn filter(mut self, label: String, predicate: impl Fn(&T) -> bool) -> Self {
283        self.entries.retain(|entry| predicate(entry));
284        self.filters.push(label);
285        self
286    }
287    /// Restricts matches to a declared phase key.
288    pub fn in_phase(self, phase: &str) -> Self {
289        self.filter(format!("phase={phase:?}"), |entry| entry.phase() == phase)
290    }
291    /// Restricts matches to an exact runtime task identity.
292    pub fn task(self, task: &str) -> Self {
293        self.filter(format!("task={task:?}"), |entry| entry.task() == task)
294    }
295    /// Returns exactly one result, reporting missing or ambiguous matches.
296    pub fn one(&self) -> Result<&'a T, DependencyError> {
297        self.optional()?.ok_or_else(|| DependencyError::Missing {
298            selection: self.label(),
299        })
300    }
301    /// Returns zero or one result; several matches produce an ambiguity error.
302    pub fn optional(&self) -> Result<Option<&'a T>, DependencyError> {
303        match self.entries.as_slice() {
304            [] => Ok(None),
305            [entry] => Ok(Some(*entry)),
306            _ => Err(DependencyError::Ambiguous {
307                selection: self.label(),
308                matches: self
309                    .entries
310                    .iter()
311                    .map(|entry| entry.description())
312                    .collect(),
313            }),
314        }
315    }
316    /// Iterates all matching results in snapshot order, including zero matches.
317    pub fn iter(&self) -> impl ExactSizeIterator<Item = &'a T> + '_ {
318        self.entries.iter().copied()
319    }
320    fn label(&self) -> String {
321        format!(
322            "{} [{}]",
323            std::any::type_name::<T>(),
324            self.filters.join(", ")
325        )
326    }
327}
328
329impl Selection<'_, RecordingDependency> {
330    /// Restricts recordings to an exact execution-unit registration key.
331    pub fn execution_unit(self, key: &str) -> Self {
332        self.filter(format!("execution_unit={key:?}"), |entry| {
333            entry.execution_unit == key
334        })
335    }
336    /// Restricts recordings to an exact member identity.
337    pub fn member(self, member: &str) -> Self {
338        self.filter(format!("member={member:?}"), |entry| entry.member == member)
339    }
340}
341
342/// A completed member recording.
343#[derive(Clone, Debug)]
344pub struct RecordingDependency {
345    source: Source,
346    execution_unit: String,
347    member: String,
348    final_iteration: u64,
349    directory: PathBuf,
350}
351impl RecordingDependency {
352    /// Declared phase key.
353    pub fn phase(&self) -> &str {
354        &self.source.phase
355    }
356    /// Runtime-generated task identity.
357    pub fn task(&self) -> &str {
358        &self.source.task
359    }
360    /// Execution-unit registration key.
361    pub fn execution_unit(&self) -> &str {
362        &self.execution_unit
363    }
364    /// Member identity within its execution unit.
365    pub fn member(&self) -> &str {
366        &self.member
367    }
368    /// Final scientific iteration.
369    pub fn final_iteration(&self) -> u64 {
370        self.final_iteration
371    }
372    /// Completed recording directory.
373    pub fn directory(&self) -> &Path {
374        &self.directory
375    }
376}
377impl sealed::Sealed for RecordingDependency {}
378impl Dependency for RecordingDependency {
379    fn phase(&self) -> &str {
380        self.phase()
381    }
382    fn task(&self) -> &str {
383        self.task()
384    }
385    fn description(&self) -> String {
386        format!("{}/{}", self.phase(), self.task()) + &format!("/{}", self.member)
387    }
388}
389
390/// A completed external executable or Python task.
391#[derive(Clone, Debug)]
392pub struct ProgramDependency {
393    source: Source,
394    directory: PathBuf,
395    executable: PathBuf,
396    python_script: Option<PathBuf>,
397}
398impl ProgramDependency {
399    /// Declared phase key.
400    pub fn phase(&self) -> &str {
401        &self.source.phase
402    }
403    /// Runtime-generated task identity.
404    pub fn task(&self) -> &str {
405        &self.source.task
406    }
407    /// Standard artifacts directory, excluding logs and snapshots.
408    pub fn directory(&self) -> &Path {
409        &self.directory
410    }
411    /// Resolved launcher executable.
412    pub fn executable(&self) -> &Path {
413        &self.executable
414    }
415    /// Canonical Python script when this was a Python task.
416    pub fn python_script(&self) -> Option<&Path> {
417        self.python_script.as_deref()
418    }
419}
420impl sealed::Sealed for ProgramDependency {}
421impl Dependency for ProgramDependency {
422    fn phase(&self) -> &str {
423        self.phase()
424    }
425    fn task(&self) -> &str {
426        self.task()
427    }
428    fn description(&self) -> String {
429        format!("{}/{}", self.phase(), self.task())
430    }
431}
432
433/// An aggregate converted NPY batch.
434#[derive(Clone, Debug)]
435pub struct NpyDependency {
436    source: Source,
437    directory: PathBuf,
438}
439impl NpyDependency {
440    /// Declared phase key.
441    pub fn phase(&self) -> &str {
442        &self.source.phase
443    }
444    /// Runtime-generated task identity.
445    pub fn task(&self) -> &str {
446        &self.source.task
447    }
448    /// Verified-reader entry directory containing the batch manifest.
449    pub fn directory(&self) -> &Path {
450        &self.directory
451    }
452}
453impl sealed::Sealed for NpyDependency {}
454impl Dependency for NpyDependency {
455    fn phase(&self) -> &str {
456        self.phase()
457    }
458    fn task(&self) -> &str {
459        self.task()
460    }
461    fn description(&self) -> String {
462        format!("{}/{}", self.phase(), self.task())
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469    fn snapshot() -> Value {
470        serde_json::json!([
471            {"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"}]}}]},
472            {"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"}]}}]}
473        ])
474    }
475    #[test]
476    fn selection_is_explicit_and_preserves_order_and_source() {
477        let deps = Dependencies::from_json(snapshot()).unwrap();
478        assert!(
479            matches!(deps.recordings().execution_unit("init").one(), Err(DependencyError::Ambiguous { matches, .. }) if matches == ["initialize/a/one", "other/b/one"])
480        );
481        let selected = deps
482            .recordings()
483            .in_phase("initialize")
484            .member("one")
485            .one()
486            .unwrap();
487        assert_eq!(selected.directory(), Path::new("/run/a"));
488        assert_eq!(
489            deps.recordings()
490                .iter()
491                .map(|r| r.final_iteration())
492                .collect::<Vec<_>>(),
493            [4, 5]
494        );
495        assert!(
496            deps.recordings()
497                .in_phase("missing")
498                .optional()
499                .unwrap()
500                .is_none()
501        );
502        assert!(matches!(
503            deps.recordings().in_phase("missing").one(),
504            Err(DependencyError::Missing { .. })
505        ));
506        assert_eq!(deps.raw_json(), &snapshot());
507    }
508    #[test]
509    fn malformed_known_results_fail_and_extensions_remain_available() {
510        let mut value = snapshot();
511        value[0]["tasks"][0]["workload"]["members"][0]["final_iteration"] = "bad".into();
512        assert!(Dependencies::from_json(value).is_err());
513        let value = serde_json::json!([{"phase":"extension","tasks":[{"identity":"task","output_directory":"/output","workload":{"kind":"future","extra":1}}]}]);
514        let deps = Dependencies::from_json(value.clone()).unwrap();
515        assert_eq!(deps.raw_json(), &value);
516        assert_eq!(deps.recordings().iter().len(), 0);
517    }
518}