ironflow-engine 2.48.0

Workflow orchestration engine for ironflow with FSM-based run lifecycle
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! [`SubWorkflowOutput`] -- what a parent gets back from a sub-workflow.
//!
//! [`SubWorkflowOutcome`] adds the case of a sub-workflow started with a
//! concurrency key that another active run already holds.

use std::fmt;

use rust_decimal::Decimal;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Value, from_value};
use uuid::Uuid;

use ironflow_store::entities::RunStatus;

use crate::error::EngineError;

/// Result of a [`workflow`](crate::context::WorkflowContext::workflow) step.
///
/// While planning, no child run is created: [`run_id`](Self::run_id) is
/// [`Uuid::nil`] and the metrics are zero.
///
/// It is also the persisted output of the step, so a stored workflow step
/// reads back with [`StepOutput::json`](super::StepOutput::json).
///
/// # Examples
///
/// ```
/// use ironflow_engine::executor::SubWorkflowOutput;
/// use ironflow_store::entities::RunStatus;
/// use rust_decimal::Decimal;
/// use uuid::Uuid;
///
/// let run_id = Uuid::now_v7();
/// let output = SubWorkflowOutput::new(run_id, "collect", RunStatus::Completed, Decimal::ZERO, 1200);
/// assert_eq!(output.run_id(), run_id);
/// assert_eq!(output.workflow_name(), "collect");
/// assert_eq!(output.status(), RunStatus::Completed);
/// assert_eq!(output.duration_ms(), 1200);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SubWorkflowOutput {
    run_id: Uuid,
    workflow_name: String,
    status: RunStatus,
    cost_usd: Decimal,
    duration_ms: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    error: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    output: Option<Value>,
}

impl SubWorkflowOutput {
    /// Assemble the result of a child run.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::SubWorkflowOutput;
    /// use ironflow_store::entities::RunStatus;
    /// use rust_decimal::Decimal;
    /// use uuid::Uuid;
    ///
    /// let output = SubWorkflowOutput::new(Uuid::nil(), "collect", RunStatus::Warning, Decimal::ONE, 0);
    /// assert_eq!(output.cost_usd(), Decimal::ONE);
    /// ```
    pub fn new(
        run_id: Uuid,
        workflow_name: &str,
        status: RunStatus,
        cost_usd: Decimal,
        duration_ms: u64,
    ) -> Self {
        Self {
            run_id,
            workflow_name: workflow_name.to_string(),
            status,
            cost_usd,
            duration_ms,
            error: None,
            output: None,
        }
    }

    /// Attach the error of a child run tolerated by `allow_failure`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::SubWorkflowOutput;
    /// use ironflow_store::entities::RunStatus;
    /// use rust_decimal::Decimal;
    /// use uuid::Uuid;
    ///
    /// let output = SubWorkflowOutput::new(Uuid::nil(), "collect", RunStatus::Failed, Decimal::ZERO, 0)
    ///     .with_error("boom");
    /// assert_eq!(output.error(), Some("boom"));
    /// ```
    pub fn with_error(mut self, error: impl Into<String>) -> Self {
        self.error = Some(error.into());
        self
    }

    /// Attach the output the child handler set with
    /// [`set_output`](crate::context::WorkflowContext::set_output).
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::SubWorkflowOutput;
    /// use ironflow_store::entities::RunStatus;
    /// use rust_decimal::Decimal;
    /// use serde_json::json;
    /// use uuid::Uuid;
    ///
    /// # use ironflow_engine::error::EngineError;
    /// # fn example() -> Result<(), EngineError> {
    /// let output = SubWorkflowOutput::new(Uuid::nil(), "review", RunStatus::Completed, Decimal::ZERO, 0)
    ///     .with_output(Some(json!(true)));
    /// assert_eq!(output.output::<bool>()?, Some(true));
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_output(mut self, output: Option<Value>) -> Self {
        self.output = output;
        self
    }

    /// The child run, to read its steps from the store. [`Uuid::nil`] while
    /// planning.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::SubWorkflowOutput;
    /// use ironflow_store::entities::RunStatus;
    /// use rust_decimal::Decimal;
    /// use uuid::Uuid;
    ///
    /// let output = SubWorkflowOutput::new(Uuid::nil(), "collect", RunStatus::Completed, Decimal::ZERO, 0);
    /// assert!(output.run_id().is_nil());
    /// ```
    pub fn run_id(&self) -> Uuid {
        self.run_id
    }

    /// Name of the child workflow.
    pub fn workflow_name(&self) -> &str {
        &self.workflow_name
    }

    /// Final status of the child run: `Completed`, `Warning` when one of its
    /// `allow_failure` steps failed, or (only when the step was started with
    /// `allow_failure`) `Failed` / `Cancelled`.
    pub fn status(&self) -> RunStatus {
        self.status
    }

