a3s-flow 1.1.0

Durable workflow engine and Rust SDK for A3S
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
use super::*;

struct BatchStepRuntime;

#[async_trait]
impl FlowRuntime for BatchStepRuntime {
    async fn run_workflow(
        &self,
        invocation: WorkflowInvocation,
    ) -> a3s_flow::Result<RuntimeCommand> {
        let ctx = invocation.context();
        let user = ctx.step_output("load-user");
        let orders = ctx.step_output("load-orders");

        match (user, orders) {
            (Some(user), Some(orders)) => Ok(ctx.complete(json!({
                "user": user,
                "orders": orders,
            }))),
            _ => Ok(ctx.schedule_steps(vec![
                ctx.step(
                    "load-user",
                    "loadUser",
                    json!({ "userId": ctx.input()["userId"] }),
                ),
                ctx.step_with_retry(
                    "load-orders",
                    "loadOrders",
                    json!({ "userId": ctx.input()["userId"] }),
                    RetryPolicy::fixed(2, Duration::from_millis(0)),
                ),
            ])),
        }
    }

    async fn run_step(&self, invocation: StepInvocation) -> a3s_flow::Result<serde_json::Value> {
        match invocation.step_name.as_str() {
            "loadUser" => Ok(json!({ "id": invocation.input["userId"], "name": "Ada" })),
            "loadOrders" => Ok(json!([{ "id": "o1" }, { "id": "o2" }])),
            other => Err(FlowError::Runtime(format!("unknown step {other}"))),
        }
    }
}

#[tokio::test]
async fn schedule_steps_fans_out_multiple_durable_steps() {
    let engine = FlowEngine::in_memory(Arc::new(BatchStepRuntime));
    let run_id = engine
        .start(spec(), json!({ "userId": "u1" }))
        .await
        .unwrap();
    let snapshot = engine.snapshot(&run_id).await.unwrap();

    assert_eq!(snapshot.status, WorkflowRunStatus::Completed);
    assert_eq!(snapshot.steps.len(), 2);
    assert_eq!(snapshot.steps["load-user"].status, StepStatus::Completed);
    assert_eq!(snapshot.steps["load-orders"].status, StepStatus::Completed);
    assert_eq!(snapshot.steps["load-orders"].retry.max_attempts, 2);
    assert_eq!(snapshot.output.unwrap()["orders"][1]["id"], "o2");
}

struct ConcurrentBatchStepRuntime {
    barrier: Barrier,
    in_flight: AtomicUsize,
    maximum_in_flight: AtomicUsize,
}

impl ConcurrentBatchStepRuntime {
    fn new(step_count: usize) -> Self {
        Self {
            barrier: Barrier::new(step_count),
            in_flight: AtomicUsize::new(0),
            maximum_in_flight: AtomicUsize::new(0),
        }
    }
}

#[async_trait]
impl FlowRuntime for ConcurrentBatchStepRuntime {
    async fn run_workflow(
        &self,
        invocation: WorkflowInvocation,
    ) -> a3s_flow::Result<RuntimeCommand> {
        let ctx = invocation.context();
        if ctx.step_output("alpha").is_some() && ctx.step_output("beta").is_some() {
            return Ok(ctx.complete(json!({ "done": true })));
        }
        Ok(ctx.schedule_steps(vec![
            ctx.step("alpha", "barrier", json!({ "value": "alpha" })),
            ctx.step("beta", "barrier", json!({ "value": "beta" })),
        ]))
    }

    async fn run_step(&self, invocation: StepInvocation) -> a3s_flow::Result<serde_json::Value> {
        let in_flight = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
        self.maximum_in_flight
            .fetch_max(in_flight, Ordering::SeqCst);
        self.barrier.wait().await;
        self.in_flight.fetch_sub(1, Ordering::SeqCst);
        Ok(invocation.input)
    }
}

