modewise_pipeline/
executor.rs

1use std::collections::{BTreeMap, HashMap};
2use std::sync::Arc;
3use std::time::Instant;
4
5use serde_json::json;
6
7use crate::plan::{PlannedStep, Source};
8use crate::{
9    Artifact, ArtifactKey, ArtifactKind, ArtifactStore, Inputs, PipelineError, Plan, RunManifest,
10    StepRecord,
11};
12
13pub struct RunResult {
14    pub manifest: RunManifest,
15    outputs: BTreeMap<String, ArtifactKey>,
16}
17
18impl RunResult {
19    /// All step outputs, by `step.output`.
20    pub fn outputs(&self) -> &BTreeMap<String, ArtifactKey> {
21        &self.outputs
22    }
23
24    /// Key of a step output, by `step.output`, or by `step` when it has one output.
25    pub fn output_key(&self, reference: &str) -> Option<&ArtifactKey> {
26        if let Some(key) = self.outputs.get(reference) {
27            return Some(key);
28        }
29        let prefix = format!("{reference}.");
30        let mut matches = self
31            .outputs
32            .iter()
33            .filter(|(name, _)| name.starts_with(&prefix));
34        match (matches.next(), matches.next()) {
35            (Some((_, key)), None) => Some(key),
36            _ => None,
37        }
38    }
39}
40
41/// Runs a plan. Steps whose outputs are already in the store are skipped. Inputs are never
42/// stored: the caller still has them, so only their keys are recorded.
43pub fn run(
44    plan: &Plan,
45    inputs: &BTreeMap<String, Artifact>,
46    store: &dyn ArtifactStore,
47) -> Result<RunResult, PipelineError> {
48    if let Some(extra) = inputs.keys().find(|k| !plan.inputs.contains(k)) {
49        return Err(PipelineError::UnexpectedInput(extra.clone()));
50    }
51    let mut keys = BTreeMap::new();
52    for name in &plan.inputs {
53        let artifact = inputs
54            .get(name)
55            .ok_or_else(|| PipelineError::MissingInput(name.clone()))?;
56        let key = match (plan.input_kind(name), artifact) {
57            (Some(ArtifactKind::Series), Artifact::Series(s)) => ArtifactKey::of_series(s),
58            (Some(ArtifactKind::Events), Artifact::Events(e)) => ArtifactKey::of_events(e),
59            (Some(ArtifactKind::Channels), Artifact::Channels(t)) => ArtifactKey::of_channels(t),
60            (expected, found) => {
61                return Err(PipelineError::InputKind {
62                    name: name.clone(),
63                    expected: expected.unwrap_or(ArtifactKind::Series),
64                    found: found.kind(),
65                });
66            }
67        };
68        keys.insert(name.clone(), key);
69    }
70
71    let mut manifest = RunManifest {
72        pipeline: plan.name.clone(),
73        modewise_version: env!("CARGO_PKG_VERSION").to_string(),
74        inputs: keys.clone(),
75        steps: Vec::with_capacity(plan.steps.len()),
76    };
77    // Every key follows from the recipe alone, so they are all known before anything runs.
78    let mut outputs = BTreeMap::new();
79    let mut step_keys = Vec::with_capacity(plan.steps.len());
80    for step in &plan.steps {
81        let k = keys_of(step, &keys);
82        for (name, key) in &k.outputs {
83            let full = format!("{}.{name}", step.id);
84            keys.insert(full.clone(), key.clone());
85            outputs.insert(full, key.clone());
86        }
87        step_keys.push(k);
88    }
89
90    // A stored step runs when its outputs are missing; an unstored one only when a step that
91    // runs needs it. Later steps decide first, so walk backwards.
92    let consumers = |i: usize| {
93        let id = &plan.steps[i].id;
94        (i + 1..plan.steps.len()).filter(move |&j| {
95            plan.steps[j]
96                .inputs
97                .values()
98                .any(|s| matches!(s, Source::Step { step, .. } if step == id))
99        })
100    };
101    let mut needed = vec![false; plan.steps.len()];
102    for i in (0..plan.steps.len()).rev() {
103        needed[i] = if plan.steps[i].keep {
104            let mut missing = false;
105            for key in step_keys[i].outputs.values() {
106                missing |= !store.contains(key)?;
107            }
108            missing
109        } else {
110            consumers(i).any(|j| needed[j])
111        };
112    }
113
114    // Inputs and unstored outputs live here until their last consumer has run.
115    let mut scratch: HashMap<ArtifactKey, Arc<Artifact>> = HashMap::new();
116    let mut uses: HashMap<ArtifactKey, usize> = HashMap::new();
117    for (_, k) in step_keys.iter().enumerate().filter(|(i, _)| needed[*i]) {
118        for key in k.inputs.values() {
119            *uses.entry(key.clone()).or_default() += 1;
120        }
121    }
122    for name in &plan.inputs {
123        let key = &keys[name];
124        if uses.contains_key(key) {
125            scratch.insert(key.clone(), Arc::new(inputs[name].clone()));
126        }
127    }
128    for (i, step) in plan.steps.iter().enumerate() {
129        let k = &step_keys[i];
130        let started = Instant::now();
131        if needed[i] {
132            execute(step, k, store, &mut scratch)?;
133            for key in k.inputs.values() {
134                if let Some(n) = uses.get_mut(key) {
135                    *n -= 1;
136                    if *n == 0 {
137                        scratch.remove(key);
138                    }
139                }
140            }
141        }
142        let descriptor = step.op.descriptor();
143        manifest.steps.push(StepRecord {
144            id: step.id.clone(),
145            op: descriptor.name.to_string(),
146            op_version: descriptor.version.to_string(),
147            params: step.params.clone(),
148            inputs: k.inputs.clone(),
149            outputs: k.outputs.clone(),
150            cached: !needed[i],
151            stored: step.keep,
152            seconds: started.elapsed().as_secs_f64(),
153        });
154    }
155    Ok(RunResult { manifest, outputs })
156}
157
158struct StepKeys {
159    inputs: BTreeMap<String, ArtifactKey>,
160    outputs: BTreeMap<String, ArtifactKey>,
161}
162
163/// A step's input and output keys: a hash of the operation, its version, its parameters and its
164/// input keys, so equal recipes share outputs.
165fn keys_of(step: &PlannedStep, keys: &BTreeMap<String, ArtifactKey>) -> StepKeys {
166    let descriptor = step.op.descriptor();
167    let inputs: BTreeMap<String, ArtifactKey> = step
168        .inputs
169        .iter()
170        .map(|(port, source)| (port.clone(), keys[&source.name()].clone()))
171        .collect();
172    let identity = json!({
173        "op": descriptor.name,
174        "version": descriptor.version,
175        "params": step.params,
176        "inputs": inputs,
177    });
178    let step_key = ArtifactKey::from_bytes(identity.to_string().as_bytes());
179    let outputs = descriptor
180        .outputs
181        .iter()
182        .map(|p| {
183            let key = ArtifactKey::from_bytes(format!("{step_key}/{}", p.name).as_bytes());
184            (p.name.to_string(), key)
185        })
186        .collect();
187    StepKeys { inputs, outputs }
188}
189
190fn execute(
191    step: &PlannedStep,
192    keys: &StepKeys,
193    store: &dyn ArtifactStore,
194    scratch: &mut HashMap<ArtifactKey, Arc<Artifact>>,
195) -> Result<(), PipelineError> {
196    let descriptor = step.op.descriptor();
197    let failed = |message: String| PipelineError::StepFailed {
198        step: step.id.clone(),
199        message,
200    };
201    let mut inputs = Inputs::new();
202    for (port, key) in &keys.inputs {
203        let artifact = match scratch.get(key) {
204            Some(a) => Arc::clone(a),
205            None => store
206                .get(key)?
207                .ok_or_else(|| failed(format!("input {port:?} is missing from the store")))?,
208        };
209        inputs.insert(port.clone(), artifact);
210    }
211    let mut produced = step.op.run(&step.params, &inputs).map_err(failed)?;
212    for port in descriptor.outputs {
213        let artifact = produced
214            .remove(port.name)
215            .ok_or_else(|| failed(format!("operation did not produce {:?}", port.name)))?;
216        let expected = step.output_kinds[port.name];
217        if artifact.kind() != expected {
218            return Err(failed(format!(
219                "output {:?} should be {}, got {}",
220                port.name,
221                expected,
222                artifact.kind()
223            )));
224        }
225        let key = &keys.outputs[port.name];
226        if step.keep {
227            store.put(key, Arc::new(artifact))?;
228        } else {
229            scratch.insert(key.clone(), Arc::new(artifact));
230        }
231    }
232    if let Some(extra) = produced.keys().next() {
233        return Err(failed(format!(
234            "operation produced undeclared output {extra:?}"
235        )));
236    }
237    Ok(())
238}
239
240#[cfg(test)]
241mod tests {
242    use std::sync::atomic::Ordering;
243
244    use super::*;
245    use crate::PipelineSpec;
246    use crate::test_support::{TestStore, ops, series};
247
248    const CHAIN: &str = r#"
249        [pipeline]
250        name = "chain"
251        inputs = ["x"]
252
253        [[step]]
254        id = "first"
255        op = "scale"
256        input = "x"
257        params = { factor = 2.0 }
258
259        [[step]]
260        id = "second"
261        op = "scale"
262        input = "first"
263        params = { factor = FACTOR }
264    "#;
265
266    fn chain(factor: f64) -> PipelineSpec {
267        PipelineSpec::from_toml(&CHAIN.replace("FACTOR", &format!("{factor:?}"))).unwrap()
268    }
269
270    fn inputs(values: &[f64]) -> BTreeMap<String, Artifact> {
271        BTreeMap::from([("x".to_string(), Artifact::Series(series(values)))])
272    }
273
274    fn cached(result: &RunResult) -> Vec<bool> {
275        result.manifest.steps.iter().map(|s| s.cached).collect()
276    }
277
278    fn unkept(second_factor: f64) -> PipelineSpec {
279        let text = CHAIN
280            .replace("FACTOR", &format!("{second_factor:?}"))
281            .replacen(
282                "params = { factor = 2.0 }",
283                "params = { factor = 2.0 }\n        keep = false",
284                1,
285            );
286        PipelineSpec::from_toml(&text).unwrap()
287    }
288
289    #[test]
290    fn inputs_are_used_but_never_stored() {
291        let ops = ops();
292        let store = TestStore::default();
293        let plan = Plan::new(&chain(3.0), &ops.registry).unwrap();
294        let result = run(&plan, &inputs(&[1.0, 2.0]), &store).unwrap();
295        assert!(!store.contains(&result.manifest.inputs["x"]).unwrap());
296        let Some(Artifact::Series(out)) = store
297            .get(result.output_key("second").unwrap())
298            .unwrap()
299            .as_deref()
300            .cloned()
301        else {
302            panic!("second is stored")
303        };
304        assert_eq!(out.data().row(0).to_vec(), [6.0, 12.0]);
305    }
306
307    #[test]
308    fn unkept_outputs_stay_in_memory_and_are_recomputed_only_when_needed() {
309        let ops = ops();
310        let store = TestStore::default();
311        let plan = Plan::new(&unkept(3.0), &ops.registry).unwrap();
312        let first = run(&plan, &inputs(&[1.0, 2.0]), &store).unwrap();
313        assert_eq!(cached(&first), [false, false]);
314        assert!(
315            !store.contains(first.output_key("first").unwrap()).unwrap(),
316            "never written"
317        );
318        let Some(Artifact::Series(out)) = store
319            .get(first.output_key("second").unwrap())
320            .unwrap()
321            .as_deref()
322            .cloned()
323        else {
324            panic!("missing output");
325        };
326        assert_eq!(
327            out.data().row(0).to_vec(),
328            [6.0, 12.0],
329            "computed from the in-memory output"
330        );
331        assert_eq!(
332            first
333                .manifest
334                .steps
335                .iter()
336                .map(|s| s.stored)
337                .collect::<Vec<_>>(),
338            [false, true]
339        );
340
341        let again = run(&plan, &inputs(&[1.0, 2.0]), &store).unwrap();
342        assert_eq!(
343            cached(&again),
344            [true, true],
345            "nothing downstream is missing, so nothing runs"
346        );
347        assert_eq!(ops.scale.runs.load(Ordering::SeqCst), 2);
348
349        let changed = run(
350            &Plan::new(&unkept(4.0), &ops.registry).unwrap(),
351            &inputs(&[1.0, 2.0]),
352            &store,
353        )
354        .unwrap();
355        assert_eq!(
356            cached(&changed),
357            [false, false],
358            "the unkept step reruns because the next one must"
359        );
360        assert_eq!(ops.scale.runs.load(Ordering::SeqCst), 4);
361    }
362
363    #[test]
364    fn an_unkept_step_nothing_uses_is_refused() {
365        let ops = ops();
366        let text = CHAIN.replace("FACTOR", "3.0").replace(
367            "params = { factor = 3.0 }",
368            "params = { factor = 3.0 }\n        keep = false",
369        );
370        let err = Plan::new(&PipelineSpec::from_toml(&text).unwrap(), &ops.registry)
371            .err()
372            .unwrap();
373        assert!(
374            matches!(err, PipelineError::UnusedTransient(ref id) if id == "second"),
375            "{err}"
376        );
377    }
378
379    #[test]
380    fn an_unkept_output_serves_every_step_that_uses_it() {
381        let ops = ops();
382        let store = TestStore::default();
383        let text = r#"
384            [pipeline]
385            name = "fork"
386            inputs = ["x"]
387
388            [[step]]
389            id = "a"
390            op = "scale"
391            input = "x"
392            params = { factor = 2.0 }
393            keep = false
394
395            [[step]]
396            id = "b"
397            op = "scale"
398            input = "a"
399            params = { factor = 3.0 }
400
401            [[step]]
402            id = "c"
403            op = "scale"
404            input = "a"
405            params = { factor = 5.0 }
406        "#;
407        let plan = Plan::new(&PipelineSpec::from_toml(text).unwrap(), &ops.registry).unwrap();
408        let result = run(&plan, &inputs(&[1.0, 2.0]), &store).unwrap();
409        for (id, want) in [("b", [6.0, 12.0]), ("c", [10.0, 20.0])] {
410            let Some(Artifact::Series(out)) = store
411                .get(result.output_key(id).unwrap())
412                .unwrap()
413                .as_deref()
414                .cloned()
415            else {
416                panic!("missing {id}");
417            };
418            assert_eq!(out.data().row(0).to_vec(), want);
419        }
420    }
421
422    #[test]
423    fn chains_of_unkept_steps_are_computed_in_memory() {
424        let ops = ops();
425        let store = TestStore::default();
426        let text = r#"
427            [pipeline]
428            name = "three"
429            inputs = ["x"]
430
431            [[step]]
432            id = "a"
433            op = "scale"
434            input = "x"
435            params = { factor = 2.0 }
436            keep = false
437
438            [[step]]
439            id = "b"
440            op = "scale"
441            input = "a"
442            params = { factor = 3.0 }
443            keep = false
444
445            [[step]]
446            id = "c"
447            op = "scale"
448            input = "b"
449            params = { factor = 5.0 }
450        "#;
451        let plan = Plan::new(&PipelineSpec::from_toml(text).unwrap(), &ops.registry).unwrap();
452        let result = run(&plan, &inputs(&[1.0, 2.0]), &store).unwrap();
453        let Some(Artifact::Series(out)) = store
454            .get(result.output_key("c").unwrap())
455            .unwrap()
456            .as_deref()
457            .cloned()
458        else {
459            panic!("missing output");
460        };
461        assert_eq!(out.data().row(0).to_vec(), [30.0, 60.0]);
462        for id in ["a", "b"] {
463            assert!(!store.contains(result.output_key(id).unwrap()).unwrap());
464        }
465    }
466
467    #[test]
468    fn computes_then_reuses_everything() {
469        let ops = ops();
470        let store = TestStore::default();
471        let plan = Plan::new(&chain(3.0), &ops.registry).unwrap();
472
473        let first = run(&plan, &inputs(&[1.0, 2.0]), &store).unwrap();
474        assert_eq!(cached(&first), [false, false]);
475        let key = first.output_key("second").unwrap();
476        let Some(Artifact::Series(out)) = store.get(key).unwrap().as_deref().cloned() else {
477            panic!("missing output");
478        };
479        assert_eq!(out.data().row(0).to_vec(), [6.0, 12.0]);
480
481        let second = run(&plan, &inputs(&[1.0, 2.0]), &store).unwrap();
482        assert_eq!(cached(&second), [true, true]);
483        assert_eq!(ops.scale.runs.load(Ordering::SeqCst), 2);
484        assert_eq!(second.output_key("second"), first.output_key("second"));
485    }
486
487    #[test]
488    fn param_change_reruns_only_that_step_and_later() {
489        let ops = ops();
490        let store = TestStore::default();
491        run(
492            &Plan::new(&chain(3.0), &ops.registry).unwrap(),
493            &inputs(&[1.0, 2.0]),
494            &store,
495        )
496        .unwrap();
497
498        let changed = run(
499            &Plan::new(&chain(4.0), &ops.registry).unwrap(),
500            &inputs(&[1.0, 2.0]),
501            &store,
502        )
503        .unwrap();
504        assert_eq!(cached(&changed), [true, false]);
505    }
506
507    #[test]
508    fn new_input_data_reruns_everything() {
509        let ops = ops();
510        let store = TestStore::default();
511        let plan = Plan::new(&chain(3.0), &ops.registry).unwrap();
512        run(&plan, &inputs(&[1.0, 2.0]), &store).unwrap();
513        let changed = run(&plan, &inputs(&[1.0, 2.5]), &store).unwrap();
514        assert_eq!(cached(&changed), [false, false]);
515    }
516
517    #[test]
518    fn rejects_missing_and_unexpected_inputs() {
519        let ops = ops();
520        let store = TestStore::default();
521        let plan = Plan::new(&chain(3.0), &ops.registry).unwrap();
522        let missing = run(&plan, &BTreeMap::new(), &store);
523        assert!(matches!(missing, Err(PipelineError::MissingInput(n)) if n == "x"));
524
525        let mut extra = inputs(&[1.0, 2.0]);
526        extra.insert("y".into(), Artifact::Series(series(&[1.0, 2.0])));
527        assert!(
528            matches!(run(&plan, &extra, &store), Err(PipelineError::UnexpectedInput(n)) if n == "y")
529        );
530    }
531
532    fn single_step(op: &str, params: &str) -> PipelineSpec {
533        PipelineSpec::from_toml(&format!(
534            "[pipeline]\nname = \"t\"\ninputs = [\"x\"]\n[[step]]\nid = \"s\"\nop = \"{op}\"\ninput = \"x\"\nparams = {params}\n"
535        ))
536        .unwrap()
537    }
538
539    #[test]
540    fn rejects_operations_that_break_their_contract() {
541        let ops = ops();
542        for (lie, expected) in [
543            ("missing", "did not produce"),
544            ("wrong_kind", "should be series"),
545            ("extra", "undeclared output"),
546            ("fail", "asked to fail"),
547        ] {
548            let plan = Plan::new(
549                &single_step("liar", &format!("{{ lie = \"{lie}\" }}")),
550                &ops.registry,
551            )
552            .unwrap();
553            let err = run(&plan, &inputs(&[1.0, 2.0]), &TestStore::default())
554                .err()
555                .unwrap();
556            assert!(
557                matches!(&err, PipelineError::StepFailed { step, message } if step == "s" && message.contains(expected)),
558                "{lie}: {err}"
559            );
560        }
561    }
562
563    #[test]
564    fn missing_input_in_store_fails_the_step() {
565        let ops = ops();
566        let plan = Plan::new(&chain(3.0), &ops.registry).unwrap();
567        let err = run(
568            &plan,
569            &inputs(&[1.0, 2.0]),
570            &crate::test_support::ForgetfulStore,
571        )
572        .err()
573        .unwrap();
574        assert!(
575            matches!(&err, PipelineError::StepFailed { message, .. } if message.contains("missing from the store")),
576            "{err}"
577        );
578    }
579
580    #[test]
581    fn output_keys_resolve_by_full_or_short_name() {
582        let ops = ops();
583        let spec = PipelineSpec::from_toml(
584            "[pipeline]\nname = \"t\"\ninputs = [\"x\"]\n[[step]]\nid = \"split\"\nop = \"split\"\ninput = \"x\"\n[[step]]\nid = \"one\"\nop = \"scale\"\ninput = \"x\"\n",
585        )
586        .unwrap();
587        let result = run(
588            &Plan::new(&spec, &ops.registry).unwrap(),
589            &inputs(&[1.0, 2.0]),
590            &TestStore::default(),
591        )
592        .unwrap();
593        assert_eq!(result.outputs().len(), 3);
594        assert!(result.output_key("split.low").is_some());
595        assert!(
596            result.output_key("split").is_none(),
597            "two outputs, so the short name is ambiguous"
598        );
599        assert_eq!(result.output_key("one"), result.output_key("one.signal"));
600        assert!(result.output_key("nope").is_none());
601    }
602
603    #[test]
604    fn manifest_records_resolved_params() {
605        let ops = ops();
606        let store = TestStore::default();
607        let plan = Plan::new(&chain(3.0), &ops.registry).unwrap();
608        let result = run(&plan, &inputs(&[1.0, 2.0]), &store).unwrap();
609        let outputs = result.manifest.outputs();
610        assert_eq!(
611            outputs.keys().collect::<Vec<_>>(),
612            ["first.signal", "second.signal"]
613        );
614        assert_eq!(&outputs, result.outputs());
615        let json = result.manifest.to_json();
616        assert!(json.contains("\"factor\": 3.0"), "{json}");
617        assert!(json.contains("\"pipeline\": \"chain\""));
618    }
619
620    mod properties {
621        use proptest::prelude::*;
622
623        use super::*;
624
625        proptest! {
626            #[test]
627            fn keys_are_stable_and_sensitive_to_every_sample(
628                values in prop::collection::vec(-1e6f64..1e6, 2..32),
629                at in any::<prop::sample::Index>(),
630            ) {
631                let ops = ops();
632                let plan = Plan::new(&chain(3.0), &ops.registry).unwrap();
633                let first = run(&plan, &inputs(&values), &TestStore::default()).unwrap();
634                let again = run(&plan, &inputs(&values), &TestStore::default()).unwrap();
635                prop_assert_eq!(first.outputs(), again.outputs());
636
637                let mut changed = values.clone();
638                let i = at.index(changed.len());
639                changed[i] += 1.0;
640                let other = run(&plan, &inputs(&changed), &TestStore::default()).unwrap();
641                prop_assert_ne!(first.output_key("second"), other.output_key("second"));
642            }
643        }
644    }
645}