erio-workflow 0.1.0

DAG workflow engine for Erio
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! Workflow execution engine with parallel step execution.

use std::sync::Arc;

use tokio::sync::Mutex;

use std::path::Path;

use crate::WorkflowError;
use crate::builder::Workflow;
use crate::checkpoint::Checkpoint;
use crate::context::WorkflowContext;
use crate::step::StepOutput;

/// Executes workflows by resolving the DAG and running steps.
///
/// Independent steps are executed in parallel using tokio tasks.
#[derive(Debug, Clone, Default)]
pub struct WorkflowEngine;

impl WorkflowEngine {
    /// Creates a new workflow engine.
    pub fn new() -> Self {
        Self
    }

    /// Runs a workflow to completion.
    ///
    /// Steps are executed in parallel groups determined by the DAG.
    /// If any step fails, dependent steps are skipped and the error is returned.
    pub async fn run(&self, workflow: Workflow) -> Result<WorkflowContext, WorkflowError> {
        let groups = workflow.parallel_groups()?;
        let ctx = Arc::new(Mutex::new(WorkflowContext::new()));
        let failed: Arc<Mutex<Option<WorkflowError>>> = Arc::new(Mutex::new(None));

        for group in groups {
            // Check if a previous step already failed
            if failed.lock().await.is_some() {
                break;
            }

            if group.len() == 1 {
                // Single step — run directly (no spawn overhead)
                let step_id = group[0];
                let step = workflow.step(step_id).expect("DAG validated step exists");

                let mut ctx_guard = ctx.lock().await;
                match step.execute(&mut ctx_guard).await {
                    Ok(output) => {
                        ctx_guard.set_output(step_id, output);
                    }
                    Err(e) => {
                        return Err(e);
                    }
                }
            } else {
                // Multiple independent steps — run in parallel
                let mut handles = Vec::with_capacity(group.len());

                for step_id in &group {
                    let step = workflow.step(step_id).expect("DAG validated step exists");
                    let ctx_clone = ctx.clone();
                    let failed_clone = failed.clone();
                    let step_id_owned = (*step_id).to_string();

                    let handle = tokio::spawn(async move {
                        // Take a snapshot of context for this step
                        let mut ctx_snapshot = ctx_clone.lock().await.clone();
                        drop(ctx_clone); // Release lock during execution

                        match step.execute(&mut ctx_snapshot).await {
                            Ok(output) => Ok((step_id_owned, output)),
                            Err(e) => {
                                *failed_clone.lock().await = Some(WorkflowError::StepFailed {
                                    step_id: step_id_owned.clone(),
                                    message: e.to_string(),
                                });
                                Err(e)
                            }
                        }
                    });

                    handles.push(handle);
                }

                // Collect results
                let mut first_error: Option<WorkflowError> = None;
                let mut outputs: Vec<(String, StepOutput)> = Vec::new();

                for handle in handles {
                    match handle.await {
                        Ok(Ok((id, output))) => outputs.push((id, output)),
                        Ok(Err(e)) => {
                            if first_error.is_none() {
                                first_error = Some(e);
                            }
                        }
                        Err(join_err) => {
                            if first_error.is_none() {
                                first_error = Some(WorkflowError::StepFailed {
                                    step_id: "unknown".into(),
                                    message: format!("Task panicked: {join_err}"),
                                });
                            }
                        }
                    }
                }

                // If any step in this group failed, return the error
                if let Some(err) = first_error {
                    return Err(err);
                }

                // Store all outputs
                let mut ctx_guard = ctx.lock().await;
                for (id, output) in outputs {
                    ctx_guard.set_output(&id, output);
                }
            }
        }

        let result = ctx.lock().await.clone();
        Ok(result)
    }

