1use 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 #[serde(default)]
66 artifacts: Option<crate::artifact::ArtifactLocator>,
67 identity: String,
68 output_directory: PathBuf,
69 workload: Value,
70}
71#[derive(Deserialize)]
72struct Member {
73 #[serde(default)]
74 artifacts: Option<crate::artifact::ArtifactLocator>,
75 identity: String,
76 final_iteration: u64,
77 output_directory: PathBuf,
78}
79#[derive(Deserialize)]
80struct Unit {
81 execution_unit: String,
82 members: Vec<Member>,
83}
84#[derive(Deserialize)]
85struct Program {
86 executable: PathBuf,
87 python_script: Option<PathBuf>,
88}
89#[derive(Deserialize)]
90struct Npy {
91 #[serde(default)]
92 artifacts: Option<crate::artifact::ArtifactLocator>,
93 processed_directory: PathBuf,
94}
95
96impl Dependencies {
97 pub fn from_json(raw: Value) -> Result<Self, DependencyError> {
99 let phases: Vec<Phase> = decode(raw.clone())?;
100 let mut result = Self {
101 raw,
102 recordings: Vec::new(),
103 programs: Vec::new(),
104 npy_batches: Vec::new(),
105 };
106 let mut phases_seen = std::collections::HashSet::new();
107 for phase in phases {
108 name(&phase.phase)?;
109 if !phases_seen.insert(phase.phase.clone()) {
110 return Err(DependencyError::Invalid("duplicate phase identity".into()));
111 }
112 let mut tasks_seen = std::collections::HashSet::new();
113 for task in phase.tasks {
114 name(&task.identity)?;
115 path(&task.output_directory)?;
116 if !tasks_seen.insert(task.identity.clone()) {
117 return Err(DependencyError::Invalid(
118 "duplicate task identity in phase".into(),
119 ));
120 }
121 let source = Source {
122 phase: phase.phase.clone(),
123 task: task.identity,
124 };
125 let kind = task
126 .workload
127 .get("kind")
128 .and_then(Value::as_str)
129 .ok_or_else(|| {
130 DependencyError::Invalid("workload.kind must be a nonempty string".into())
131 })?;
132 name(kind)?;
133 match kind {
134 "execution_unit" => {
135 let unit: Unit = decode(task.workload)?;
136 name(&unit.execution_unit)?;
137 let mut members_seen = std::collections::HashSet::new();
138 if unit.members.is_empty() {
139 return Err(DependencyError::Invalid(
140 "execution unit has no members".into(),
141 ));
142 }
143 for member in unit.members {
144 name(&member.identity)?;
145 path(&member.output_directory)?;
146 if !members_seen.insert(member.identity.clone()) {
147 return Err(DependencyError::Invalid(
148 "duplicate member identity".into(),
149 ));
150 }
151 result.recordings.push(RecordingDependency {
152 source: source.clone(),
153 execution_unit: unit.execution_unit.clone(),
154 member: member.identity,
155 final_iteration: member.final_iteration,
156 artifacts: member.artifacts,
157 directory: member.output_directory,
158 });
159 }
160 }
161 "program" | "python" => {
162 let program: Program = decode(task.workload.clone())?;
163 path(&program.executable)?;
164 if kind == "python" && program.python_script.is_none() {
165 return Err(DependencyError::Invalid(
166 "python workload requires python_script".into(),
167 ));
168 }
169 if let Some(script) = &program.python_script {
170 path(script)?;
171 }
172 result.programs.push(ProgramDependency {
173 source,
174 artifacts: task.artifacts,
175 directory: task.output_directory.join("artifacts"),
176 executable: program.executable,
177 python_script: program.python_script,
178 });
179 }
180 "npy" => {
181 let npy: Npy = decode(task.workload)?;
182 path(&npy.processed_directory)?;
183 result.npy_batches.push(NpyDependency {
184 source,
185 artifacts: npy.artifacts,
186 directory: npy.processed_directory,
187 });
188 }
189 _ => {} }
191 }
192 }
193 Ok(result)
194 }
195
196 pub fn load(path: &Path) -> Result<Self, DependencyError> {
201 if path
202 .file_name()
203 .is_none_or(|name| name != "workflow-dependencies.json")
204 {
205 return Err(DependencyError::Invalid(
206 "expected canonical workflow-dependencies.json snapshot path".into(),
207 ));
208 }
209 let directory = path
210 .parent()
211 .ok_or_else(|| DependencyError::Invalid("snapshot path has no parent".into()))?;
212 let inputs =
213 crate::persistence::TaskInputSnapshots::open(directory).map_err(snapshot_error)?;
214 let [_, bytes] = inputs.read_verified().map_err(snapshot_error)?;
215 Self::from_json(
216 serde_json::from_slice(&bytes)
217 .map_err(|error| DependencyError::Invalid(error.to_string()))?,
218 )
219 }
220
221 pub fn from_env() -> Result<Self, DependencyError> {
223 let path = std::env::var_os("WORKFLOW_DEPENDENCIES_PATH").ok_or(
224 DependencyError::MissingEnvironment {
225 variable: "WORKFLOW_DEPENDENCIES_PATH",
226 },
227 )?;
228 Self::load(Path::new(&path))
229 }
230
231 pub const fn raw_json(&self) -> &Value {
233 &self.raw
234 }
235 pub fn recordings(&self) -> Selection<'_, RecordingDependency> {
237 Selection::new(&self.recordings)
238 }
239 pub fn programs(&self) -> Selection<'_, ProgramDependency> {
241 Selection::new(&self.programs)
242 }
243 pub fn npy_batches(&self) -> Selection<'_, NpyDependency> {
245 Selection::new(&self.npy_batches)
246 }
247}
248
249fn snapshot_error(error: crate::persistence::PersistenceError) -> DependencyError {
250 match error {
251 crate::persistence::PersistenceError::Io { path, source, .. } => {
252 DependencyError::Io { path, source }
253 }
254 other => DependencyError::Invalid(other.to_string()),
255 }
256}
257
258fn decode<T: serde::de::DeserializeOwned>(value: Value) -> Result<T, DependencyError> {
259 serde_json::from_value(value).map_err(|error| DependencyError::Invalid(error.to_string()))
260}
261fn name(value: &str) -> Result<(), DependencyError> {
262 if value.is_empty() || value.trim() != value {
263 return Err(DependencyError::Invalid(
264 "identifiers must be nonempty without surrounding whitespace".into(),
265 ));
266 }
267 Ok(())
268}
269fn path(value: &Path) -> Result<(), DependencyError> {
270 if !value.is_absolute() {
271 return Err(DependencyError::Invalid(format!(
272 "expected absolute path, got {}",
273 value.display()
274 )));
275 }
276 Ok(())
277}
278
279#[derive(Clone, Debug)]
280struct Source {
281 phase: String,
282 task: String,
283}
284
285mod sealed {
286 pub trait Sealed {}
287}
288pub trait Dependency: sealed::Sealed {
292 fn phase(&self) -> &str;
294 fn task(&self) -> &str;
296 fn description(&self) -> String;
298}
299
300#[derive(Clone, Debug)]
302pub struct Selection<'a, T> {
303 entries: Vec<&'a T>,
304 filters: Vec<String>,
305}
306impl<'a, T: Dependency> Selection<'a, T> {
307 fn new(entries: &'a [T]) -> Self {
308 Self {
309 entries: entries.iter().collect(),
310 filters: Vec::new(),
311 }
312 }
313 fn filter(mut self, label: String, predicate: impl Fn(&T) -> bool) -> Self {
314 self.entries.retain(|entry| predicate(entry));
315 self.filters.push(label);
316 self
317 }
318 pub fn in_phase(self, phase: &str) -> Self {
320 self.filter(format!("phase={phase:?}"), |entry| entry.phase() == phase)
321 }
322 pub fn task(self, task: &str) -> Self {
324 self.filter(format!("task={task:?}"), |entry| entry.task() == task)
325 }
326 pub fn one(&self) -> Result<&'a T, DependencyError> {
328 self.optional()?.ok_or_else(|| DependencyError::Missing {
329 selection: self.label(),
330 })
331 }
332 pub fn optional(&self) -> Result<Option<&'a T>, DependencyError> {
334 match self.entries.as_slice() {
335 [] => Ok(None),
336 [entry] => Ok(Some(*entry)),
337 _ => Err(DependencyError::Ambiguous {
338 selection: self.label(),
339 matches: self
340 .entries
341 .iter()
342 .map(|entry| entry.description())
343 .collect(),
344 }),
345 }
346 }
347 pub fn iter(&self) -> impl ExactSizeIterator<Item = &'a T> + '_ {
349 self.entries.iter().copied()
350 }
351 fn label(&self) -> String {
352 format!(
353 "{} [{}]",
354 std::any::type_name::<T>(),
355 self.filters.join(", ")
356 )
357 }
358}
359
360impl Selection<'_, RecordingDependency> {
361 pub fn execution_unit(self, key: &str) -> Self {
363 self.filter(format!("execution_unit={key:?}"), |entry| {
364 entry.execution_unit == key
365 })
366 }
367 pub fn member(self, member: &str) -> Self {
369 self.filter(format!("member={member:?}"), |entry| entry.member == member)
370 }
371}
372
373#[derive(Clone, Debug)]
375pub struct RecordingDependency {
376 artifacts: Option<crate::artifact::ArtifactLocator>,
377 source: Source,
378 execution_unit: String,
379 member: String,
380 final_iteration: u64,
381 directory: PathBuf,
382}
383impl RecordingDependency {
384 pub fn artifacts(&self) -> std::io::Result<crate::artifact::ArtifactSet> {
386 self.artifacts
387 .as_ref()
388 .ok_or_else(|| {
389 std::io::Error::other(
390 "this snapshot contains only an explicit local workspace view",
391 )
392 })?
393 .open()
394 }
395
396 pub fn phase(&self) -> &str {
398 &self.source.phase
399 }
400 pub fn task(&self) -> &str {
402 &self.source.task
403 }
404 pub fn execution_unit(&self) -> &str {
406 &self.execution_unit
407 }
408 pub fn member(&self) -> &str {
410 &self.member
411 }
412 pub fn final_iteration(&self) -> u64 {
414 self.final_iteration
415 }
416 pub fn directory(&self) -> &Path {
418 &self.directory
419 }
420}
421impl sealed::Sealed for RecordingDependency {}
422impl Dependency for RecordingDependency {
423 fn phase(&self) -> &str {
424 self.phase()
425 }
426 fn task(&self) -> &str {
427 self.task()
428 }
429 fn description(&self) -> String {
430 format!("{}/{}", self.phase(), self.task()) + &format!("/{}", self.member)
431 }
432}
433
434#[derive(Clone, Debug)]
436pub struct ProgramDependency {
437 artifacts: Option<crate::artifact::ArtifactLocator>,
438 source: Source,
439 directory: PathBuf,
440 executable: PathBuf,
441 python_script: Option<PathBuf>,
442}
443impl ProgramDependency {
444 pub fn artifacts(&self) -> std::io::Result<crate::artifact::ArtifactSet> {
446 self.artifacts
447 .as_ref()
448 .ok_or_else(|| {
449 std::io::Error::other(
450 "this snapshot contains only an explicit local workspace view",
451 )
452 })?
453 .open()
454 }
455
456 pub fn phase(&self) -> &str {
458 &self.source.phase
459 }
460 pub fn task(&self) -> &str {
462 &self.source.task
463 }
464 pub fn directory(&self) -> &Path {
466 &self.directory
467 }
468 pub fn executable(&self) -> &Path {
470 &self.executable
471 }
472 pub fn python_script(&self) -> Option<&Path> {
474 self.python_script.as_deref()
475 }
476}
477impl sealed::Sealed for ProgramDependency {}
478impl Dependency for ProgramDependency {
479 fn phase(&self) -> &str {
480 self.phase()
481 }
482 fn task(&self) -> &str {
483 self.task()
484 }
485 fn description(&self) -> String {
486 format!("{}/{}", self.phase(), self.task())
487 }
488}
489
490#[derive(Clone, Debug)]
492pub struct NpyDependency {
493 artifacts: Option<crate::artifact::ArtifactLocator>,
494 source: Source,
495 directory: PathBuf,
496}
497impl NpyDependency {
498 pub fn artifacts(&self) -> std::io::Result<crate::artifact::ArtifactSet> {
500 self.artifacts
501 .as_ref()
502 .ok_or_else(|| {
503 std::io::Error::other(
504 "this snapshot contains only an explicit local workspace view",
505 )
506 })?
507 .open()
508 }
509
510 pub fn phase(&self) -> &str {
512 &self.source.phase
513 }
514 pub fn task(&self) -> &str {
516 &self.source.task
517 }
518 pub fn directory(&self) -> &Path {
520 &self.directory
521 }
522}
523impl sealed::Sealed for NpyDependency {}
524impl Dependency for NpyDependency {
525 fn phase(&self) -> &str {
526 self.phase()
527 }
528 fn task(&self) -> &str {
529 self.task()
530 }
531 fn description(&self) -> String {
532 format!("{}/{}", self.phase(), self.task())
533 }
534}
535
536#[cfg(test)]
537mod tests {
538 use super::*;
539 fn snapshot() -> Value {
540 serde_json::json!([
541 {"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"}]}}]},
542 {"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"}]}}]}
543 ])
544 }
545 #[test]
546 fn selection_is_explicit_and_preserves_order_and_source() {
547 let deps = Dependencies::from_json(snapshot()).unwrap();
548 assert!(
549 matches!(deps.recordings().execution_unit("init").one(), Err(DependencyError::Ambiguous { matches, .. }) if matches == ["initialize/a/one", "other/b/one"])
550 );
551 let selected = deps
552 .recordings()
553 .in_phase("initialize")
554 .member("one")
555 .one()
556 .unwrap();
557 assert_eq!(selected.directory(), Path::new("/run/a"));
558 assert_eq!(
559 deps.recordings()
560 .iter()
561 .map(|r| r.final_iteration())
562 .collect::<Vec<_>>(),
563 [4, 5]
564 );
565 assert!(
566 deps.recordings()
567 .in_phase("missing")
568 .optional()
569 .unwrap()
570 .is_none()
571 );
572 assert!(matches!(
573 deps.recordings().in_phase("missing").one(),
574 Err(DependencyError::Missing { .. })
575 ));
576 assert_eq!(deps.raw_json(), &snapshot());
577 }
578 #[test]
579 fn malformed_known_results_fail_and_extensions_remain_available() {
580 let mut value = snapshot();
581 value[0]["tasks"][0]["workload"]["members"][0]["final_iteration"] = "bad".into();
582 assert!(Dependencies::from_json(value).is_err());
583 let value = serde_json::json!([{"phase":"extension","tasks":[{"identity":"task","output_directory":"/output","workload":{"kind":"future","extra":1}}]}]);
584 let deps = Dependencies::from_json(value.clone()).unwrap();
585 assert_eq!(deps.raw_json(), &value);
586 assert_eq!(deps.recordings().iter().len(), 0);
587 }
588}