a3s-flow 0.4.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
#[cfg(all(feature = "native-ts", unix))]
mod native_ts_runtime {
    use a3s_flow::{
        FlowEngine, FlowError, NativeTsRuntime, NativeTsRuntimeConfig, WorkflowRunStatus,
        WorkflowSpec,
    };
    use serde_json::{json, Value};
    use std::fs;
    use std::os::unix::fs::PermissionsExt;
    use std::path::Path;
    use std::sync::Arc;

    fn native_spec(entrypoint: &str) -> WorkflowSpec {
        WorkflowSpec::native_ts("native.workflow", "0.1.0", entrypoint, "main")
    }

    fn shell_quote(path: &Path) -> String {
        let raw = path.to_string_lossy();
        format!("'{}'", raw.replace('\'', "'\"'\"'"))
    }

    fn write_executable(path: &Path, content: &str) {
        fs::write(path, content).unwrap();
        let mut permissions = fs::metadata(path).unwrap().permissions();
        permissions.set_mode(0o755);
        fs::set_permissions(path, permissions).unwrap();
    }

    fn write_fake_compiler(path: &Path, compile_log: &Path) {
        let content = format!(
            r#"#!/bin/sh
set -eu
printf 'compile\n' >> {compile_log}
if [ "$1" != "compile" ]; then
  echo "expected compile command" >&2
  exit 2
fi
if [ "$3" != "-o" ]; then
  echo "expected -o" >&2
  exit 2
fi
cp "$2" "$4"
chmod +x "$4"
"#,
            compile_log = shell_quote(compile_log),
        );
        write_executable(path, &content);
    }

    fn write_failing_compiler(path: &Path, compile_log: &Path) {
        let content = format!(
            r#"#!/bin/sh
set -eu
printf 'compile\n' >> {compile_log}
echo "compile broke on purpose" >&2
exit 9
"#,
            compile_log = shell_quote(compile_log),
        );
        write_executable(path, &content);
    }

    fn write_runtime_source(path: &Path, request_log: &Path, marker: &str, protocol: &str) {
        let content = format!(
            r#"#!/bin/sh
set -eu
request="$(cat)"
printf '%s\n' "$request" >> {request_log}
printf '{{"protocol":"{protocol}","kind":"workflow","ok":true,"output":{{"type":"complete","output":{{"marker":"{marker}"}}}}}}\n'
"#,
            marker = marker,
            protocol = protocol,
            request_log = shell_quote(request_log),
        );
        write_executable(path, &content);
    }

    fn write_step_runtime_source(path: &Path, request_log: &Path) {
        let content = format!(
            r#"#!/bin/sh
set -eu
request="$(cat)"
printf '%s\n' "$request" >> {request_log}
case "$request" in
  *'"kind":"step"'*)
    printf '{{"protocol":"a3s.flow.native_ts.v1","kind":"step","ok":true,"output":{{"message":"native step complete"}}}}\n'
    ;;
  *'"type":"step_completed"'*)
    printf '{{"protocol":"a3s.flow.native_ts.v1","kind":"workflow","ok":true,"output":{{"type":"complete","output":{{"status":"done"}}}}}}\n'
    ;;
  *)
    printf '{{"protocol":"a3s.flow.native_ts.v1","kind":"workflow","ok":true,"output":{{"type":"schedule_step","step_id":"native-step","step_name":"nativeStep","input":{{"value":42}},"retry":{{"max_attempts":1,"delay_ms":0}}}}}}\n'
    ;;