    /// Runs a workflow with checkpointing after each group completes.
    ///
    /// If a checkpoint file already exists at the path, completed steps are skipped.
    pub async fn run_with_checkpoint(
        &self,
        workflow: Workflow,
        checkpoint_path: &Path,
    ) -> Result<WorkflowContext, WorkflowError> {
        let groups = workflow.parallel_groups()?;

        // Load existing checkpoint or create new
        let mut checkpoint = if checkpoint_path.exists() {
            Checkpoint::load(checkpoint_path).await?
        } else {
            Checkpoint::new()
        };

        let ctx = Arc::new(Mutex::new(checkpoint.clone().into_context()));

        for group in groups {
            // Filter out already-completed steps
            let pending: Vec<&str> = group
                .iter()
                .filter(|id| !checkpoint.is_completed(id))
                .copied()
                .collect();

            if pending.is_empty() {
                continue;
            }

            if pending.len() == 1 {
                let step_id = pending[0];
                let step = workflow.step(step_id).expect("DAG validated");
                let mut ctx_guard = ctx.lock().await;
                let output = step.execute(&mut ctx_guard).await?;
                ctx_guard.set_output(step_id, output.clone());
                checkpoint.mark_completed(step_id, output);
            } else {
                let mut handles = Vec::with_capacity(pending.len());

                for step_id in &pending {
                    let step = workflow.step(step_id).expect("DAG validated");
                    let ctx_clone = ctx.clone();
                    let step_id_owned = (*step_id).to_string();

                    let handle = tokio::spawn(async move {
                        let mut ctx_snapshot = ctx_clone.lock().await.clone();
                        drop(ctx_clone);
                        let output = step.execute(&mut ctx_snapshot).await?;
                        Ok::<_, WorkflowError>((step_id_owned, output))
                    });
                    handles.push(handle);
                }

                let mut first_error: Option<WorkflowError> = None;
                let mut outputs: Vec<(String, StepOutput)> = Vec::new();

                for handle in handles {
                    match handle.await {
                        Ok(Ok((id, output))) => outputs.push((id, output)),
                        Ok(Err(e)) => {
                            if first_error.is_none() {
                                first_error = Some(e);
                            }
                        }
                        Err(join_err) => {
                            if first_error.is_none() {
                                first_error = Some(WorkflowError::StepFailed {
                                    step_id: "unknown".into(),
                                    message: format!("Task panicked: {join_err}"),
                                });
                            }
                        }
                    }
                }

                if let Some(err) = first_error {
                    // Save checkpoint before returning error
                    checkpoint.save(checkpoint_path).await?;
                    return Err(err);
                }

                let mut ctx_guard = ctx.lock().await;
                for (id, output) in outputs {
                    ctx_guard.set_output(&id, output.clone());
                    checkpoint.mark_completed(&id, output);
                }
            }

            // Save checkpoint after each group
            checkpoint.save(checkpoint_path).await?;
        }

        let result = ctx.lock().await.clone();
        Ok(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::WorkflowError;
    use crate::builder::Workflow;
    use crate::context::WorkflowContext;
    use crate::step::{Step, StepOutput};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::time::Duration;

    // === Mock Steps ===

    struct ValueStep {
        step_id: String,
        output: String,
    }

    impl ValueStep {
        fn new(id: &str, output: &str) -> Self {
            Self {
                step_id: id.into(),
                output: output.into(),
            }
        }
    }

    #[async_trait::async_trait]
    impl Step for ValueStep {
        fn id(&self) -> &str {
            &self.step_id
        }

        async fn execute(&self, _ctx: &mut WorkflowContext) -> Result<StepOutput, WorkflowError> {
            Ok(StepOutput::new(&self.output))
        }
    }

    /// Step that reads a dependency's output and appends to it.
    struct AppendStep {
        step_id: String,
        dep_id: String,
        suffix: String,
    }

    impl AppendStep {
        fn new(id: &str, dep_id: &str, suffix: &str) -> Self {
            Self {
                step_id: id.into(),
                dep_id: dep_id.into(),
                suffix: suffix.into(),
            }
        }
    }

    #[async_trait::async_trait]
    impl Step for AppendStep {
        fn id(&self) -> &str {
            &self.step_id
        }

        async fn execute(&self, ctx: &mut WorkflowContext) -> Result<StepOutput, WorkflowError> {
            let prev = ctx
                .output(&self.dep_id)
                .map(|o| o.value().to_string())
                .unwrap_or_default();
            Ok(StepOutput::new(&format!("{prev}{}", self.suffix)))
        }
    }

    /// Step that fails.
    struct FailStep {
        step_id: String,
        message: String,
    }

    impl FailStep {
        fn new(id: &str, message: &str) -> Self {
            Self {
                step_id: id.into(),
                message: message.into(),
            }
        }
    }

    #[async_trait::async_trait]
    impl Step for FailStep {
        fn id(&self) -> &str {
            &self.step_id
        }

        async fn execute(&self, _ctx: &mut WorkflowContext) -> Result<StepOutput, WorkflowError> {
            Err(WorkflowError::StepFailed {
                step_id: self.step_id.clone(),
                message: self.message.clone(),
            })
        }
    }

    /// Step that tracks execution via an atomic counter.
    struct CountStep {
        step_id: String,
        counter: Arc<AtomicUsize>,
        delay: Option<Duration>,
    }

    impl CountStep {
        fn new(id: &str, counter: Arc<AtomicUsize>) -> Self {
            Self {
                step_id: id.into(),
                counter,
                delay: None,
            }
        }

        fn with_delay(mut self, delay: Duration) -> Self {
            self.delay = Some(delay);
            self
        }
    }

    #[async_trait::async_trait]
    impl Step for CountStep {
        fn id(&self) -> &str {
            &self.step_id
        }

        async fn execute(&self, _ctx: &mut WorkflowContext) -> Result<StepOutput, WorkflowError> {
            self.counter.fetch_add(1, Ordering::SeqCst);
            if let Some(d) = self.delay {
                tokio::time::sleep(d).await;
            }
            Ok(StepOutput::new("done"))
        }
    }

    // === Engine Tests ===

    #[tokio::test]
    async fn runs_single_step() {
        let workflow = Workflow::builder()
            .step(ValueStep::new("a", "hello"), &[])
            .build()
            .unwrap();

        let engine = WorkflowEngine::new();
        let result = engine.run(workflow).await.unwrap();

        assert!(result.is_completed("a"));
        assert_eq!(result.output("a").unwrap().value(), "hello");
    }

    #[tokio::test]
    async fn runs_linear_chain_passing_context() {
        let workflow = Workflow::builder()
            .step(ValueStep::new("a", "start"), &[])
            .step(AppendStep::new("b", "a", "_middle"), &["a"])
            .step(AppendStep::new("c", "b", "_end"), &["b"])
            .build()
            .unwrap();

        let engine = WorkflowEngine::new();
        let result = engine.run(workflow).await.unwrap();

        assert_eq!(result.output("c").unwrap().value(), "start_middle_end");
    }

    #[tokio::test]
    async fn runs_parallel_independent_steps() {
        let counter = Arc::new(AtomicUsize::new(0));

        let workflow = Workflow::builder()
            .step(
                CountStep::new("a", counter.clone()).with_delay(Duration::from_millis(50)),
                &[],
            )
            .step(
                CountStep::new("b", counter.clone()).with_delay(Duration::from_millis(50)),
                &[],
            )
            .step(
                CountStep::new("c", counter.clone()).with_delay(Duration::from_millis(50)),
                &[],
            )
            .build()
            .unwrap();

        let engine = WorkflowEngine::new();
        let start = std::time::Instant::now();
        let result = engine.run(workflow).await.unwrap();
        let elapsed = start.elapsed();

        // All 3 should have run
        assert_eq!(counter.load(Ordering::SeqCst), 3);
        assert!(result.is_completed("a"));
        assert!(result.is_completed("b"));
        assert!(result.is_completed("c"));

        // Should run in parallel (< 120ms), not sequentially (>= 150ms)
        assert!(elapsed < Duration::from_millis(120));
    }

    #[tokio::test]
    async fn step_failure_propagates_error() {
        let workflow = Workflow::builder()
            .step(FailStep::new("a", "boom"), &[])
            .build()
            .unwrap();

        let engine = WorkflowEngine::new();
        let result = engine.run(workflow).await;

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            WorkflowError::StepFailed { step_id, .. } if step_id == "a"
        ));
    }

