blazen-core 0.1.157

Core workflow engine for Blazen - event-driven, async, pausable workflows
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
//! Integration tests for `StepKind::SubWorkflow` and
//! `StepKind::ParallelSubWorkflows` (Wave 5).
//!
//! These cases construct a parent workflow whose steps are themselves
//! workflows, exercise per-step timeouts and retries on the child run,
//! and validate both `JoinStrategy::WaitAll` and
//! `JoinStrategy::FirstCompletes` semantics.

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;

use blazen_core::{
    JoinStrategy, ParallelSubWorkflowsStep, StepFn, StepOutput, StepRegistration, SubWorkflowStep,
    Workflow, WorkflowBuilder, WorkflowError,
};
use blazen_events::{Event, StartEvent, StopEvent};
use blazen_llm::retry::RetryConfig;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Build a child workflow that turns its `StartEvent` into a `StopEvent`
/// whose `result` JSON is the input data with `{"child": "<tag>"}` merged.
fn child_workflow_tag(tag: &'static str) -> Workflow {
    let handler: StepFn = Arc::new(move |event, _ctx| {
        Box::pin(async move {
            let start = event
                .as_any()
                .downcast_ref::<StartEvent>()
                .expect("expected StartEvent in child workflow");
            let mut data = start.data.clone();
            if let Some(obj) = data.as_object_mut() {
                obj.insert(
                    "child".to_owned(),
                    serde_json::Value::String(tag.to_owned()),
                );
            } else {
                data = serde_json::json!({ "input": data, "child": tag });
            }
            Ok(StepOutput::Single(Box::new(StopEvent { result: data })))
        })
    });

    WorkflowBuilder::new(format!("child::{tag}"))
        .step(StepRegistration::new(
            format!("child_step_{tag}"),
            vec![StartEvent::event_type()],
            vec![StopEvent::event_type()],
            handler,
            0,
        ))
        .no_timeout()
        .build()
        .expect("child workflow must build")
}

/// Build a child workflow that sleeps for `d` before producing a
/// `StopEvent`. Used to exercise timeouts and `FirstCompletes`.
fn child_workflow_sleeping(name: &'static str, d: Duration) -> Workflow {
    let handler: StepFn = Arc::new(move |_event, _ctx| {
        Box::pin(async move {
            tokio::time::sleep(d).await;
            let slept_ms = u64::try_from(d.as_millis()).unwrap_or(u64::MAX);
            Ok(StepOutput::Single(Box::new(StopEvent {
                result: serde_json::json!({ "name": name, "slept_ms": slept_ms }),
            })))
        })
    });

    WorkflowBuilder::new(format!("child::sleep::{name}"))
        .step(StepRegistration::new(
            format!("child_sleep_{name}"),
            vec![StartEvent::event_type()],
            vec![StopEvent::event_type()],
            handler,
            0,
        ))
        .no_timeout()
        .build()
        .expect("sleeping child workflow must build")
}

/// Build a child workflow that fails the first `fails_before_success`
/// runs and succeeds afterwards. Used to verify retry behaviour.
///
/// The counter is shared across handler invocations.
fn child_workflow_flaky(
    name: &'static str,
    counter: Arc<AtomicUsize>,
    fails_before_success: usize,
) -> Workflow {
    let handler: StepFn = Arc::new(move |_event, _ctx| {
        let counter = Arc::clone(&counter);
        Box::pin(async move {
            let attempts_so_far = counter.fetch_add(1, Ordering::SeqCst);
            if attempts_so_far < fails_before_success {
                Err(WorkflowError::Context(format!(
                    "{name} attempt {attempts_so_far} failed"
                )))
            } else {
                Ok(StepOutput::Single(Box::new(StopEvent {
                    result: serde_json::json!({
                        "name": name,
                        "attempts": attempts_so_far + 1,
                    }),
                })))
            }
        })
    });

    WorkflowBuilder::new(format!("child::flaky::{name}"))
        .step(StepRegistration::new(
            format!("child_flaky_{name}"),
            vec![StartEvent::event_type()],
            vec![StopEvent::event_type()],
            handler,
            0,
        ))
        .no_timeout()
        .no_retry()
        .build()
        .expect("flaky child workflow must build")
}

/// Default input mapper: forwards the parent `StartEvent` payload as-is.
fn passthrough_input_mapper() -> blazen_core::SubWorkflowInputMapper {
    Arc::new(|event| {
        if let Some(start) = event.as_any().downcast_ref::<StartEvent>() {
            start.data.clone()
        } else {
            event.to_json()
        }
    })
}

/// Default output mapper: wraps the child's terminal JSON in a
/// `StopEvent` so the parent workflow exits cleanly.
fn stop_event_output_mapper() -> blazen_core::SubWorkflowOutputMapper {
    Arc::new(|json| Box::new(StopEvent { result: json }))
}