    /// Cost of the child run, in USD. Already included in the parent's cost.
    pub fn cost_usd(&self) -> Decimal {
        self.cost_usd
    }

    /// Wall-clock duration of the child run, in milliseconds.
    pub fn duration_ms(&self) -> u64 {
        self.duration_ms
    }

    /// Error of a failed or cancelled child run tolerated by `allow_failure`,
    /// `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::SubWorkflowOutput;
    /// use ironflow_store::entities::RunStatus;
    /// use rust_decimal::Decimal;
    /// use uuid::Uuid;
    ///
    /// let output = SubWorkflowOutput::new(Uuid::nil(), "collect", RunStatus::Completed, Decimal::ZERO, 0);
    /// assert_eq!(output.error(), None);
    /// ```
    pub fn error(&self) -> Option<&str> {
        self.error.as_deref()
    }

    /// The typed output the child handler set with
    /// [`set_output`](crate::context::WorkflowContext::set_output).
    ///
    /// `Ok(None)` when the child set no output. A failed child tolerated by
    /// `allow_failure` keeps the output it set before failing. On replay the
    /// value is read from the recorded step, not from the child run.
    ///
    /// # Errors
    ///
    /// Returns [`EngineError::Serialization`] if the output does not
    /// deserialize into `T`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::SubWorkflowOutput;
    /// use ironflow_store::entities::RunStatus;
    /// use rust_decimal::Decimal;
    /// use serde::Deserialize;
    /// use serde_json::json;
    /// use uuid::Uuid;
    ///
    /// #[derive(Deserialize)]
    /// struct Review {
    ///     approved: bool,
    /// }
    ///
    /// # use ironflow_engine::error::EngineError;
    /// # fn example() -> Result<(), EngineError> {
    /// let child = SubWorkflowOutput::new(Uuid::nil(), "review", RunStatus::Completed, Decimal::ZERO, 0)
    ///     .with_output(Some(json!({"approved": true})));
    /// let review: Option<Review> = child.output()?;
    /// assert!(review.is_some_and(|r| r.approved));
    /// # Ok(())
    /// # }
    /// ```
    pub fn output<T: DeserializeOwned>(&self) -> Result<Option<T>, EngineError> {
        self.output
            .as_ref()
            .map(|value| from_value(value.clone()))
            .transpose()
            .map_err(EngineError::Serialization)
    }
}

/// A sub-workflow skipped because its concurrency key is held by another
/// active run.
///
/// Persisted as the step output `{"concurrency_conflict": {"key": .., "run_id": ..}}`
/// and replayed as-is on resume.
///
/// # Examples
///
/// ```
/// use ironflow_engine::executor::ConcurrencyConflict;
/// use uuid::Uuid;
///
/// let holder = Uuid::now_v7();
/// let conflict = ConcurrencyConflict::new("issue:12", holder);
/// assert_eq!(conflict.key(), "issue:12");
/// assert_eq!(conflict.run_id(), holder);
/// assert!(conflict.to_string().contains("issue:12"));
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConcurrencyConflict {
    key: String,
    run_id: Uuid,
}

impl ConcurrencyConflict {
    /// Record that `run_id` holds `key`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::ConcurrencyConflict;
    /// use uuid::Uuid;
    ///
    /// let conflict = ConcurrencyConflict::new("deploy:prod", Uuid::nil());
    /// assert_eq!(conflict.key(), "deploy:prod");
    /// ```
    pub fn new(key: impl Into<String>, run_id: Uuid) -> Self {
        Self {
            key: key.into(),
            run_id,
        }
    }

    /// The contested concurrency key.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::ConcurrencyConflict;
    /// use uuid::Uuid;
    ///
    /// assert_eq!(ConcurrencyConflict::new("k", Uuid::nil()).key(), "k");
    /// ```
    pub fn key(&self) -> &str {
        &self.key
    }

    /// The active run holding the key, at the time of the conflict.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::ConcurrencyConflict;
    /// use uuid::Uuid;
    ///
    /// let holder = Uuid::now_v7();
    /// assert_eq!(ConcurrencyConflict::new("k", holder).run_id(), holder);
    /// ```
    pub fn run_id(&self) -> Uuid {
        self.run_id
    }
}

impl fmt::Display for ConcurrencyConflict {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "conflict on concurrency key {:?} (run {})",
            self.key, self.run_id
        )
    }
}