#[tokio::test]
async fn schedule_steps_runs_durable_siblings_concurrently() {
    let runtime = Arc::new(ConcurrentBatchStepRuntime::new(2));
    let engine = FlowEngine::in_memory(runtime.clone());
    let run_id = tokio::time::timeout(Duration::from_secs(1), engine.start(spec(), json!({})))
        .await
        .expect("both batch steps must enter the runtime without waiting for a sibling")
        .unwrap();

    assert_eq!(runtime.maximum_in_flight.load(Ordering::SeqCst), 2);
    let history = engine.history(&run_id).await.unwrap();
    let second_started = history
        .iter()
        .position(|event| {
            matches!(
                &event.event,
                FlowEvent::StepStarted { step_id, .. } if step_id == "beta"
            )
        })
        .unwrap();
    let first_completed = history
        .iter()
        .position(|event| matches!(event.event, FlowEvent::StepCompleted { .. }))
        .unwrap();
    assert!(
        second_started < first_completed,
        "every sibling start must be durable before any batch completion"
    );
}

struct HangingBatchSiblingRuntime;

#[async_trait]
impl FlowRuntime for HangingBatchSiblingRuntime {
    async fn run_workflow(
        &self,
        invocation: WorkflowInvocation,
    ) -> a3s_flow::Result<RuntimeCommand> {
        let ctx = invocation.context();
        Ok(ctx.schedule_steps(vec![
            ctx.step("fast", "partialBatch", json!({})),
            ctx.step("hanging", "partialBatch", json!({})),
        ]))
    }

    async fn run_step(&self, invocation: StepInvocation) -> a3s_flow::Result<serde_json::Value> {
        if invocation.step_id == "hanging" {
            return pending().await;
        }
        Ok(json!({ "step": invocation.step_id }))
    }
}