// ---------------------------------------------------------------------------
// SubWorkflowStep: happy path
// ---------------------------------------------------------------------------

#[tokio::test]
async fn subworkflow_step_runs_child_and_emits_output() {
    let child = child_workflow_tag("alpha");

    let sub = SubWorkflowStep {
        name: "outer_sub".to_owned(),
        accepts: vec![StartEvent::event_type()],
        emits: vec![StopEvent::event_type()],
        workflow: Arc::new(child),
        input_mapper: passthrough_input_mapper(),
        output_mapper: stop_event_output_mapper(),
        timeout: None,
        retry_config: None,
    };

    let parent = WorkflowBuilder::new("parent")
        .add_subworkflow_step(sub)
        .no_timeout()
        .build()
        .expect("parent workflow must build");

    let handler = parent
        .run(serde_json::json!({ "n": 7 }))
        .await
        .expect("parent run() must succeed");

    let result = handler.result().await.expect("workflow must complete");
    let stop = result
        .event
        .as_any()
        .downcast_ref::<StopEvent>()
        .expect("terminal event must be StopEvent");

    assert_eq!(
        stop.result,
        serde_json::json!({ "n": 7, "child": "alpha" }),
        "parent should emit the child's mapped output",
    );
}

// ---------------------------------------------------------------------------
// SubWorkflowStep: timeout
// ---------------------------------------------------------------------------

#[tokio::test]
async fn subworkflow_step_respects_its_own_timeout() {
    // Child sleeps 500ms; per-step timeout is 50ms.
    let child = child_workflow_sleeping("slow", Duration::from_millis(500));

    let sub = SubWorkflowStep {
        name: "slow_sub".to_owned(),
        accepts: vec![StartEvent::event_type()],
        emits: vec![StopEvent::event_type()],
        workflow: Arc::new(child),
        input_mapper: passthrough_input_mapper(),
        output_mapper: stop_event_output_mapper(),
        timeout: Some(Duration::from_millis(50)),
        retry_config: Some(Arc::new(RetryConfig {
            max_retries: 0,
            ..RetryConfig::default()
        })),
    };

    let parent = WorkflowBuilder::new("parent")
        .add_subworkflow_step(sub)
        .timeout(Duration::from_secs(5))
        .build()
        .expect("parent workflow must build");

    let handler = parent
        .run(serde_json::json!({}))
        .await
        .expect("parent run() must succeed");

    let result = handler.result().await;
    let err = result.expect_err("parent should fail when sub-workflow times out");
    match err {
        WorkflowError::SubWorkflowFailed { step_name, message } => {
            assert_eq!(step_name, "slow_sub");
            assert!(
                message.contains("slow_sub") && message.contains("timed out"),
                "message should describe the inner step timeout, got: {message}",
            );
        }
        other => panic!("expected SubWorkflowFailed, got {other:?}"),
    }
}

// ---------------------------------------------------------------------------
// SubWorkflowStep: retry config
// ---------------------------------------------------------------------------

#[tokio::test]
async fn subworkflow_step_respects_its_own_retry_config() {
    let counter = Arc::new(AtomicUsize::new(0));
    // First two runs fail, third succeeds. With `max_retries = 2` the
    // sub-workflow makes 3 attempts in total and ultimately succeeds.
    let child = child_workflow_flaky("flaky", Arc::clone(&counter), 2);

    let sub = SubWorkflowStep {
        name: "flaky_sub".to_owned(),
        accepts: vec![StartEvent::event_type()],
        emits: vec![StopEvent::event_type()],
        workflow: Arc::new(child),
        input_mapper: passthrough_input_mapper(),
        output_mapper: stop_event_output_mapper(),
        timeout: None,
        retry_config: Some(Arc::new(RetryConfig {
            max_retries: 2,
            initial_delay_ms: 1,
            max_delay_ms: 1,
            jitter: false,
            ..RetryConfig::default()
        })),
    };

    let parent = WorkflowBuilder::new("parent")
        .add_subworkflow_step(sub)
        .timeout(Duration::from_secs(5))
        .build()
        .expect("parent workflow must build");

    let handler = parent
        .run(serde_json::json!({}))
        .await
        .expect("parent run() must succeed");

    let result = handler
        .result()
        .await
        .expect("retry should eventually succeed");
    let stop = result
        .event
        .as_any()
        .downcast_ref::<StopEvent>()
        .expect("terminal event must be StopEvent");
    assert_eq!(stop.result["name"], serde_json::json!("flaky"));
    assert_eq!(
        stop.result["attempts"],
        serde_json::json!(3),
        "third attempt must be the one that succeeded"
    );
    assert_eq!(
        counter.load(Ordering::SeqCst),
        3,
        "child handler should have been invoked exactly 3 times"
    );
}

