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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
//! [`WorkflowContext`] — execution context for dynamic workflows.
//!
//! Provides step execution methods that automatically persist results to the
//! store. Each call to [`shell`](WorkflowContext::shell),
//! [`http`](WorkflowContext::http), [`agent`](WorkflowContext::agent), or
//! [`workflow`](WorkflowContext::workflow) creates a step record, executes the
//! operation, captures the output, and returns a [`StepOutput`] that the next
//! step can reference.
//!
//! # Examples
//!
//! ```no_run
//! use ironflow_engine::context::WorkflowContext;
//! use ironflow_engine::config::{ShellConfig, AgentStepConfig};
//! use ironflow_engine::error::EngineError;
//!
//! # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
//! let build = ctx.shell("build", ShellConfig::new("cargo build")).await?;
//! let review = ctx.agent("review", AgentStepConfig::new(
//! &format!("Build output:\n{}", build.output["stdout"])
//! )).await?;
//! # Ok(())
//! # }
//! ```
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use std::time::Instant;
use chrono::{DateTime, Utc};
use futures_util::StreamExt;
use rust_decimal::Decimal;
use serde_json::{Value, json};
use tokio::task::{Id, JoinSet};
use tracing::{error, info, warn};
use uuid::Uuid;
use ironflow_core::error::{AgentError, OperationError};
use ironflow_core::provider::AgentProvider;
use ironflow_store::models::{
ArtifactLookup, NewRun, NewStep, NewStepDependency, RunStatus, RunUpdate, Step, StepKind,
StepStatus, StepUpdate, TriggerKind,
};
use ironflow_store::store::Store;
use ironflow_artifacts::name::guess_content_type;
use ironflow_artifacts::stream_from_bytes;
use ironflow_store::entities::Artifact;
use crate::artifact::{
ArtifactSink, ArtifactUpload, StepLocation, collect_outputs, materialize_inputs,
};
use crate::budget::step_budget_usd;
use crate::config::{
AgentStepConfig, ApprovalConfig, HttpConfig, ShellConfig, StepConfig, WorkflowStepConfig,
};
use crate::error::EngineError;
use crate::executor::{ParallelStepResult, StepOutput, execute_step_config};
use crate::handler::WorkflowHandler;
use crate::log_sender::{LogSender, StepLogSender};
use crate::operation::Operation;
/// Callback type for resolving workflow handlers by name.
pub(crate) type HandlerResolver =
Arc<dyn Fn(&str) -> Option<Arc<dyn WorkflowHandler>> + Send + Sync>;
/// Execution context for a single workflow run.
///
/// Tracks the current step position and provides convenience methods
/// for executing operations with automatic persistence.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::context::WorkflowContext;
/// use ironflow_engine::config::ShellConfig;
/// use ironflow_engine::error::EngineError;
///
/// # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
/// let result = ctx.shell("greet", ShellConfig::new("echo hello")).await?;
/// assert!(result.output["stdout"].as_str().unwrap().contains("hello"));
/// # Ok(())
/// # }
/// ```
pub struct WorkflowContext {
run_id: Uuid,
store: Arc<dyn Store>,
provider: Arc<dyn AgentProvider>,
handler_resolver: Option<HandlerResolver>,
position: u32,
/// IDs of the last executed step(s) -- used to record DAG dependencies.
last_step_ids: Vec<Uuid>,
/// Accumulated cost across all steps in this run.
total_cost_usd: Decimal,
/// Accumulated duration across all steps.
total_duration_ms: u64,
/// Cumulative cost cap for this run, resolved at creation. `None` = no cap.
max_cost_usd: Option<Decimal>,
/// Cost already spent by ancestor runs when this context belongs to a
/// sub-workflow. Zero for a top-level run.
inherited_cost_usd: Decimal,
/// Steps from a previous execution of the *same* attempt, keyed by position.
/// Used when resuming after approval to replay completed steps.
replay_steps: HashMap<u32, Step>,
/// Approvals granted in an *earlier* attempt, keyed by position, holding the
/// attempt that granted them. An approval is carried by the run, not by the
/// attempt, so a retry never asks a human to approve the same gate twice.
granted_approvals: HashMap<u32, u32>,
/// Which run attempt this context is executing (1-based).
attempt: u32,
/// Wall-clock duration already recorded on the run by previous attempts.
/// Added to this attempt's duration when the run is finalized.
carried_duration_ms: u64,
/// Optional sender for real-time log streaming.
log_sender: Option<LogSender>,
/// Where artifact bytes are read and written. `None` when no artifact
/// storage is configured: steps that declare artifacts then fail explicitly
/// instead of silently dropping their files.
artifact_sink: Option<Arc<dyn ArtifactSink>>,
}
impl WorkflowContext {
/// Create a new context for a run.
///
/// Not typically called directly — the [`Engine`](crate::engine::Engine)
/// creates this when executing a [`WorkflowHandler`].
pub fn new(run_id: Uuid, store: Arc<dyn Store>, provider: Arc<dyn AgentProvider>) -> Self {
Self {
run_id,
store,
provider,
handler_resolver: None,
position: 0,
last_step_ids: Vec::new(),
total_cost_usd: Decimal::ZERO,
total_duration_ms: 0,
max_cost_usd: None,
inherited_cost_usd: Decimal::ZERO,
replay_steps: HashMap::new(),
granted_approvals: HashMap::new(),
attempt: 1,
carried_duration_ms: 0,
log_sender: None,
artifact_sink: None,
}
}
/// Create a new context with a handler resolver for sub-workflow support.
///
/// The resolver is called when [`workflow`](Self::workflow) is invoked to
/// look up registered handlers by name.
pub(crate) fn with_handler_resolver(
run_id: Uuid,
store: Arc<dyn Store>,
provider: Arc<dyn AgentProvider>,
resolver: HandlerResolver,
) -> Self {
Self {
run_id,
store,
provider,
handler_resolver: Some(resolver),
position: 0,
last_step_ids: Vec::new(),
total_cost_usd: Decimal::ZERO,
total_duration_ms: 0,
max_cost_usd: None,
inherited_cost_usd: Decimal::ZERO,
replay_steps: HashMap::new(),
granted_approvals: HashMap::new(),
attempt: 1,
carried_duration_ms: 0,
log_sender: None,
artifact_sink: None,
}
}
/// Attach a log sender for real-time step output streaming.
pub fn set_log_sender(&mut self, sender: LogSender) {
self.log_sender = Some(sender);
}
/// Attach the backend that stores and serves artifact bytes.
///
/// Without one, any step that declares an output or calls
/// [`put_artifact`](Self::put_artifact) fails with
/// [`EngineError::ArtifactsUnavailable`]. Every other step is unaffected,
/// so an existing deployment keeps working until artifacts are configured.
///
/// # Examples
///
/// ```no_run
/// use std::sync::Arc;
///
/// use ironflow_engine::artifact::ArtifactSink;
/// use ironflow_engine::context::WorkflowContext;
///
/// # fn example(ctx: &mut WorkflowContext, sink: Arc<dyn ArtifactSink>) {
/// ctx.set_artifact_sink(sink);
/// # }
/// ```
pub fn set_artifact_sink(&mut self, sink: Arc<dyn ArtifactSink>) {
self.artifact_sink = Some(sink);
}
/// The artifact backend, or an explicit error when none is configured.
fn artifact_sink(&self) -> Result<&Arc<dyn ArtifactSink>, EngineError> {
self.artifact_sink.as_ref().ok_or_else(|| {
EngineError::ArtifactsUnavailable(
"no artifact storage is attached to this run".to_string(),
)
})
}
/// Store an in-memory payload as an artifact of the given step.
///
/// The declarative [`ShellConfig::output`](crate::config::ShellConfig::output)
/// covers shell steps; this covers custom operations and agent steps, which
/// have no working directory to collect from.
///
/// The MIME type is guessed from `name` unless `content_type` is set.
///
/// # Errors
///
/// Returns [`EngineError::ArtifactsUnavailable`] when no backend is
/// attached, [`EngineError::Artifact`] when the name is invalid or storage
/// fails, and [`EngineError::Store`] when the step already owns that name.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::context::WorkflowContext;
/// use ironflow_engine::error::EngineError;
/// use uuid::Uuid;
///
/// # async fn example(ctx: &WorkflowContext, step_id: Uuid) -> Result<(), EngineError> {
/// let artifact = ctx
/// .put_artifact(step_id, "summary.json", None, br#"{"ok":true}"#.to_vec())
/// .await?;
/// assert_eq!(artifact.content_type, "application/json");
/// # Ok(())
/// # }
/// ```
pub async fn put_artifact(
&self,
step_id: Uuid,
name: &str,
content_type: Option<&str>,
content: Vec<u8>,
) -> Result<Artifact, EngineError> {
let sink = self.artifact_sink()?;
sink.put(
ArtifactUpload {
run_id: self.run_id,
step_id,
name: name.to_string(),
content_type: content_type
.map(str::to_string)
.unwrap_or_else(|| guess_content_type(name)),
},
stream_from_bytes(content),
)
.await
}
/// Read back an artifact produced earlier in this run.
///
/// Resolution follows the same rule as a declared input: same run and
/// attempt, steps positioned strictly before the current one, closest
/// producer wins.
///
/// # Errors
///
/// Returns [`EngineError::ArtifactNotFound`] when nothing matches,
/// [`EngineError::ArtifactsUnavailable`] when no backend is attached, and
/// [`EngineError::Artifact`] when the bytes cannot be read.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::context::WorkflowContext;
/// use ironflow_engine::error::EngineError;
///
/// # async fn example(ctx: &WorkflowContext) -> Result<(), EngineError> {
/// let bytes = ctx.get_artifact("build", "report.html").await?;
/// println!("{} bytes", bytes.len());
/// # Ok(())
/// # }
/// ```
pub async fn get_artifact(&self, step: &str, name: &str) -> Result<Vec<u8>, EngineError> {
let sink = self.artifact_sink()?;
let artifact = self
.store
.find_artifact_for_input(ArtifactLookup {
run_id: self.run_id,
attempt: self.attempt,
before_position: self.position,
step_name: step.to_string(),
name: name.to_string(),
})
.await?
.ok_or_else(|| EngineError::ArtifactNotFound {
step: step.to_string(),
name: name.to_string(),
})?;
let mut content = sink.get(&artifact).await?;
let mut buffer = Vec::with_capacity(artifact.size_bytes as usize);
while let Some(chunk) = content.next().await {
let chunk = chunk?;
buffer.extend_from_slice(chunk.as_ref());
}
Ok(buffer)
}
/// Place a shell step's declared inputs in its working directory.
///
/// A step that declares none needs no backend, so the check for one only
/// happens when there is something to materialize.
async fn prepare_step_inputs(
&self,
config: &StepConfig,
position: u32,
) -> Result<(), EngineError> {
let StepConfig::Shell(shell) = config else {
return Ok(());
};
if shell.inputs.is_empty() {
return Ok(());
}
materialize_inputs(
self.artifact_sink()?,
&self.store,
shell,
StepLocation {
run_id: self.run_id,
attempt: self.attempt,
position,
},
)
.await
}
/// Store a shell step's declared outputs.
///
/// On a failed step this is best-effort: the collection error is logged and
/// swallowed so it never masks the failure that actually stopped the step.
async fn store_step_outputs(
&self,
config: &StepConfig,
step_id: Uuid,
step_name: &str,
step_succeeded: bool,
) -> Result<(), EngineError> {
let StepConfig::Shell(shell) = config else {
return Ok(());
};
if shell.outputs.is_empty() {
return Ok(());
}
let sink = match self.artifact_sink() {
Ok(sink) => sink,
Err(err) if step_succeeded => return Err(err),
Err(err) => {
warn!(
run_id = %self.run_id,
step = %step_name,
error = %err,
"cannot collect outputs of a failed step"
);
return Ok(());
}
};
let collected =
collect_outputs(sink, shell, self.run_id, step_id, step_name, step_succeeded).await;
match collected {
Ok(()) => Ok(()),
Err(err) if step_succeeded => Err(err),
Err(err) => {
warn!(
run_id = %self.run_id,
step = %step_name,
error = %err,
"failed to collect outputs of a failed step"
);
Ok(())
}
}
}
/// Seed the context with the run's attempt number and the totals already
/// accumulated by previous attempts.
///
/// Called by the engine before executing a handler. Steps created by this
/// context belong to `attempt`, and the cost and duration it reports at the
/// end cover the whole run, not just this attempt.
pub(crate) fn carry_over_run_totals(
&mut self,
attempt: u32,
cost_usd: Decimal,
duration_ms: u64,
) {
self.attempt = attempt;
self.total_cost_usd = cost_usd;
self.carried_duration_ms = duration_ms;
}
/// Wall-clock duration already recorded on the run by previous attempts.
pub(crate) fn carried_duration_ms(&self) -> u64 {
self.carried_duration_ms
}
/// The run attempt this context is executing (1-based).
pub fn attempt(&self) -> u32 {
self.attempt
}
/// Set the cumulative cost cap enforced before every agent step.
///
/// Called by the [`Engine`](crate::engine::Engine) with the run's persisted
/// `max_cost_usd`. `None` disables the check.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::context::WorkflowContext;
/// use rust_decimal::Decimal;
///
/// # fn example(ctx: &mut WorkflowContext) {
/// ctx.set_max_cost_usd(Some(Decimal::new(200, 2))); // $2.00
/// # }
/// ```
pub fn set_max_cost_usd(&mut self, cap: Option<Decimal>) {
self.max_cost_usd = cap;
}
/// The cumulative cost cap of this run, if any.
pub fn max_cost_usd(&self) -> Option<Decimal> {
self.max_cost_usd
}
/// Total cost charged against the cap: this run plus every ancestor run.
///
/// For a top-level run this equals [`total_cost_usd`](Self::total_cost_usd).
/// For a sub-workflow it also includes what the parent chain already spent.
pub fn charged_cost_usd(&self) -> Decimal {
self.inherited_cost_usd + self.total_cost_usd
}
/// Reject the upcoming agent work when it would cross the run's cost cap.
///
/// `step_budget` is the declared budget of the step (or the sum of budgets
/// for a parallel wave). Called *before* any step record is created so a
/// refused run never launches the work it could not afford.
///
/// # Errors
///
/// Returns [`EngineError::RunBudgetExceeded`] when
/// `charged_cost + step_budget` exceeds the cap.
fn check_run_budget(&self, step_budget: Decimal) -> Result<(), EngineError> {
let Some(limit) = self.max_cost_usd else {
return Ok(());
};
let spent = self.charged_cost_usd();
if spent + step_budget <= limit {
return Ok(());
}
error!(
run_id = %self.run_id,
limit_usd = %limit,
spent_usd = %spent,
step_budget_usd = %step_budget,
"run cost cap reached, refusing agent step"
);
Err(EngineError::RunBudgetExceeded {
run_id: self.run_id,
limit_usd: limit,
spent_usd: spent,
step_budget_usd: step_budget,
})
}
/// Load existing steps from the store for replay after approval.
///
/// Called by the engine when resuming a run. All completed steps
/// and the approved approval step are indexed by position so that
/// `execute_step` and `approval` can skip them.
///
/// Only steps of the current attempt are replayed: positions repeat across
/// attempts, so replaying an earlier attempt's steps would skip the whole
/// workflow. The one exception is an approval already granted in an earlier
/// attempt -- approval is carried by the run, not by the attempt, so a human
/// is never asked to approve the same gate twice.
pub(crate) async fn load_replay_steps(&mut self) -> Result<(), EngineError> {
let steps = self.store.list_steps(self.run_id).await?;
for step in steps {
let dominated = matches!(
step.status.state,
StepStatus::Completed | StepStatus::Running | StepStatus::AwaitingApproval
);
if !dominated {
continue;
}
if step.attempt == self.attempt {
self.replay_steps.insert(step.position, step);
} else if step.kind == StepKind::Approval && step.status.state == StepStatus::Completed
{
self.granted_approvals.insert(step.position, step.attempt);
}
}
Ok(())
}
/// The run ID this context is executing for.
pub fn run_id(&self) -> Uuid {
self.run_id
}
/// Accumulated cost across all executed steps so far.
pub fn total_cost_usd(&self) -> Decimal {
self.total_cost_usd
}
/// Accumulated duration across all executed steps so far.
pub fn total_duration_ms(&self) -> u64 {
self.total_duration_ms
}
/// Execute multiple steps concurrently (wait-all model).
///
/// All steps in the batch execute in parallel via `tokio::JoinSet`.
/// Each step is recorded with the same `position` (execution wave).
/// Dependencies on previous steps are recorded automatically.
///
/// When `fail_fast` is true, remaining steps are aborted on the first
/// failure. When false, all steps run to completion and the first
/// error is returned.
///
/// # Errors
///
/// Returns [`EngineError`] if any step fails.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::context::WorkflowContext;
/// use ironflow_engine::config::{StepConfig, ShellConfig};
/// use ironflow_engine::error::EngineError;
///
/// # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
/// let results = ctx.parallel(
/// vec![
/// ("test-unit", StepConfig::Shell(ShellConfig::new("cargo test --lib"))),
/// ("lint", StepConfig::Shell(ShellConfig::new("cargo clippy"))),
/// ],
/// true,
/// ).await?;
///
/// for r in &results {
/// println!("{}: {:?}", r.name, r.output.output);
/// }
/// # Ok(())
/// # }
/// ```
pub async fn parallel(
&mut self,
steps: Vec<(&str, StepConfig)>,
fail_fast: bool,
) -> Result<Vec<ParallelStepResult>, EngineError> {
if steps.is_empty() {
return Ok(Vec::new());
}
// Cost cap: the whole wave is charged at once. Refused before any step
// record is created, so nothing in the wave starts.
let wave_budget: Decimal = steps
.iter()
.filter_map(|(_, config)| match config {
StepConfig::Agent(agent_config) => Some(agent_config.max_budget_usd),
_ => None,
})
.map(step_budget_usd)
.sum();
self.check_run_budget(wave_budget)?;
let wave_position = self.position;
self.position += 1;
let now = Utc::now();
let mut step_records: Vec<(Uuid, String, StepConfig)> = Vec::with_capacity(steps.len());
for (name, config) in &steps {
let kind = config.kind();
let step = self
.store
.create_step(NewStep {
run_id: self.run_id,
name: name.to_string(),
kind,
position: wave_position,
input: Some(serde_json::to_value(config)?),
})
.await?;
self.start_step(step.id, now).await?;
// Inputs are materialized before any step in the wave starts, so a
// missing one fails the wave rather than a half-run command.
if let Err(err) = self.prepare_step_inputs(config, wave_position).await {
self.fail_step(step.id, &err).await;
return Err(err);
}
step_records.push((step.id, name.to_string(), config.clone()));
}
let mut join_set = JoinSet::new();
let mut task_index: HashMap<Id, usize> = HashMap::new();
for (idx, (step_id, step_name, config)) in step_records.iter().enumerate() {
let provider = self.provider.clone();
let config = config.clone();
let step_log_sender = self
.log_sender
.as_ref()
.map(|s| StepLogSender::new(s.clone(), self.run_id, *step_id, step_name.clone()));
let handle = join_set.spawn(async move {
(
idx,
execute_step_config(&config, &provider, step_log_sender).await,
)
});
task_index.insert(handle.id(), idx);
}
// JoinSet returns in completion order; indexed_results restores input order.
let mut indexed_results: Vec<Option<Result<StepOutput, String>>> =
vec![None; step_records.len()];
let mut first_error: Option<EngineError> = None;
while let Some(join_result) = join_set.join_next().await {
let (idx, step_result) = match join_result {
Ok(r) => r,
Err(e) => {
let error_msg = format!("join error: {e}");
if let Some(&idx) = task_index.get(&e.id()) {
let (step_id, step_name, _) = &step_records[idx];
let completed_at = Utc::now();
error!(
run_id = %self.run_id,
step = %step_name,
error = %error_msg,
"parallel step panicked or was cancelled"
);
if let Err(store_err) = self
.store
.update_step(
*step_id,
StepUpdate {
status: Some(StepStatus::Failed),
error: Some(error_msg.clone()),
completed_at: Some(completed_at),
..StepUpdate::default()
},
)
.await
{
error!(
run_id = %self.run_id,
step_id = %step_id,
error = %store_err,
"failed to persist JoinError for step"
);
}
indexed_results[idx] = Some(Err(error_msg.clone()));
}
if first_error.is_none() {
first_error = Some(EngineError::StepConfig(error_msg));
}
if fail_fast {
join_set.abort_all();
}
continue;
}
};
let (step_id, step_name, step_config) = &step_records[idx];
let completed_at = Utc::now();
if let Err(err) = self
.store_step_outputs(step_config, *step_id, step_name, step_result.is_ok())
.await
{
self.fail_step(*step_id, &err).await;
indexed_results[idx] = Some(Err(err.to_string()));
if first_error.is_none() {
first_error = Some(err);
}
if fail_fast {
join_set.abort_all();
}
continue;
}
match step_result {
Ok(output) => {
self.total_cost_usd += output.cost_usd;
self.total_duration_ms += output.duration_ms;
let debug_messages_json = output.debug_messages_json();
self.store
.update_step(
*step_id,
StepUpdate {
status: Some(StepStatus::Completed),
output: Some(output.output.clone()),
duration_ms: Some(output.duration_ms),
cost_usd: Some(output.cost_usd),
input_tokens: output.input_tokens,
output_tokens: output.output_tokens,
completed_at: Some(completed_at),
debug_messages: debug_messages_json,
..StepUpdate::default()
},
)
.await?;
info!(
run_id = %self.run_id,
step = %step_name,
duration_ms = output.duration_ms,
"parallel step completed"
);
indexed_results[idx] = Some(Ok(output));
}
Err(err) => {
let err_msg = err.to_string();
let debug_messages_json = extract_debug_messages_from_error(&err);
let partial = extract_partial_usage_from_error(&err);
let raw_response_output = extract_raw_response_from_error(&err);
if let Some(ref usage) = partial {
if let Some(cost) = usage.cost_usd {
self.total_cost_usd += cost;
}
if let Some(dur) = usage.duration_ms {
self.total_duration_ms += dur;
}
}
if let Err(store_err) = self
.store
.update_step(
*step_id,
StepUpdate {
status: Some(StepStatus::Failed),
error: Some(err_msg.clone()),
output: raw_response_output,
completed_at: Some(completed_at),
debug_messages: debug_messages_json,
duration_ms: partial.as_ref().and_then(|p| p.duration_ms),
cost_usd: partial.as_ref().and_then(|p| p.cost_usd),
input_tokens: partial.as_ref().and_then(|p| p.input_tokens),
output_tokens: partial.as_ref().and_then(|p| p.output_tokens),
..StepUpdate::default()
},
)
.await
{
tracing::error!(
step_id = %step_id,
error = %store_err,
"failed to persist parallel step failure"
);
}
indexed_results[idx] = Some(Err(err_msg.clone()));
if first_error.is_none() {
first_error = Some(err);
}
if fail_fast {
join_set.abort_all();
}
}
}
}
if let Some(err) = first_error {
return Err(err);
}
self.last_step_ids = step_records.iter().map(|(id, _, _)| *id).collect();
// Build results in original order.
let results: Vec<ParallelStepResult> = step_records
.iter()
.enumerate()
.map(|(idx, (step_id, name, _))| {
let output = match indexed_results[idx].take() {
Some(Ok(o)) => o,
_ => unreachable!("all steps succeeded if no error returned"),
};
ParallelStepResult {
name: name.clone(),
output,
step_id: *step_id,
}
})
.collect();
Ok(results)
}
/// Execute a shell step.
///
/// Creates the step record, runs the command, persists the result,
/// and returns the output for use in subsequent steps.
///
/// # Errors
///
/// Returns [`EngineError`] if the command fails or the store errors.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::context::WorkflowContext;
/// use ironflow_engine::config::ShellConfig;
/// use ironflow_engine::error::EngineError;
///
/// # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
/// let files = ctx.shell("list", ShellConfig::new("ls -la")).await?;
/// println!("stdout: {}", files.output["stdout"]);
/// # Ok(())
/// # }
/// ```
pub async fn shell(
&mut self,
name: &str,
config: ShellConfig,
) -> Result<StepOutput, EngineError> {
self.execute_step(name, StepKind::Shell, StepConfig::Shell(config))
.await
}
/// Execute an HTTP step.
///
/// # Errors
///
/// Returns [`EngineError`] if the request fails or the store errors.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::context::WorkflowContext;
/// use ironflow_engine::config::HttpConfig;
/// use ironflow_engine::error::EngineError;
///
/// # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
/// let resp = ctx.http("health", HttpConfig::get("https://api.example.com/health")).await?;
/// println!("status: {}", resp.output["status"]);
/// # Ok(())
/// # }
/// ```
pub async fn http(
&mut self,
name: &str,
config: HttpConfig,
) -> Result<StepOutput, EngineError> {
self.execute_step(name, StepKind::Http, StepConfig::Http(config))
.await
}
/// Execute an agent step.
///
/// # Errors
///
/// Returns [`EngineError`] if the agent invocation fails or the store errors.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::context::WorkflowContext;
/// use ironflow_engine::config::AgentStepConfig;
/// use ironflow_engine::error::EngineError;
///
/// # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
/// let review = ctx.agent("review", AgentStepConfig::new("Review the code")).await?;
/// println!("review: {}", review.output);
/// # Ok(())
/// # }
/// ```
pub async fn agent(
&mut self,
name: &str,
config: impl Into<AgentStepConfig>,
) -> Result<StepOutput, EngineError> {
self.execute_step(name, StepKind::Agent, StepConfig::Agent(config.into()))
.await
}
/// Create a human approval gate.
///
/// On first execution, records an approval step and returns
/// [`EngineError::ApprovalRequired`] to suspend the run. The engine
/// transitions the run to `AwaitingApproval`.
///
/// On resume (after a human approved via the API), the approval step
/// is replayed: it is marked as `Completed` and execution continues
/// past it. Multiple approval gates in the same handler work -- each
/// one pauses and resumes independently.
///
/// # Errors
///
/// Returns [`EngineError::ApprovalRequired`] to pause the run on
/// first execution. Returns other [`EngineError`] variants on store
/// failures.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::context::WorkflowContext;
/// use ironflow_engine::config::ApprovalConfig;
/// use ironflow_engine::error::EngineError;
///
/// # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
/// ctx.approval("deploy-gate", ApprovalConfig::new("Approve deployment?")).await?;
/// // Execution continues here after approval
/// # Ok(())
/// # }
/// ```
pub async fn approval(
&mut self,
name: &str,
config: ApprovalConfig,
) -> Result<(), EngineError> {
let position = self.position;
self.position += 1;
// Replay: if this approval step exists from a prior execution,
// the run was approved -- mark it completed (if not already) and continue.
if let Some(existing) = self.replay_steps.get(&position)
&& existing.kind == StepKind::Approval
{
if existing.status.state == StepStatus::AwaitingApproval {
self.store
.update_step(
existing.id,
StepUpdate {
status: Some(StepStatus::Completed),
completed_at: Some(Utc::now()),
..StepUpdate::default()
},
)
.await?;
}
self.last_step_ids = vec![existing.id];
info!(
run_id = %self.run_id,
step = %name,
position,
"approval step replayed (approved)"
);
return Ok(());
}
// Carried over: a human already approved this gate in an earlier
// attempt. Record a fresh step in the current attempt so that each
// attempt keeps a complete, self-contained DAG, and continue.
if let Some(&granted_in) = self.granted_approvals.get(&position) {
let step = self
.store
.create_step(NewStep {
run_id: self.run_id,
name: name.to_string(),
kind: StepKind::Approval,
position,
input: Some(serde_json::to_value(&config)?),
})
.await?;
let now = Utc::now();
self.start_step(step.id, now).await?;
self.store
.update_step(
step.id,
StepUpdate {
status: Some(StepStatus::Completed),
output: Some(json!({"approved_in_attempt": granted_in})),
completed_at: Some(now),
..StepUpdate::default()
},
)
.await?;
self.last_step_ids = vec![step.id];
info!(
run_id = %self.run_id,
step = %name,
position,
granted_in_attempt = granted_in,
attempt = self.attempt,
"approval carried over from a previous attempt"
);
return Ok(());
}
// First execution: create the approval step and suspend.
let step = self
.store
.create_step(NewStep {
run_id: self.run_id,
name: name.to_string(),
kind: StepKind::Approval,
position,
input: Some(serde_json::to_value(&config)?),
})
.await?;
self.start_step(step.id, Utc::now()).await?;
// Transition the step to AwaitingApproval so it reflects
// the suspended state on the dashboard.
self.store
.update_step(
step.id,
StepUpdate {
status: Some(StepStatus::AwaitingApproval),
..StepUpdate::default()
},
)
.await?;
self.last_step_ids = vec![step.id];
Err(EngineError::ApprovalRequired {
run_id: self.run_id,
step_id: step.id,
message: config.message().to_string(),
})
}
/// Record a step as explicitly skipped.
///
/// Use this inside an `if`/`else` branch when a step should not execute
/// but must still appear in the DAG and timeline with its reason.
///
/// The step is created directly in [`StepStatus::Skipped`] state and the
/// reason is stored in the output as `{"reason": "..."}`.
///
/// # Errors
///
/// Returns [`EngineError`] if the store fails.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::context::WorkflowContext;
/// use ironflow_engine::error::EngineError;
///
/// # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
/// let tests_passed = false;
/// if tests_passed {
/// // ctx.shell("deploy", ...).await?;
/// } else {
/// ctx.skip("deploy", "tests failed").await?;
/// }
/// # Ok(())
/// # }
/// ```
pub async fn skip(&mut self, name: &str, reason: &str) -> Result<(), EngineError> {
let position = self.position;
self.position += 1;
let step = self
.store
.create_step(NewStep {
run_id: self.run_id,
name: name.to_string(),
kind: StepKind::Custom("skip".to_string()),
position,
input: None,
})
.await?;
if !self.last_step_ids.is_empty() {
let deps: Vec<NewStepDependency> = self
.last_step_ids
.iter()
.map(|&depends_on| NewStepDependency {
step_id: step.id,
depends_on,
})
.collect();
self.store.create_step_dependencies(deps).await?;
}
let now = Utc::now();
self.store
.update_step(
step.id,
StepUpdate {
status: Some(StepStatus::Skipped),
output: Some(serde_json::json!({"reason": reason})),
completed_at: Some(now),
..StepUpdate::default()
},
)
.await?;
self.last_step_ids = vec![step.id];
info!(
run_id = %self.run_id,
step = %name,
reason,
"step skipped"
);
Ok(())
}
/// Execute a custom operation step.
///
/// Runs a user-defined [`Operation`] with full step lifecycle management:
/// creates the step record, transitions to Running, executes the operation,
/// persists the output and duration, and marks the step Completed or Failed.
///
/// The operation's [`kind()`](Operation::kind) is stored as
/// [`StepKind::Custom`].
///
/// # Errors
///
/// Returns [`EngineError`] if the operation fails or the store errors.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::context::WorkflowContext;
/// use ironflow_engine::operation::Operation;
/// use ironflow_engine::error::EngineError;
/// use serde_json::{Value, json};
/// use std::pin::Pin;
/// use std::future::Future;
///
/// struct MyOp;
/// impl Operation for MyOp {
/// fn kind(&self) -> &str { "my-service" }
/// fn execute(&self) -> Pin<Box<dyn Future<Output = Result<Value, EngineError>> + Send + '_>> {
/// Box::pin(async { Ok(json!({"ok": true})) })
/// }
/// }
///
/// # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
/// let result = ctx.operation("call-service", &MyOp).await?;
/// println!("output: {}", result.output);
/// # Ok(())
/// # }
/// ```
pub async fn operation(
&mut self,
name: &str,
op: &dyn Operation,
) -> Result<StepOutput, EngineError> {
let kind = StepKind::Custom(op.kind().to_string());
let position = self.position;
self.position += 1;
let step = self
.store
.create_step(NewStep {
run_id: self.run_id,
name: name.to_string(),
kind,
position,
input: op.input(),
})
.await?;
self.start_step(step.id, Utc::now()).await?;
let start = Instant::now();
match op.execute().await {
Ok(output_value) => {
let duration_ms = start.elapsed().as_millis() as u64;
self.total_duration_ms += duration_ms;
let completed_at = Utc::now();
self.store
.update_step(
step.id,
StepUpdate {
status: Some(StepStatus::Completed),
output: Some(output_value.clone()),
duration_ms: Some(duration_ms),
cost_usd: Some(Decimal::ZERO),
completed_at: Some(completed_at),
..StepUpdate::default()
},
)
.await?;
info!(
run_id = %self.run_id,
step = %name,
kind = op.kind(),
duration_ms,
"operation step completed"
);
self.last_step_ids = vec![step.id];
Ok(StepOutput {
output: output_value,
duration_ms,
cost_usd: Decimal::ZERO,
input_tokens: None,
output_tokens: None,
model: None,
debug_messages: None,
})
}
Err(err) => {
let completed_at = Utc::now();
if let Err(store_err) = self
.store
.update_step(
step.id,
StepUpdate {
status: Some(StepStatus::Failed),
error: Some(err.to_string()),
completed_at: Some(completed_at),
..StepUpdate::default()
},
)
.await
{
error!(step_id = %step.id, error = %store_err, "failed to persist step failure");
}
Err(err)
}
}
}
/// Execute a sub-workflow step.
///
/// Creates a child run for the named workflow handler, executes it with
/// its own steps and lifecycle, and returns a [`StepOutput`] containing
/// the child run ID and aggregated metrics.
///
/// Requires the context to be created with
/// `with_handler_resolver`.
///
/// # Errors
///
/// Returns [`EngineError::InvalidWorkflow`] if no handler is registered
/// with the given name, or if no handler resolver is available.
///
/// # Examples
///
/// ```no_run
/// use ironflow_engine::context::WorkflowContext;
/// use ironflow_engine::error::EngineError;
/// use serde_json::json;
///
/// # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
/// // let result = ctx.workflow(&MySubWorkflow, json!({})).await?;
/// # Ok(())
/// # }
/// ```
pub async fn workflow(
&mut self,
handler: &dyn WorkflowHandler,
payload: Value,
) -> Result<StepOutput, EngineError> {
let config = WorkflowStepConfig::new(handler.name(), payload);
let position = self.position;
self.position += 1;
let step = self
.store
.create_step(NewStep {
run_id: self.run_id,
name: config.workflow_name.clone(),
kind: StepKind::Workflow,
position,
input: Some(serde_json::to_value(&config)?),
})
.await?;
self.start_step(step.id, Utc::now()).await?;
match self.execute_child_workflow(&config).await {
Ok(output) => {
self.total_cost_usd += output.cost_usd;
self.total_duration_ms += output.duration_ms;
let completed_at = Utc::now();
self.store
.update_step(
step.id,
StepUpdate {
status: Some(StepStatus::Completed),
output: Some(output.output.clone()),
duration_ms: Some(output.duration_ms),
cost_usd: Some(output.cost_usd),
completed_at: Some(completed_at),
..StepUpdate::default()
},
)
.await?;
info!(
run_id = %self.run_id,
child_workflow = %config.workflow_name,
duration_ms = output.duration_ms,
"workflow step completed"
);
self.last_step_ids = vec![step.id];
Ok(output)
}
Err(err) => {
let completed_at = Utc::now();
if let Err(store_err) = self
.store
.update_step(
step.id,
StepUpdate {
status: Some(StepStatus::Failed),
error: Some(err.to_string()),
completed_at: Some(completed_at),
..StepUpdate::default()
},
)
.await
{
error!(step_id = %step.id, error = %store_err, "failed to persist step failure");
}
Err(err)
}
}
}
/// Execute a child workflow and return aggregated output.
async fn execute_child_workflow(
&self,
config: &WorkflowStepConfig,
) -> Result<StepOutput, EngineError> {
let resolver = self.handler_resolver.as_ref().ok_or_else(|| {
EngineError::InvalidWorkflow(
"sub-workflow requires a handler resolver (use Engine to execute)".to_string(),
)
})?;
let handler = resolver(&config.workflow_name).ok_or_else(|| {
EngineError::InvalidWorkflow(format!("no handler registered: {}", config.workflow_name))
})?;
// A child run inherits both the parent labels and the parent author:
// whoever triggered the parent workflow is accountable for its children.
let parent = self.store.get_run(self.run_id).await?;
let (parent_labels, parent_author) =
parent.map(|r| (r.labels, r.created_by)).unwrap_or_default();
let child_run = self
.store
.create_run(NewRun {
workflow_name: config.workflow_name.clone(),
trigger: TriggerKind::Workflow,
payload: config.payload.clone(),
max_retries: 0,
handler_version: None,
labels: parent_labels,
scheduled_at: None,
created_by: parent_author,
idempotency_key: None,
// The child shares the parent's cap; it does not get its own budget.
max_cost_usd: self.max_cost_usd,
})
.await?
.into_run();
let child_run_id = child_run.id;
info!(
parent_run_id = %self.run_id,
child_run_id = %child_run_id,
workflow = %config.workflow_name,
"child run created"
);
self.store
.update_run_status(child_run_id, RunStatus::Running)
.await?;
let run_start = Instant::now();
let mut child_ctx = WorkflowContext {
run_id: child_run_id,
store: self.store.clone(),
provider: self.provider.clone(),
handler_resolver: self.handler_resolver.clone(),
position: 0,
last_step_ids: Vec::new(),
total_cost_usd: Decimal::ZERO,
total_duration_ms: 0,
max_cost_usd: self.max_cost_usd,
// Everything the parent chain already spent counts against the
// shared cap, so the child cannot restart the budget from zero.
inherited_cost_usd: self.charged_cost_usd(),
replay_steps: HashMap::new(),
granted_approvals: HashMap::new(),
// A child run is created fresh here; it is never itself retried.
attempt: 1,
carried_duration_ms: 0,
log_sender: self.log_sender.clone(),
// A child shares the storage backend but not the parent's artifacts:
// input lookups are scoped to the child's own run.
artifact_sink: self.artifact_sink.clone(),
};
let result = handler.execute(&mut child_ctx).await;
let total_duration = run_start.elapsed().as_millis() as u64;
let completed_at = Utc::now();
match result {
Ok(()) => {
self.store
.update_run(
child_run_id,
RunUpdate {
status: Some(RunStatus::Completed),
cost_usd: Some(child_ctx.total_cost_usd),
duration_ms: Some(total_duration),
completed_at: Some(completed_at),
..RunUpdate::default()
},
)
.await?;
Ok(StepOutput {
output: serde_json::json!({
"run_id": child_run_id,
"workflow_name": config.workflow_name,
"status": RunStatus::Completed,
"cost_usd": child_ctx.total_cost_usd,
"duration_ms": total_duration,
}),
duration_ms: total_duration,
cost_usd: child_ctx.total_cost_usd,
input_tokens: None,
output_tokens: None,
model: None,
debug_messages: None,
})
}
Err(err) => {
if let Err(store_err) = self
.store
.update_run(
child_run_id,
RunUpdate {
status: Some(RunStatus::Failed),
error: Some(err.to_string()),
cost_usd: Some(child_ctx.total_cost_usd),
duration_ms: Some(total_duration),
completed_at: Some(completed_at),
..RunUpdate::default()
},
)
.await
{
error!(
child_run_id = %child_run_id,
store_error = %store_err,
"failed to persist child run failure"
);
}
Err(err)
}
}
}
/// Try to replay a completed step from a previous execution.
///
/// Returns `Some(StepOutput)` if a completed step exists at the given
/// position, `None` otherwise.
fn try_replay_step(&mut self, position: u32) -> Option<StepOutput> {
let step = self.replay_steps.get(&position)?;
if step.status.state != StepStatus::Completed {
return None;
}
let output = StepOutput {
output: step.output.clone().unwrap_or(Value::Null),
duration_ms: step.duration_ms,
cost_usd: step.cost_usd,
input_tokens: step.input_tokens,
output_tokens: step.output_tokens,
model: None,
debug_messages: None,
};
self.total_cost_usd += output.cost_usd;
self.total_duration_ms += output.duration_ms;
self.last_step_ids = vec![step.id];
info!(
run_id = %self.run_id,
step = %step.name,
position,
"step replayed from previous execution"
);
Some(output)
}
/// Internal: execute a step with full persistence lifecycle.
async fn execute_step(
&mut self,
name: &str,
kind: StepKind,
config: StepConfig,
) -> Result<StepOutput, EngineError> {
let position = self.position;
self.position += 1;
// Replay: if this step already completed in a prior execution, return cached output.
if let Some(output) = self.try_replay_step(position) {
return Ok(output);
}
// Cost cap: refuse before creating the step record, so a run that hits
// its cap never launches the work it cannot afford.
if let StepConfig::Agent(ref agent_config) = config {
self.check_run_budget(step_budget_usd(agent_config.max_budget_usd))?;
}
// Create step record in Pending.
let step = self
.store
.create_step(NewStep {
run_id: self.run_id,
name: name.to_string(),
kind,
position,
input: Some(serde_json::to_value(&config)?),
})
.await?;
self.start_step(step.id, Utc::now()).await?;
// Inputs must exist before the command runs. A failure here fails the
// step: the command would otherwise run against missing files.
if let Err(err) = self.prepare_step_inputs(&config, position).await {
self.fail_step(step.id, &err).await;
return Err(err);
}
let step_log_sender = self
.log_sender
.as_ref()
.map(|s| StepLogSender::new(s.clone(), self.run_id, step.id, name.to_string()));
let execution = execute_step_config(&config, &self.provider, step_log_sender).await;
if let Err(err) = self
.store_step_outputs(&config, step.id, name, execution.is_ok())
.await
{
self.fail_step(step.id, &err).await;
return Err(err);
}
match execution {
Ok(output) => {
self.total_cost_usd += output.cost_usd;
self.total_duration_ms += output.duration_ms;
let debug_messages_json = output.debug_messages_json();
let completed_at = Utc::now();
self.store
.update_step(
step.id,
StepUpdate {
status: Some(StepStatus::Completed),
output: Some(output.output.clone()),
duration_ms: Some(output.duration_ms),
cost_usd: Some(output.cost_usd),
input_tokens: output.input_tokens,
output_tokens: output.output_tokens,
completed_at: Some(completed_at),
debug_messages: debug_messages_json,
..StepUpdate::default()
},
)
.await?;
info!(
run_id = %self.run_id,
step = %name,
duration_ms = output.duration_ms,
"step completed"
);
self.last_step_ids = vec![step.id];
Ok(output)
}
Err(err) => {
let completed_at = Utc::now();
let debug_messages_json = extract_debug_messages_from_error(&err);
let partial = extract_partial_usage_from_error(&err);
let raw_response_output = extract_raw_response_from_error(&err);
if let Some(ref usage) = partial {
if let Some(cost) = usage.cost_usd {
self.total_cost_usd += cost;
}
if let Some(dur) = usage.duration_ms {
self.total_duration_ms += dur;
}
}
if let Err(store_err) = self
.store
.update_step(
step.id,
StepUpdate {
status: Some(StepStatus::Failed),
error: Some(err.to_string()),
output: raw_response_output,
completed_at: Some(completed_at),
debug_messages: debug_messages_json,
duration_ms: partial.as_ref().and_then(|p| p.duration_ms),
cost_usd: partial.as_ref().and_then(|p| p.cost_usd),
input_tokens: partial.as_ref().and_then(|p| p.input_tokens),
output_tokens: partial.as_ref().and_then(|p| p.output_tokens),
..StepUpdate::default()
},
)
.await
{
tracing::error!(step_id = %step.id, error = %store_err, "failed to persist step failure");
}
Err(err)
}
}
}
/// Record dependency edges and transition a step to Running.
///
/// Records edges from `step_id` to all `last_step_ids`, then
/// transitions the step to `Running` with the given timestamp.
async fn start_step(&self, step_id: Uuid, now: DateTime<Utc>) -> Result<(), EngineError> {
if !self.last_step_ids.is_empty() {
let deps: Vec<NewStepDependency> = self
.last_step_ids
.iter()
.map(|&depends_on| NewStepDependency {
step_id,
depends_on,
})
.collect();
self.store.create_step_dependencies(deps).await?;
}
self.store
.update_step(
step_id,
StepUpdate {
status: Some(StepStatus::Running),
started_at: Some(now),
..StepUpdate::default()
},
)
.await?;
Ok(())
}
/// Mark a step as failed, best-effort.
///
/// Used on paths that fail around the operation itself (artifact inputs and
/// outputs), where the step record is already `Running` and the caller is
/// about to propagate `err`. A store failure here is logged, never returned:
/// it must not replace the error the caller is reporting.
async fn fail_step(&self, step_id: Uuid, err: &EngineError) {
if let Err(store_err) = self
.store
.update_step(
step_id,
StepUpdate {
status: Some(StepStatus::Failed),
error: Some(err.to_string()),
completed_at: Some(Utc::now()),
..StepUpdate::default()
},
)
.await
{
error!(
step_id = %step_id,
error = %store_err,
"failed to persist step failure"
);
}
}
/// Access the store directly (advanced usage).
pub fn store(&self) -> &Arc<dyn Store> {
&self.store
}
/// Access the payload that triggered this run.
///
/// Fetches the run from the store and returns its payload.
///
/// # Errors
///
/// Returns [`EngineError::Store`] if the run is not found.
pub async fn payload(&self) -> Result<Value, EngineError> {
let run = self
.store
.get_run(self.run_id)
.await?
.ok_or(EngineError::Store(
ironflow_store::error::StoreError::RunNotFound(self.run_id),
))?;
Ok(run.payload)
}
}
impl fmt::Debug for WorkflowContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WorkflowContext")
.field("run_id", &self.run_id)
.field("position", &self.position)
.field("total_cost_usd", &self.total_cost_usd)
.field("inherited_cost_usd", &self.inherited_cost_usd)
.field("max_cost_usd", &self.max_cost_usd)
.finish_non_exhaustive()
}
}
/// Extract debug messages from an engine error, if it wraps a schema validation
/// failure that carries a verbose conversation trace.
fn extract_debug_messages_from_error(err: &EngineError) -> Option<Value> {
if let EngineError::Operation(OperationError::Agent(AgentError::SchemaValidation {
debug_messages,
..
})) = err
&& !debug_messages.is_empty()
{
return serde_json::to_value(debug_messages).ok();
}
None
}
/// Partial usage with `Decimal` cost, converted from the `f64` in [`PartialUsage`].
///
/// Exists only because `ironflow-store` uses [`Decimal`] for monetary values
/// while `ironflow-core` uses `f64` (the CLI's native type). The conversion
/// happens here, at the engine/store boundary.
struct StepPartialUsage {
cost_usd: Option<Decimal>,
duration_ms: Option<u64>,
input_tokens: Option<u64>,
output_tokens: Option<u64>,
}
/// Extract the raw response text from a schema validation error.
///
/// When the agent produced text but structured output extraction failed,
/// this returns the truncated raw text so it can be persisted as the
/// step output for dashboard visibility.
fn extract_raw_response_from_error(err: &EngineError) -> Option<Value> {
if let EngineError::Operation(OperationError::Agent(AgentError::SchemaValidation {
raw_response: Some(text),
..
})) = err
{
return Some(Value::String(text.clone()));
}
None
}
fn extract_partial_usage_from_error(err: &EngineError) -> Option<StepPartialUsage> {
if let EngineError::Operation(OperationError::Agent(AgentError::SchemaValidation {
partial_usage,
..
})) = err
&& (partial_usage.cost_usd.is_some() || partial_usage.duration_ms.is_some())
{
return Some(StepPartialUsage {
cost_usd: partial_usage
.cost_usd
.and_then(|c| Decimal::try_from(c).ok()),
duration_ms: partial_usage.duration_ms,
input_tokens: partial_usage.input_tokens,
output_tokens: partial_usage.output_tokens,
});
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use ironflow_core::providers::claude::ClaudeCodeProvider;
use ironflow_core::providers::record_replay::RecordReplayProvider;
use ironflow_store::memory::InMemoryStore;
use ironflow_store::models::{Run, RunActor, RunFilter};
use ironflow_store::store::RunStore;
use serde_json::json;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use uuid::Uuid;
/// Helper to create a test provider with fixtures
fn create_test_provider() -> Arc<dyn ironflow_core::provider::AgentProvider> {
let inner = ClaudeCodeProvider::new();
Arc::new(RecordReplayProvider::replay(
inner,
"/tmp/ironflow-fixtures",
))
}
/// Helper to create a test context
fn create_test_context() -> WorkflowContext {
let store = Arc::new(InMemoryStore::new());
let provider = create_test_provider();
let run_id = Uuid::now_v7();
WorkflowContext::new(run_id, store, provider)
}
#[test]
fn context_new_initializes_correctly() {
let ctx = create_test_context();
assert_eq!(ctx.position, 0);
assert_eq!(ctx.total_cost_usd, Decimal::ZERO);
assert_eq!(ctx.total_duration_ms, 0);
assert!(ctx.last_step_ids.is_empty());
assert!(ctx.replay_steps.is_empty());
assert!(ctx.log_sender.is_none());
}
#[test]
fn context_run_id_returns_correct_id() {
let run_id = Uuid::now_v7();
let store = Arc::new(InMemoryStore::new());
let provider = create_test_provider();
let ctx = WorkflowContext::new(run_id, store, provider);
assert_eq!(ctx.run_id(), run_id);
}
#[test]
fn context_total_cost_usd_initially_zero() {
let ctx = create_test_context();
assert_eq!(ctx.total_cost_usd(), Decimal::ZERO);
}
#[test]
fn context_total_duration_ms_initially_zero() {
let ctx = create_test_context();
assert_eq!(ctx.total_duration_ms(), 0);
}
#[test]
fn context_with_handler_resolver_creates_context_with_resolver() {
let store = Arc::new(InMemoryStore::new());
let provider = create_test_provider();
let run_id = Uuid::now_v7();
let called = Arc::new(AtomicBool::new(false));
let called_clone = called.clone();
let resolver: HandlerResolver = Arc::new(move |_name: &str| {
called_clone.store(true, Ordering::SeqCst);
None
});
let ctx = WorkflowContext::with_handler_resolver(run_id, store, provider, resolver);
assert_eq!(ctx.run_id(), run_id);
assert!(ctx.handler_resolver.is_some());
}
#[tokio::test]
async fn context_set_log_sender_attaches_sender() {
let mut ctx = create_test_context();
let (sender, _receiver) = crate::log_sender::channel();
ctx.set_log_sender(sender);
assert!(ctx.log_sender.is_some());
}
#[tokio::test]
async fn context_skip_creates_skipped_step() {
let store = Arc::new(InMemoryStore::new());
let provider = create_test_provider();
// Create the run first using RunStore trait
store
.create_run(NewRun {
created_by: None,
workflow_name: "test".to_string(),
trigger: TriggerKind::Manual,
payload: json!({}),
max_retries: 0,
handler_version: None,
labels: Default::default(),
scheduled_at: None,
idempotency_key: None,
max_cost_usd: None,
})
.await
.expect("failed to create run")
.into_run();
// Get the created run to extract its ID
let runs = store
.list_runs(RunFilter::default(), 1, 10)
.await
.expect("failed to list runs");
let created_run_id = runs.items[0].id;
let mut ctx = WorkflowContext::new(created_run_id, store.clone(), provider);
let initial_position = ctx.position;
ctx.skip("skip-step", "condition not met")
.await
.expect("skip failed");
assert_eq!(ctx.position, initial_position + 1);
assert!(!ctx.last_step_ids.is_empty());
// Verify the step was recorded with Skipped status
let steps = store
.list_steps(created_run_id)
.await
.expect("failed to list steps");
assert_eq!(steps.len(), 1);
assert_eq!(steps[0].status.state, StepStatus::Skipped);
}
/// Sub-workflow handler that records no steps, so the child run reaches a
/// terminal state without touching the filesystem or the network.
struct NoopSubWorkflow;
impl WorkflowHandler for NoopSubWorkflow {
fn name(&self) -> &str {
"noop-sub"
}
fn execute<'a>(
&'a self,
_ctx: &'a mut WorkflowContext,
) -> crate::handler::HandlerFuture<'a> {
Box::pin(async move { Ok(()) })
}
}
/// Run a parent workflow authored by `created_by` and return the child run
/// created by its sub-workflow step.
async fn child_run_of_parent_authored_by(created_by: Option<RunActor>) -> Run {
let store = Arc::new(InMemoryStore::new());
let provider = create_test_provider();
let parent = store
.create_run(NewRun {
workflow_name: "parent".to_string(),
trigger: TriggerKind::Api,
payload: json!({}),
max_retries: 0,
handler_version: None,
labels: Default::default(),
scheduled_at: None,
created_by,
idempotency_key: None,
max_cost_usd: None,
})
.await
.expect("failed to create parent run")
.into_run();
let resolver: HandlerResolver = Arc::new(|name: &str| match name {
"noop-sub" => Some(Arc::new(NoopSubWorkflow) as Arc<dyn WorkflowHandler>),
_ => None,
});
let mut ctx =
WorkflowContext::with_handler_resolver(parent.id, store.clone(), provider, resolver);
ctx.workflow(&NoopSubWorkflow, json!({}))
.await
.expect("sub-workflow failed");
let runs = store
.list_runs(RunFilter::default(), 1, 10)
.await
.expect("failed to list runs");
runs.items
.into_iter()
.find(|r| r.workflow_name == "noop-sub")
.expect("child run was created")
}
#[tokio::test]
async fn child_run_inherits_the_parent_author() {
let user_id = Uuid::now_v7();
let child = child_run_of_parent_authored_by(Some(RunActor::User { user_id })).await;
assert_eq!(child.created_by, Some(RunActor::User { user_id }));
}
#[tokio::test]
async fn child_run_of_an_unattributed_parent_has_no_author() {
let child = child_run_of_parent_authored_by(None).await;
assert!(child.created_by.is_none());
}
#[tokio::test]
async fn context_parallel_empty_steps_returns_empty_vec() {
let mut ctx = create_test_context();
let results = ctx
.parallel(vec![], true)
.await
.expect("parallel should not fail on empty input");
assert!(results.is_empty());
}
#[tokio::test]
async fn context_approval_first_execution_returns_error() {
let store = Arc::new(InMemoryStore::new());
let provider = create_test_provider();
// Create the run first
store
.create_run(NewRun {
created_by: None,
workflow_name: "test".to_string(),
trigger: TriggerKind::Manual,
payload: json!({}),
max_retries: 0,
handler_version: None,
labels: Default::default(),
scheduled_at: None,
idempotency_key: None,
max_cost_usd: None,
})
.await
.expect("failed to create run")
.into_run();
// Get the created run to extract its ID
let runs = store
.list_runs(RunFilter::default(), 1, 10)
.await
.expect("failed to list runs");
let created_run_id = runs.items[0].id;
let mut ctx = WorkflowContext::new(created_run_id, store.clone(), provider);
let result = ctx
.approval(
"approve-step",
crate::config::ApprovalConfig::new("Continue?"),
)
.await;
// First execution should return ApprovalRequired error
assert!(matches!(result, Err(EngineError::ApprovalRequired { .. })));
// Verify position incremented
assert_eq!(ctx.position, 1);
// Verify step was created with AwaitingApproval status
let steps = store
.list_steps(created_run_id)
.await
.expect("failed to list steps");
assert_eq!(steps.len(), 1);
assert_eq!(steps[0].status.state, StepStatus::AwaitingApproval);
}
#[tokio::test]
async fn context_approval_replay_returns_ok() {
let store = Arc::new(InMemoryStore::new());
let provider = create_test_provider();
// Create the run first
store
.create_run(NewRun {
created_by: None,
workflow_name: "test".to_string(),
trigger: TriggerKind::Manual,
payload: json!({}),
max_retries: 0,
handler_version: None,
labels: Default::default(),
scheduled_at: None,
idempotency_key: None,
max_cost_usd: None,
})
.await
.expect("failed to create run")
.into_run();
// Get the created run to extract its ID
let runs = store
.list_runs(RunFilter::default(), 1, 10)
.await
.expect("failed to list runs");
let created_run_id = runs.items[0].id;
// Create an approval step that's already in AwaitingApproval state
let step = store
.create_step(NewStep {
run_id: created_run_id,
name: "approval".to_string(),
kind: StepKind::Approval,
position: 0,
input: None,
})
.await
.expect("failed to create step");
// Transition through proper states: Pending -> Running -> AwaitingApproval
store
.update_step(
step.id,
StepUpdate {
status: Some(StepStatus::Running),
started_at: Some(Utc::now()),
..StepUpdate::default()
},
)
.await
.expect("failed to update step to Running");
store
.update_step(
step.id,
StepUpdate {
status: Some(StepStatus::AwaitingApproval),
..StepUpdate::default()
},
)
.await
.expect("failed to update step to AwaitingApproval");
// Create context and load replay steps
let mut ctx = WorkflowContext::new(created_run_id, store.clone(), provider);
ctx.load_replay_steps()
.await
.expect("failed to load replay steps");
// Now approval should succeed (replay)
let result = ctx
.approval("approval", crate::config::ApprovalConfig::new("Continue?"))
.await;
assert!(result.is_ok());
// Verify the step was marked Completed
let steps = store
.list_steps(created_run_id)
.await
.expect("failed to list steps");
assert_eq!(steps.len(), 1);
assert_eq!(steps[0].status.state, StepStatus::Completed);
}
#[tokio::test]
async fn context_load_replay_steps_loads_completed_steps() {
let store = Arc::new(InMemoryStore::new());
let provider = create_test_provider();
// Create the run first
store
.create_run(NewRun {
created_by: None,
workflow_name: "test".to_string(),
trigger: TriggerKind::Manual,
payload: json!({}),
max_retries: 0,
handler_version: None,
labels: Default::default(),
scheduled_at: None,
idempotency_key: None,
max_cost_usd: None,
})
.await
.expect("failed to create run")
.into_run();
// Get the created run to extract its ID
let runs = store
.list_runs(RunFilter::default(), 1, 10)
.await
.expect("failed to list runs");
let created_run_id = runs.items[0].id;
// Create multiple steps with different statuses
let completed_step = store
.create_step(NewStep {
run_id: created_run_id,
name: "completed".to_string(),
kind: StepKind::Shell,
position: 0,
input: None,
})
.await
.expect("failed to create step");
// Transition to Running then Completed
store
.update_step(
completed_step.id,
StepUpdate {
status: Some(StepStatus::Running),
started_at: Some(Utc::now()),
..StepUpdate::default()
},
)
.await
.expect("failed to update step to Running");
store
.update_step(
completed_step.id,
StepUpdate {
status: Some(StepStatus::Completed),
completed_at: Some(Utc::now()),
..StepUpdate::default()
},
)
.await
.expect("failed to update step to Completed");
let _pending_step = store
.create_step(NewStep {
run_id: created_run_id,
name: "pending".to_string(),
kind: StepKind::Shell,
position: 1,
input: None,
})
.await
.expect("failed to create step");
// Load replay steps
let mut ctx = WorkflowContext::new(created_run_id, store, provider);
ctx.load_replay_steps()
.await
.expect("failed to load replay steps");
// Only completed step should be in replay_steps
assert_eq!(ctx.replay_steps.len(), 1);
assert!(ctx.replay_steps.contains_key(&0));
assert!(!ctx.replay_steps.contains_key(&1));
}
#[tokio::test]
async fn context_payload_returns_run_payload() {
let store = Arc::new(InMemoryStore::new());
let provider = create_test_provider();
let test_payload = json!({"key": "value", "number": 42});
// Create the run first
store
.create_run(NewRun {
created_by: None,
workflow_name: "test".to_string(),
trigger: TriggerKind::Manual,
payload: test_payload.clone(),
max_retries: 0,
handler_version: None,
labels: Default::default(),
scheduled_at: None,
idempotency_key: None,
max_cost_usd: None,
})
.await
.expect("failed to create run")
.into_run();
// Get the created run to extract its ID
let runs = store
.list_runs(RunFilter::default(), 1, 10)
.await
.expect("failed to list runs");
let created_run_id = runs.items[0].id;
let ctx = WorkflowContext::new(created_run_id, store, provider);
let payload = ctx.payload().await.expect("failed to get payload");
assert_eq!(payload, test_payload);
}
#[tokio::test]
async fn context_payload_returns_error_for_nonexistent_run() {
let store = Arc::new(InMemoryStore::new());
let provider = create_test_provider();
let run_id = Uuid::now_v7();
let ctx = WorkflowContext::new(run_id, store, provider);
let result = ctx.payload().await;
assert!(result.is_err());
}
#[tokio::test]
async fn context_store_returns_reference() {
let ctx = create_test_context();
let _store = ctx.store();
// store() returns a reference to the Arc<dyn Store>, which is always available
}
#[test]
fn context_debug_formatting() {
let ctx = create_test_context();
let debug_str = format!("{:?}", ctx);
assert!(debug_str.contains("WorkflowContext"));
assert!(debug_str.contains("run_id"));
}
#[tokio::test]
async fn context_last_step_ids_tracks_executed_steps() {
let store = Arc::new(InMemoryStore::new());
let provider = create_test_provider();
// Create the run first
store
.create_run(NewRun {
created_by: None,
workflow_name: "test".to_string(),
trigger: TriggerKind::Manual,
payload: json!({}),
max_retries: 0,
handler_version: None,
labels: Default::default(),
scheduled_at: None,
idempotency_key: None,
max_cost_usd: None,
})
.await
.expect("failed to create run")
.into_run();
// Get the created run to extract its ID
let runs = store
.list_runs(RunFilter::default(), 1, 10)
.await
.expect("failed to list runs");
let created_run_id = runs.items[0].id;
let mut ctx = WorkflowContext::new(created_run_id, store, provider);
assert!(ctx.last_step_ids.is_empty());
ctx.skip("step1", "reason").await.expect("skip failed");
assert_eq!(ctx.last_step_ids.len(), 1);
ctx.skip("step2", "reason").await.expect("skip failed");
// last_step_ids should now contain only step2's ID
assert_eq!(ctx.last_step_ids.len(), 1);
}
}