#[tokio::test]
async fn completed_batch_sibling_is_durable_while_another_sibling_is_running() {
    let engine = FlowEngine::in_memory(Arc::new(HangingBatchSiblingRuntime));
    let worker = {
        let engine = engine.clone();
        tokio::spawn(async move {
            engine
                .start_with_id("partial-concurrent-batch", spec(), json!({}))
                .await
        })
    };

    tokio::time::timeout(Duration::from_secs(1), async {
        loop {
            if let Ok(snapshot) = engine.snapshot("partial-concurrent-batch").await {
                if snapshot
                    .steps
                    .get("fast")
                    .is_some_and(|step| step.status == StepStatus::Completed)
                    && snapshot
                        .steps
                        .get("hanging")
                        .is_some_and(|step| step.status == StepStatus::Running)
                {
                    break;
                }
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("the fast sibling must commit without waiting for the hanging sibling");
    worker.abort();
    let _ = worker.await;

    let snapshot = engine.snapshot("partial-concurrent-batch").await.unwrap();
    assert_eq!(snapshot.steps["fast"].status, StepStatus::Completed);
    assert_eq!(snapshot.steps["hanging"].status, StepStatus::Running);
    let history = engine.history("partial-concurrent-batch").await.unwrap();
    assert_eq!(
        history
            .iter()
            .filter(|event| matches!(event.event, FlowEvent::StepStarted { .. }))
            .count(),
        2
    );
    assert_eq!(
        history
            .iter()
            .filter(|event| matches!(event.event, FlowEvent::StepCompleted { .. }))
            .count(),
        1
    );
}

struct DelayedConcurrentBatchRuntime {
    barrier: Barrier,
    alpha_attempts: AtomicUsize,
    beta_attempts: AtomicUsize,
}

impl DelayedConcurrentBatchRuntime {
    fn new() -> Self {
        Self {
            barrier: Barrier::new(2),
            alpha_attempts: AtomicUsize::new(0),
            beta_attempts: AtomicUsize::new(0),
        }
    }
}

#[async_trait]
impl FlowRuntime for DelayedConcurrentBatchRuntime {
    async fn run_workflow(
        &self,
        invocation: WorkflowInvocation,
    ) -> a3s_flow::Result<RuntimeCommand> {
        let ctx = invocation.context();
        if ctx.step_output("alpha").is_some() && ctx.step_output("beta").is_some() {
            return Ok(ctx.complete(json!({ "done": true })));
        }
        let retry = RetryPolicy::fixed(2, Duration::from_millis(10));
        Ok(ctx.schedule_steps(vec![
            ctx.step_with_retry("alpha", "delayedBarrier", json!({}), retry),
            ctx.step_with_retry("beta", "delayedBarrier", json!({}), retry),
        ]))
    }

    async fn run_step(&self, invocation: StepInvocation) -> a3s_flow::Result<serde_json::Value> {
        let attempts = match invocation.step_id.as_str() {
            "alpha" => &self.alpha_attempts,
            "beta" => &self.beta_attempts,
            other => return Err(FlowError::Runtime(format!("unknown batch step {other}"))),
        };
        let attempt = attempts.fetch_add(1, Ordering::SeqCst) + 1;
        self.barrier.wait().await;
        if attempt == 1 {
            Err(FlowError::Runtime(format!(
                "{} failed once",
                invocation.step_id
            )))
        } else {
            Ok(json!({ "attempt": attempt }))
        }
    }
}

#[tokio::test]
async fn delayed_batch_retries_resume_all_due_siblings_concurrently() {
    let runtime = Arc::new(DelayedConcurrentBatchRuntime::new());
    let engine = FlowEngine::in_memory(runtime.clone());
    let run_id = engine.start(spec(), json!({})).await.unwrap();
    let suspended = engine.snapshot(&run_id).await.unwrap();

    assert_eq!(suspended.status, WorkflowRunStatus::Suspended);
    assert_eq!(suspended.steps["alpha"].status, StepStatus::Pending);
    assert_eq!(suspended.steps["beta"].status, StepStatus::Pending);
    assert_eq!(runtime.alpha_attempts.load(Ordering::SeqCst), 1);
    assert_eq!(runtime.beta_attempts.load(Ordering::SeqCst), 1);

    let resumed = tokio::time::timeout(
        Duration::from_secs(1),
        engine.resume_due_retries(Utc::now() + ChronoDuration::seconds(1)),
    )
    .await
    .expect("both due retries must re-enter the runtime together")
    .unwrap();
    assert_eq!(
        resumed,
        vec![
            (run_id.clone(), "alpha".to_string()),
            (run_id.clone(), "beta".to_string())
        ]
    );

    let completed = engine.snapshot(&run_id).await.unwrap();
    assert_eq!(completed.status, WorkflowRunStatus::Completed);
    assert_eq!(completed.steps["alpha"].attempt, 2);
    assert_eq!(completed.steps["beta"].attempt, 2);
    assert_eq!(runtime.alpha_attempts.load(Ordering::SeqCst), 2);
    assert_eq!(runtime.beta_attempts.load(Ordering::SeqCst), 2);
}

struct StaggeredDelayedBatchRuntime {
    alpha_attempts: AtomicUsize,
    beta_attempts: AtomicUsize,
}

impl StaggeredDelayedBatchRuntime {
    fn new() -> Self {
        Self {
            alpha_attempts: AtomicUsize::new(0),
            beta_attempts: AtomicUsize::new(0),
        }
    }
}

#[async_trait]
impl FlowRuntime for StaggeredDelayedBatchRuntime {
    async fn run_workflow(
        &self,
        invocation: WorkflowInvocation,
    ) -> a3s_flow::Result<RuntimeCommand> {
        let ctx = invocation.context();
        if ctx.step_output("alpha").is_some() && ctx.step_output("beta").is_some() {
            return Ok(ctx.complete(json!({ "done": true })));
        }
        Ok(ctx.schedule_steps(vec![
            ctx.step_with_retry(
                "alpha",
                "staggeredDelayed",
                json!({}),
                RetryPolicy::fixed(2, Duration::from_millis(10)),
            ),
            ctx.step_with_retry(
                "beta",
                "staggeredDelayed",
                json!({}),
                RetryPolicy::fixed(2, Duration::from_secs(60)),
            ),
        ]))
    }

    async fn run_step(&self, invocation: StepInvocation) -> a3s_flow::Result<serde_json::Value> {
        let attempts = match invocation.step_id.as_str() {
            "alpha" => &self.alpha_attempts,
            "beta" => &self.beta_attempts,
            other => return Err(FlowError::Runtime(format!("unknown batch step {other}"))),
        };
        let attempt = attempts.fetch_add(1, Ordering::SeqCst) + 1;
        if attempt == 1 {
            Err(FlowError::Runtime(format!(
                "{} failed once",
                invocation.step_id
            )))
        } else {
            Ok(json!({ "attempt": attempt }))
        }
    }
}

#[tokio::test]
async fn due_batch_retry_is_not_blocked_or_joined_by_a_future_sibling() {
    let runtime = Arc::new(StaggeredDelayedBatchRuntime::new());
    let engine = FlowEngine::in_memory(runtime.clone());
    let run_id = engine.start(spec(), json!({})).await.unwrap();
    let suspended = engine.snapshot(&run_id).await.unwrap();
    let alpha_due = suspended.steps["alpha"].retry_after.unwrap();
    let beta_due = suspended.steps["beta"].retry_after.unwrap();

    assert!(alpha_due < beta_due);
    assert_eq!(
        engine.resume_due_retries(alpha_due).await.unwrap(),
        vec![(run_id.clone(), "alpha".to_string())]
    );

    let partially_resumed = engine.snapshot(&run_id).await.unwrap();
    assert_eq!(partially_resumed.status, WorkflowRunStatus::Suspended);
    assert_eq!(
        partially_resumed.steps["alpha"].status,
        StepStatus::Completed
    );
    assert_eq!(partially_resumed.steps["alpha"].attempt, 2);
    assert_eq!(partially_resumed.steps["beta"].status, StepStatus::Pending);
    assert_eq!(partially_resumed.steps["beta"].attempt, 1);
    assert_eq!(runtime.alpha_attempts.load(Ordering::SeqCst), 2);
    assert_eq!(runtime.beta_attempts.load(Ordering::SeqCst), 1);

    assert_eq!(
        engine
            .resume_due_retries(beta_due + ChronoDuration::seconds(1))
            .await
            .unwrap(),
        vec![(run_id.clone(), "beta".to_string())]
    );
    let completed = engine.snapshot(&run_id).await.unwrap();
    assert_eq!(completed.status, WorkflowRunStatus::Completed);
    assert_eq!(runtime.beta_attempts.load(Ordering::SeqCst), 2);
}

struct DuplicateStepBatchRuntime;

#[async_trait]
impl FlowRuntime for DuplicateStepBatchRuntime {
    async fn run_workflow(
        &self,
        invocation: WorkflowInvocation,
    ) -> a3s_flow::Result<RuntimeCommand> {
        let ctx = invocation.context();
        Ok(ctx.schedule_steps(vec![
            ctx.step("duplicate", "first", json!({})),
            ctx.step("duplicate", "second", json!({})),
        ]))
    }

    async fn run_step(&self, _invocation: StepInvocation) -> a3s_flow::Result<serde_json::Value> {
        unreachable!("duplicate batch should fail before running steps")
    }
}

#[tokio::test]
async fn schedule_steps_rejects_duplicate_step_ids() {
    let engine = FlowEngine::in_memory(Arc::new(DuplicateStepBatchRuntime));
    let err = engine.start(spec(), json!({})).await.unwrap_err();

    assert!(
        matches!(err, FlowError::InvalidTransition(message) if message.contains("duplicate step id duplicate"))
    );
}