esac
"#,
            request_log = shell_quote(request_log),
        );
        write_executable(path, &content);
    }

    fn write_mismatched_kind_runtime_source(path: &Path, request_log: &Path) {
        let content = format!(
            r#"#!/bin/sh
set -eu
request="$(cat)"
printf '%s\n' "$request" >> {request_log}
printf '{{"protocol":"a3s.flow.native_ts.v1","kind":"step","ok":true,"output":{{"type":"complete","output":{{}}}}}}\n'
"#,
            request_log = shell_quote(request_log),
        );
        write_executable(path, &content);
    }

    fn write_error_runtime_source(path: &Path, request_log: &Path) {
        let content = format!(
            r#"#!/bin/sh
set -eu
request="$(cat)"
printf '%s\n' "$request" >> {request_log}
printf '{{"protocol":"a3s.flow.native_ts.v1","kind":"workflow","ok":false,"error":"runtime rejected workflow"}}\n'
"#,
            request_log = shell_quote(request_log),
        );
        write_executable(path, &content);
    }

    fn compile_count(path: &Path) -> usize {
        fs::read_to_string(path).unwrap_or_default().lines().count()
    }

    fn requests(path: &Path) -> Vec<Value> {
        fs::read_to_string(path)
            .unwrap()
            .lines()
            .map(|line| serde_json::from_str(line).unwrap())
            .collect()
    }

    fn last_request(path: &Path) -> Value {
        let content = fs::read_to_string(path).unwrap();
        let line = content.lines().last().unwrap();
        serde_json::from_str(line).unwrap()
    }

    #[tokio::test]
    async fn native_runtime_preflight_compiles_and_reports_artifact() {
        let dir = tempfile::tempdir().unwrap();
        let compiler = dir.path().join("fake-compiler");
        let compile_log = dir.path().join("compile.log");
        let entrypoint = dir.path().join("workflow.ts");
        let request_log = dir.path().join("requests.jsonl");
        let cache_dir = dir.path().join("cache");

        write_fake_compiler(&compiler, &compile_log);
        write_runtime_source(
            &entrypoint,
            &request_log,
            "preflight",
            "a3s.flow.native_ts.v1",
        );

        let runtime = NativeTsRuntime::new(NativeTsRuntimeConfig::new(
            &compiler,
            &cache_dir,
            dir.path(),
        ));
        let spec = native_spec("workflow.ts");

        let first = runtime.preflight(&spec).await.unwrap();
        assert_eq!(first.entrypoint, entrypoint);
        assert!(first.artifact.starts_with(&cache_dir));
        assert_eq!(first.source_hash.len(), 64);
        assert!(!first.cache_hit);
        assert!(first.artifact.is_file());
        assert_eq!(compile_count(&compile_log), 1);

        let second = runtime.preflight(&spec).await.unwrap();
        assert_eq!(second.entrypoint, first.entrypoint);
        assert_eq!(second.artifact, first.artifact);
        assert_eq!(second.source_hash, first.source_hash);
        assert!(second.cache_hit);
        assert_eq!(compile_count(&compile_log), 1);
    }

    #[tokio::test]
    async fn native_runtime_preflight_surfaces_compile_stderr() {
        let dir = tempfile::tempdir().unwrap();
        let compiler = dir.path().join("failing-compiler");
        let compile_log = dir.path().join("compile.log");
        let entrypoint = dir.path().join("workflow.ts");
        let cache_dir = dir.path().join("cache");

        write_failing_compiler(&compiler, &compile_log);
        fs::write(&entrypoint, "export async function main() {}\n").unwrap();

        let runtime = NativeTsRuntime::new(NativeTsRuntimeConfig::new(
            &compiler,
            &cache_dir,
            dir.path(),
        ));
        let err = runtime
            .preflight(&native_spec("workflow.ts"))
            .await
            .unwrap_err();

        assert!(
            matches!(err, FlowError::Runtime(message) if message.contains("native TypeScript compile failed") && message.contains("compile broke on purpose"))
        );
        assert_eq!(compile_count(&compile_log), 1);
    }

    #[tokio::test]
    async fn native_runtime_preflight_rejects_non_native_ts_spec() {
        let dir = tempfile::tempdir().unwrap();
        let compiler = dir.path().join("fake-compiler");
        let compile_log = dir.path().join("compile.log");
        let runtime = NativeTsRuntime::new(NativeTsRuntimeConfig::new(
            &compiler,
            dir.path().join("cache"),
            dir.path(),
        ));
        write_fake_compiler(&compiler, &compile_log);

        let spec = WorkflowSpec::rust_embedded("rust.workflow", "0.1.0", "src/lib.rs", "main");
        let err = runtime.preflight(&spec).await.unwrap_err();

        assert!(
            matches!(err, FlowError::InvalidWorkflow(message) if message.contains("native_ts workflow spec"))
        );
        assert_eq!(compile_count(&compile_log), 0);
    }

    #[tokio::test]
    async fn native_runtime_compiles_by_source_hash_and_reuses_cached_artifact() {
        let dir = tempfile::tempdir().unwrap();
        let compiler = dir.path().join("fake-compiler");
        let compile_log = dir.path().join("compile.log");
        let entrypoint = dir.path().join("workflow.ts");
        let request_log = dir.path().join("requests.jsonl");
        let cache_dir = dir.path().join("cache");

        write_fake_compiler(&compiler, &compile_log);
        write_runtime_source(&entrypoint, &request_log, "first", "a3s.flow.native_ts.v1");

        let runtime = Arc::new(NativeTsRuntime::new(NativeTsRuntimeConfig::new(
            &compiler,
            &cache_dir,
            dir.path(),
        )));
        let engine = FlowEngine::in_memory(runtime);
        let spec = native_spec("workflow.ts");

        let first_run_id = engine.start(spec.clone(), json!({ "n": 1 })).await.unwrap();
        let first = engine.snapshot(&first_run_id).await.unwrap();
        assert_eq!(first.status, WorkflowRunStatus::Completed);
        assert_eq!(first.output.unwrap()["marker"], "first");
        assert_eq!(compile_count(&compile_log), 1);

        let second_run_id = engine.start(spec.clone(), json!({ "n": 2 })).await.unwrap();
        let second = engine.snapshot(&second_run_id).await.unwrap();
        assert_eq!(second.output.unwrap()["marker"], "first");
        assert_eq!(
            compile_count(&compile_log),
            1,
            "unchanged source should reuse the compiled artifact"
        );

        let request = last_request(&request_log);
        assert_eq!(request["protocol"], "a3s.flow.native_ts.v1");
        assert_eq!(request["kind"], "workflow");
        assert_eq!(request["exportName"], "main");
        assert_eq!(request["payload"]["run_id"], second_run_id);
        assert_eq!(request["sourceHash"].as_str().unwrap().len(), 64);

        write_runtime_source(&entrypoint, &request_log, "second", "a3s.flow.native_ts.v1");

        let third_run_id = engine.start(spec, json!({ "n": 3 })).await.unwrap();
        let third = engine.snapshot(&third_run_id).await.unwrap();
        assert_eq!(third.output.unwrap()["marker"], "second");
        assert_eq!(
            compile_count(&compile_log),
            2,
            "changed source should compile to a new artifact"
        );
    }

    #[tokio::test]
    async fn native_runtime_rejects_invalid_protocol_envelope() {
        let dir = tempfile::tempdir().unwrap();
        let compiler = dir.path().join("fake-compiler");
        let compile_log = dir.path().join("compile.log");
        let entrypoint = dir.path().join("workflow.ts");
        let request_log = dir.path().join("requests.jsonl");
        let cache_dir = dir.path().join("cache");

        write_fake_compiler(&compiler, &compile_log);
        write_runtime_source(&entrypoint, &request_log, "bad", "wrong.protocol");

        let runtime = Arc::new(NativeTsRuntime::new(NativeTsRuntimeConfig::new(
            &compiler,
            &cache_dir,
            dir.path(),
        )));
        let engine = FlowEngine::in_memory(runtime);

        let err = engine
            .start(native_spec("workflow.ts"), json!({}))
            .await
            .unwrap_err();

        assert!(
            matches!(err, FlowError::Runtime(message) if message.contains("protocol mismatch"))
        );
    }

    #[tokio::test]
    async fn native_runtime_invokes_step_with_same_protocol_and_source_hash() {
        let dir = tempfile::tempdir().unwrap();
        let compiler = dir.path().join("fake-compiler");
        let compile_log = dir.path().join("compile.log");
        let entrypoint = dir.path().join("workflow.ts");
        let request_log = dir.path().join("requests.jsonl");
        let cache_dir = dir.path().join("cache");

        write_fake_compiler(&compiler, &compile_log);
        write_step_runtime_source(&entrypoint, &request_log);

        let runtime = Arc::new(NativeTsRuntime::new(NativeTsRuntimeConfig::new(
            &compiler,
            &cache_dir,
            dir.path(),
        )));
        let engine = FlowEngine::in_memory(runtime);
        let run_id = engine
            .start(native_spec("workflow.ts"), json!({ "n": 1 }))
            .await
            .unwrap();
        let snapshot = engine.snapshot(&run_id).await.unwrap();

        assert_eq!(snapshot.status, WorkflowRunStatus::Completed);
        assert_eq!(snapshot.output.unwrap()["status"], "done");
        assert_eq!(
            snapshot.steps["native-step"].output.as_ref().unwrap()["message"],
            "native step complete"
        );
        assert_eq!(compile_count(&compile_log), 1);

        let requests = requests(&request_log);
        assert_eq!(requests.len(), 3);
        assert_eq!(requests[0]["kind"], "workflow");
        assert_eq!(requests[1]["kind"], "step");
        assert_eq!(requests[2]["kind"], "workflow");
        assert_eq!(requests[1]["exportName"], "main");
        assert_eq!(requests[1]["payload"]["run_id"], run_id);
        assert_eq!(requests[1]["payload"]["step_id"], "native-step");
        assert_eq!(requests[1]["payload"]["step_name"], "nativeStep");
        assert_eq!(requests[1]["payload"]["input"]["value"], 42);
        assert_eq!(requests[1]["sourceHash"], requests[0]["sourceHash"]);
        assert_eq!(requests[2]["sourceHash"], requests[0]["sourceHash"]);
    }

    #[tokio::test]
    async fn native_runtime_rejects_response_kind_mismatch() {
        let dir = tempfile::tempdir().unwrap();
        let compiler = dir.path().join("fake-compiler");
        let compile_log = dir.path().join("compile.log");
        let entrypoint = dir.path().join("workflow.ts");
        let request_log = dir.path().join("requests.jsonl");
        let cache_dir = dir.path().join("cache");

        write_fake_compiler(&compiler, &compile_log);
        write_mismatched_kind_runtime_source(&entrypoint, &request_log);

        let runtime = Arc::new(NativeTsRuntime::new(NativeTsRuntimeConfig::new(
            &compiler,
            &cache_dir,
            dir.path(),
        )));
        let engine = FlowEngine::in_memory(runtime);

        let err = engine
            .start(native_spec("workflow.ts"), json!({}))
            .await
            .unwrap_err();

        assert!(
            matches!(err, FlowError::Runtime(message) if message.contains("response kind mismatch"))
        );
    }

    #[tokio::test]
    async fn native_runtime_surfaces_error_envelope() {
        let dir = tempfile::tempdir().unwrap();
        let compiler = dir.path().join("fake-compiler");
        let compile_log = dir.path().join("compile.log");
        let entrypoint = dir.path().join("workflow.ts");
        let request_log = dir.path().join("requests.jsonl");
        let cache_dir = dir.path().join("cache");

        write_fake_compiler(&compiler, &compile_log);
        write_error_runtime_source(&entrypoint, &request_log);

        let runtime = Arc::new(NativeTsRuntime::new(NativeTsRuntimeConfig::new(
            &compiler,
            &cache_dir,
            dir.path(),
        )));
        let engine = FlowEngine::in_memory(runtime);

        let err = engine
            .start(native_spec("workflow.ts"), json!({}))
            .await
            .unwrap_err();

        assert!(
            matches!(err, FlowError::Runtime(message) if message == "runtime rejected workflow")
        );
    }
}