    #[tokio::test]
    async fn dependent_step_skipped_when_dependency_fails() {
        let counter = Arc::new(AtomicUsize::new(0));

        let workflow = Workflow::builder()
            .step(FailStep::new("a", "boom"), &[])
            .step(CountStep::new("b", counter.clone()), &["a"])
            .build()
            .unwrap();

        let engine = WorkflowEngine::new();
        let result = engine.run(workflow).await;

        // Workflow fails
        assert!(result.is_err());
        // Step b never ran
        assert_eq!(counter.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn diamond_workflow_executes_correctly() {
        //     a
        //    / \
        //   b   c
        //    \ /
        //     d
        let workflow = Workflow::builder()
            .step(ValueStep::new("a", "A"), &[])
            .step(AppendStep::new("b", "a", "_B"), &["a"])
            .step(AppendStep::new("c", "a", "_C"), &["a"])
            .step(AppendStep::new("d", "b", "_D"), &["b", "c"])
            .build()
            .unwrap();

        let engine = WorkflowEngine::new();
        let result = engine.run(workflow).await.unwrap();

        assert_eq!(result.output("a").unwrap().value(), "A");
        assert_eq!(result.output("b").unwrap().value(), "A_B");
        assert_eq!(result.output("c").unwrap().value(), "A_C");
        // d depends on b, reads b's output
        assert_eq!(result.output("d").unwrap().value(), "A_B_D");
    }

    // === Checkpointed Run Tests ===

    #[tokio::test]
    async fn checkpointed_run_saves_checkpoint_file() {
        let dir = tempfile::tempdir().unwrap();
        let ckpt_path = dir.path().join("checkpoint.json");

        let workflow = Workflow::builder()
            .step(ValueStep::new("a", "A"), &[])
            .step(ValueStep::new("b", "B"), &["a"])
            .build()
            .unwrap();

        let engine = WorkflowEngine::new();
        let result = engine
            .run_with_checkpoint(workflow, &ckpt_path)
            .await
            .unwrap();

        assert!(ckpt_path.exists());
        assert!(result.is_completed("a"));
        assert!(result.is_completed("b"));
    }

    #[tokio::test]
    async fn checkpointed_run_skips_completed_steps() {
        let dir = tempfile::tempdir().unwrap();
        let ckpt_path = dir.path().join("checkpoint.json");

        // Pre-populate checkpoint with step "a" completed
        let mut pre_checkpoint = crate::checkpoint::Checkpoint::new();
        pre_checkpoint.mark_completed("a", StepOutput::new("A"));
        pre_checkpoint.save(&ckpt_path).await.unwrap();

        let counter = Arc::new(AtomicUsize::new(0));

        let workflow = Workflow::builder()
            .step(CountStep::new("a", counter.clone()), &[])
            .step(CountStep::new("b", counter.clone()), &["a"])
            .build()
            .unwrap();

        let engine = WorkflowEngine::new();
        let result = engine
            .run_with_checkpoint(workflow, &ckpt_path)
            .await
            .unwrap();

        // Step "a" was already in checkpoint, should not run again
        // Only step "b" should have run
        assert_eq!(counter.load(Ordering::SeqCst), 1);
        assert!(result.is_completed("a"));
        assert!(result.is_completed("b"));
    }

    #[tokio::test]
    async fn returns_all_completed_step_ids() {
        let workflow = Workflow::builder()
            .step(ValueStep::new("x", "1"), &[])
            .step(ValueStep::new("y", "2"), &[])
            .build()
            .unwrap();

        let engine = WorkflowEngine::new();
        let result = engine.run(workflow).await.unwrap();

        let mut ids = result.completed_step_ids();
        ids.sort_unstable();
        assert_eq!(ids, vec!["x", "y"]);
    }
}