// ---------------------------------------------------------------------------
// ParallelSubWorkflowsStep: WaitAll
// ---------------------------------------------------------------------------

#[tokio::test]
async fn parallel_subworkflows_wait_all() {
    let branch_a = SubWorkflowStep {
        name: "branch_a".to_owned(),
        accepts: vec![StartEvent::event_type()],
        emits: vec![StopEvent::event_type()],
        workflow: Arc::new(child_workflow_tag("a")),
        input_mapper: passthrough_input_mapper(),
        output_mapper: stop_event_output_mapper(),
        timeout: None,
        retry_config: None,
    };

    let branch_b = SubWorkflowStep {
        name: "branch_b".to_owned(),
        accepts: vec![StartEvent::event_type()],
        emits: vec![StopEvent::event_type()],
        workflow: Arc::new(child_workflow_tag("b")),
        input_mapper: passthrough_input_mapper(),
        output_mapper: stop_event_output_mapper(),
        timeout: None,
        retry_config: None,
    };

    let fanout = ParallelSubWorkflowsStep {
        name: "fanout".to_owned(),
        accepts: vec![StartEvent::event_type()],
        emits: vec![StopEvent::event_type()],
        branches: vec![branch_a, branch_b],
        join_strategy: JoinStrategy::WaitAll,
    };

    let parent = WorkflowBuilder::new("parent")
        .add_parallel_subworkflows(fanout)
        .timeout(Duration::from_secs(5))
        .build()
        .expect("parent workflow must build");

    let handler = parent
        .run(serde_json::json!({ "n": 1 }))
        .await
        .expect("parent run() must succeed");

    // Both branches emit StopEvents; the first one through the channel
    // terminates the loop. Verify the result is one of the expected
    // child outputs (we don't depend on branch ordering here).
    let result = handler.result().await.expect("workflow must complete");
    let stop = result
        .event
        .as_any()
        .downcast_ref::<StopEvent>()
        .expect("terminal event must be StopEvent");
    let child_tag = stop
        .result
        .get("child")
        .and_then(|v| v.as_str())
        .expect("child tag must be present");
    assert!(
        child_tag == "a" || child_tag == "b",
        "expected child tag from one of the branches, got {child_tag}",
    );
    assert_eq!(stop.result["n"], serde_json::json!(1));
}

// ---------------------------------------------------------------------------
// ParallelSubWorkflowsStep: FirstCompletes
// ---------------------------------------------------------------------------

#[tokio::test]
async fn parallel_subworkflows_first_completes_aborts_losers() {
    let fast = SubWorkflowStep {
        name: "fast".to_owned(),
        accepts: vec![StartEvent::event_type()],
        emits: vec![StopEvent::event_type()],
        workflow: Arc::new(child_workflow_sleeping("fast", Duration::from_millis(20))),
        input_mapper: passthrough_input_mapper(),
        output_mapper: stop_event_output_mapper(),
        timeout: None,
        retry_config: None,
    };

    let slow = SubWorkflowStep {
        name: "slow".to_owned(),
        accepts: vec![StartEvent::event_type()],
        emits: vec![StopEvent::event_type()],
        workflow: Arc::new(child_workflow_sleeping("slow", Duration::from_mins(1))),
        input_mapper: passthrough_input_mapper(),
        output_mapper: stop_event_output_mapper(),
        timeout: None,
        retry_config: None,
    };

    let fanout = ParallelSubWorkflowsStep {
        name: "race".to_owned(),
        accepts: vec![StartEvent::event_type()],
        emits: vec![StopEvent::event_type()],
        branches: vec![fast, slow],
        join_strategy: JoinStrategy::FirstCompletes,
    };

    let parent = WorkflowBuilder::new("parent")
        .add_parallel_subworkflows(fanout)
        .timeout(Duration::from_secs(5))
        .build()
        .expect("parent workflow must build");

    let start = std::time::Instant::now();
    let handler = parent
        .run(serde_json::json!({}))
        .await
        .expect("parent run() must succeed");
    let result = handler.result().await.expect("workflow must complete");
    let elapsed = start.elapsed();

    let stop = result
        .event
        .as_any()
        .downcast_ref::<StopEvent>()
        .expect("terminal event must be StopEvent");
    assert_eq!(
        stop.result["name"],
        serde_json::json!("fast"),
        "FirstCompletes should resolve with the fast branch's output"
    );
    assert!(
        elapsed < Duration::from_secs(3),
        "FirstCompletes must abort the slow branch instead of waiting on it (elapsed = {elapsed:?})"
    );
}