/// Result of a
/// [`workflow_with`](crate::context::WorkflowContext::workflow_with) step.
///
/// # Examples
///
/// ```
/// use ironflow_engine::executor::{ConcurrencyConflict, SubWorkflowOutcome};
/// use uuid::Uuid;
///
/// let outcome = SubWorkflowOutcome::Conflict(ConcurrencyConflict::new("issue:12", Uuid::nil()));
/// match &outcome {
///     SubWorkflowOutcome::Completed(output) => println!("child run {}", output.run_id()),
///     SubWorkflowOutcome::Conflict(conflict) => println!("held by {}", conflict.run_id()),
/// }
/// assert!(outcome.output().is_none());
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum SubWorkflowOutcome {
    /// The child run was created and finished.
    Completed(SubWorkflowOutput),
    /// No child run was created: another active run holds the concurrency key.
    Conflict(ConcurrencyConflict),
}

impl SubWorkflowOutcome {
    /// The conflict, when no child run was created.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::{ConcurrencyConflict, SubWorkflowOutcome};
    /// use uuid::Uuid;
    ///
    /// let outcome = SubWorkflowOutcome::Conflict(ConcurrencyConflict::new("k", Uuid::nil()));
    /// assert_eq!(outcome.conflict().map(|c| c.key()), Some("k"));
    /// ```
    pub fn conflict(&self) -> Option<&ConcurrencyConflict> {
        match self {
            SubWorkflowOutcome::Conflict(conflict) => Some(conflict),
            SubWorkflowOutcome::Completed(_) => None,
        }
    }

    /// The child result, when the child run was created and finished.
    ///
    /// # Examples
    ///
    /// ```
    /// use ironflow_engine::executor::{SubWorkflowOutcome, SubWorkflowOutput};
    /// use ironflow_store::entities::RunStatus;
    /// use rust_decimal::Decimal;
    /// use uuid::Uuid;
    ///
    /// let output = SubWorkflowOutput::new(Uuid::nil(), "collect", RunStatus::Completed, Decimal::ZERO, 0);
    /// let outcome = SubWorkflowOutcome::Completed(output.clone());
    /// assert_eq!(outcome.output(), Some(&output));
    /// assert!(outcome.conflict().is_none());
    /// ```
    pub fn output(&self) -> Option<&SubWorkflowOutput> {
        match self {
            SubWorkflowOutcome::Completed(output) => Some(output),
            SubWorkflowOutcome::Conflict(_) => None,
        }
    }
}

/// The persisted output of a completed `Workflow` step, as read back on replay.
///
/// `Conflict` is tried first: a flat [`SubWorkflowOutput`] has no
/// `concurrency_conflict` field, so outputs recorded before concurrency keys
/// existed still read back as `Completed`.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub(crate) enum RecordedWorkflowStep {
    /// The step was skipped on a concurrency conflict.
    Conflict {
        /// The recorded conflict.
        concurrency_conflict: ConcurrencyConflict,
    },
    /// The child run finished.
    Completed(SubWorkflowOutput),
}

impl From<RecordedWorkflowStep> for SubWorkflowOutcome {
    fn from(recorded: RecordedWorkflowStep) -> Self {
        match recorded {
            RecordedWorkflowStep::Conflict {
                concurrency_conflict,
            } => SubWorkflowOutcome::Conflict(concurrency_conflict),
            RecordedWorkflowStep::Completed(output) => SubWorkflowOutcome::Completed(output),
        }
    }
}

#[cfg(test)]
mod tests {
    use serde_json::{from_value, json, to_value};

    use super::*;

    #[test]
    fn serializes_to_the_persisted_step_output() {
        let run_id = Uuid::now_v7();
        let output = SubWorkflowOutput::new(
            run_id,
            "collect",
            RunStatus::Warning,
            Decimal::new(25, 2),
            1200,
        );

        assert_eq!(
            to_value(&output).expect("serialize"),
            json!({
                "run_id": run_id,
                "workflow_name": "collect",
                "status": "warning",
                "cost_usd": 0.25,
                "duration_ms": 1200,
            })
        );
    }

    #[test]
    fn a_persisted_step_output_reads_back() {
        let run_id = Uuid::now_v7();
        let stored = json!({
            "run_id": run_id,
            "workflow_name": "collect",
            "status": "completed",
            "cost_usd": 0,
            "duration_ms": 7,
        });

        let output: SubWorkflowOutput = from_value(stored).expect("deserialize");

        assert_eq!(output.run_id(), run_id);
        assert_eq!(output.status(), RunStatus::Completed);
        assert_eq!(output.cost_usd(), Decimal::ZERO);
        assert_eq!(output.duration_ms(), 7);
    }

    #[test]
    fn a_recorded_conflict_round_trips() {
        let holder = Uuid::now_v7();
        let conflict = ConcurrencyConflict::new("issue:12", holder);
        let stored = json!({ "concurrency_conflict": conflict });

        assert_eq!(
            stored,
            json!({ "concurrency_conflict": { "key": "issue:12", "run_id": holder } })
        );

        let recorded: RecordedWorkflowStep = from_value(stored).expect("deserialize");
        let outcome = SubWorkflowOutcome::from(recorded);
        assert_eq!(outcome, SubWorkflowOutcome::Conflict(conflict));
        assert_eq!(
            outcome.conflict().map(ConcurrencyConflict::run_id),
            Some(holder)
        );
        assert!(outcome.output().is_none());
    }

