scientific_workflow/task/
dependencies.rs1use serde::Deserialize;
7use serde_json::Value;
8use std::path::{Path, PathBuf};
9use thiserror::Error;
10
11#[derive(Debug, Error)]
13#[non_exhaustive]
14pub enum DependencyError {
15 #[error("missing {variable}; run this program through Workflow's standard study layout")]
17 MissingEnvironment {
18 variable: &'static str,
20 },
21 #[error("cannot read dependency snapshot `{path}`")]
23 Io {
24 path: PathBuf,
26 #[source]
28 source: std::io::Error,
29 },
30 #[error("invalid dependency snapshot: {0}")]
32 Invalid(String),
33 #[error("no dependency matches {selection}")]
35 Missing {
36 selection: String,
38 },
39 #[error("ambiguous dependency selection {selection}: {matches:?}; select a phase or task")]
41 Ambiguous {
42 selection: String,
44 matches: Vec<String>,
46 },
47}
48
49#[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 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 _ => {} }
182 }
183 }
184 Ok(result)
185 }
186
187 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 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 pub const fn raw_json(&self) -> &Value {
224 &self.raw
225 }
226 pub fn recordings(&self) -> Selection<'_, RecordingDependency> {
228 Selection::new(&self.recordings)
229 }
230 pub fn programs(&self) -> Selection<'_, ProgramDependency> {
232 Selection::new(&self.programs)
233 }
234 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}
279pub trait Dependency: sealed::Sealed {
283 fn phase(&self) -> &str;
285 fn task(&self) -> &str;
287 fn description(&self) -> String;
289}
290
291#[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 pub fn in_phase(self, phase: &str) -> Self {
311 self.filter(format!("phase={phase:?}"), |entry| entry.phase() == phase)
312 }
313 pub fn task(self, task: &str) -> Self {
315 self.filter(format!("task={task:?}"), |entry| entry.task() == task)
316 }
317 pub fn one(&self) -> Result<&'a T, DependencyError> {
319 self.optional()?.ok_or_else(|| DependencyError::Missing {
320 selection: self.label(),
321 })
322 }
323 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 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 pub fn execution_unit(self, key: &str) -> Self {
354 self.filter(format!("execution_unit={key:?}"), |entry| {
355 entry.execution_unit == key
356 })
357 }
358 pub fn member(self, member: &str) -> Self {
360 self.filter(format!("member={member:?}"), |entry| entry.member == member)
361 }
362}
363
364#[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 pub fn phase(&self) -> &str {
376 &self.source.phase
377 }
378 pub fn task(&self) -> &str {
380 &self.source.task
381 }
382 pub fn execution_unit(&self) -> &str {
384 &self.execution_unit
385 }
386 pub fn member(&self) -> &str {
388 &self.member
389 }
390 pub fn final_iteration(&self) -> u64 {
392 self.final_iteration
393 }
394 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#[derive(Clone, Debug)]
414pub struct ProgramDependency {
415 source: Source,
416 directory: PathBuf,
417 executable: PathBuf,
418 python_script: Option<PathBuf>,
419}
420impl ProgramDependency {
421 pub fn phase(&self) -> &str {
423 &self.source.phase
424 }
425 pub fn task(&self) -> &str {
427 &self.source.task
428 }
429 pub fn directory(&self) -> &Path {
431 &self.directory
432 }
433 pub fn executable(&self) -> &Path {
435 &self.executable
436 }
437 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#[derive(Clone, Debug)]
457pub struct NpyDependency {
458 source: Source,
459 directory: PathBuf,
460}
461impl NpyDependency {
462 pub fn phase(&self) -> &str {
464 &self.source.phase
465 }
466 pub fn task(&self) -> &str {
468 &self.source.task
469 }
470 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}