    #[test]
    fn a_flat_output_still_reads_back_as_completed() {
        let run_id = Uuid::now_v7();
        let stored = json!({
            "run_id": run_id,
            "workflow_name": "collect",
            "status": "completed",
            "cost_usd": 0,
            "duration_ms": 7,
        });

        let recorded: RecordedWorkflowStep = from_value(stored).expect("deserialize");
        let outcome = SubWorkflowOutcome::from(recorded);
        let output = outcome.output().expect("completed outcome");
        assert_eq!(output.run_id(), run_id);
        assert_eq!(output.duration_ms(), 7);
        assert!(outcome.conflict().is_none());
    }

    #[test]
    fn conflict_display_names_the_key_and_the_holder() {
        let holder = Uuid::now_v7();
        let text = ConcurrencyConflict::new("issue:12", holder).to_string();
        assert!(text.contains("\"issue:12\""));
        assert!(text.contains(&holder.to_string()));
    }

    #[test]
    fn an_error_roundtrips() {
        let output = SubWorkflowOutput::new(
            Uuid::now_v7(),
            "collect",
            RunStatus::Failed,
            Decimal::ZERO,
            3,
        )
        .with_error("boom");

        let back: SubWorkflowOutput =
            from_value(to_value(&output).expect("serialize")).expect("deserialize");

        assert_eq!(back, output);
        assert_eq!(back.error(), Some("boom"));
    }

    #[test]
    fn a_legacy_output_without_error_reads_back_as_none() {
        let output: SubWorkflowOutput = from_value(json!({
            "run_id": Uuid::now_v7(),
            "workflow_name": "collect",
            "status": "completed",
            "cost_usd": 0,
            "duration_ms": 7,
        }))
        .expect("deserialize");

        assert_eq!(output.error(), None);
    }

    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    struct Verdict {
        approved: bool,
        score: u8,
    }

    fn child() -> SubWorkflowOutput {
        SubWorkflowOutput::new(
            Uuid::now_v7(),
            "review",
            RunStatus::Completed,
            Decimal::ZERO,
            5,
        )
    }

    #[test]
    fn set_output_none_reads_back_as_none() {
        let output: Option<Verdict> = child().output().expect("no output");
        assert_eq!(output, None);
    }

    #[test]
    fn set_output_typed_value_reads_back() {
        let output = child().with_output(Some(json!({"approved": true, "score": 7})));

        let verdict: Option<Verdict> = output.output().expect("deserialize");
        assert_eq!(
            verdict,
            Some(Verdict {
                approved: true,
                score: 7
            })
        );
    }

    #[test]
    fn set_output_of_the_wrong_type_is_a_serialization_error() {
        let output = child().with_output(Some(json!({"approved": "yes"})));

        let result = output.output::<Verdict>();
        assert!(matches!(result, Err(EngineError::Serialization(_))));
    }

    #[test]
    fn set_output_round_trips_through_the_step_output() {
        let output = child().with_output(Some(json!({"approved": false, "score": 1})));

        let stored = to_value(&output).expect("serialize");
        assert_eq!(stored["output"], json!({"approved": false, "score": 1}));

        let back: SubWorkflowOutput = from_value(stored.clone()).expect("deserialize");
        assert_eq!(back, output);

        let recorded: RecordedWorkflowStep = from_value(stored).expect("deserialize");
        let outcome = SubWorkflowOutcome::from(recorded);
        let replayed = outcome.output().expect("completed outcome");
        assert_eq!(
            replayed.output::<Verdict>().expect("deserialize"),
            Some(Verdict {
                approved: false,
                score: 1
            })
        );
    }

    #[test]
    fn set_output_absent_is_not_serialized() {
        let stored = to_value(child()).expect("serialize");
        assert!(stored.get("output").is_none());
    }

    #[test]
    fn set_output_legacy_step_output_without_the_field_reads_back_as_none() {
        let output: SubWorkflowOutput = from_value(json!({
            "run_id": Uuid::now_v7(),
            "workflow_name": "collect",
            "status": "completed",
            "cost_usd": 0,
            "duration_ms": 7,
        }))
        .expect("deserialize");

        assert_eq!(output.output::<Verdict>().expect("no output"), None);
    }

    #[test]
    fn an_output_without_run_id_is_refused() {
        let result = from_value::<SubWorkflowOutput>(json!({
            "workflow_name": "collect",
            "status": "completed",
            "cost_usd": 0,
            "duration_ms": 0,
        }));
        assert!(result.is_err());
    }
}