sayiir-runtime 0.3.1

Execution runtime, checkpointing runner and distributed workers for Sayiir workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
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
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
// Lint allows are on the `mod tests` declaration in mod.rs.

use super::*;
use crate::error::RuntimeError;
use crate::serialization::JsonCodec;
use bytes::Bytes;
use sayiir_core::branch_results::NamedBranchResults;
use sayiir_core::error::{BoxError, WorkflowError};
use sayiir_core::snapshot::{ExecutionPosition, WorkflowSnapshot, WorkflowSnapshotState};
use sayiir_core::task::{RetryPolicy, to_core_task};
use sayiir_core::workflow::{WorkflowContinuation, WorkflowStatus};
use sayiir_persistence::{InMemoryBackend, SignalStore, SnapshotStore};
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

fn codec() -> Arc<JsonCodec> {
    Arc::new(JsonCodec)
}

fn encode_u32(val: u32) -> Bytes {
    Bytes::from(serde_json::to_vec(&val).unwrap())
}

fn decode_u32(bytes: &Bytes) -> u32 {
    serde_json::from_slice(bytes).unwrap()
}

/// Build a `WorkflowContinuation::Task` with a real func.
fn task_node<F, Fut>(
    id: &str,
    f: F,
    next: Option<Box<WorkflowContinuation>>,
) -> WorkflowContinuation
where
    F: Fn(u32) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<u32, BoxError>> + Send + 'static,
{
    let c = codec();
    WorkflowContinuation::Task {
        id: id.to_string(),
        func: Some(to_core_task(id, f, c)),
        timeout: None,
        retry_policy: None,
        version: None,
        next,
    }
}

/// Build a `WorkflowContinuation::Task` with no func (for callback-based tests).
fn stub_node(id: &str, next: Option<Box<WorkflowContinuation>>) -> WorkflowContinuation {
    WorkflowContinuation::Task {
        id: id.to_string(),
        func: None,
        timeout: None,
        retry_policy: None,
        version: None,
        next,
    }
}

/// Build a task node with a retry policy (async with real func).
fn task_node_with_retry<F, Fut>(
    id: &str,
    f: F,
    retry_policy: RetryPolicy,
    next: Option<Box<WorkflowContinuation>>,
) -> WorkflowContinuation
where
    F: Fn(u32) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<u32, BoxError>> + Send + 'static,
{
    let c = codec();
    WorkflowContinuation::Task {
        id: id.to_string(),
        func: Some(to_core_task(id, f, c)),
        timeout: None,
        retry_policy: Some(retry_policy),
        version: None,
        next,
    }
}

/// Build a task node with both timeout and retry policy.
fn task_node_with_timeout_and_retry<F, Fut>(
    id: &str,
    f: F,
    timeout: std::time::Duration,
    retry_policy: RetryPolicy,
    next: Option<Box<WorkflowContinuation>>,
) -> WorkflowContinuation
where
    F: Fn(u32) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<u32, BoxError>> + Send + 'static,
{
    let c = codec();
    WorkflowContinuation::Task {
        id: id.to_string(),
        func: Some(to_core_task(id, f, c)),
        timeout: Some(timeout),
        retry_policy: Some(retry_policy),
        version: None,
        next,
    }
}

/// Build a stub node with a retry policy (callback-based tests).
fn stub_node_with_retry(
    id: &str,
    retry_policy: RetryPolicy,
    next: Option<Box<WorkflowContinuation>>,
) -> WorkflowContinuation {
    WorkflowContinuation::Task {
        id: id.to_string(),
        func: None,
        timeout: None,
        retry_policy: Some(retry_policy),
        version: None,
        next,
    }
}

/// Build a stub node with timeout + retry policy (callback-based tests).
fn stub_node_with_timeout_and_retry(
    id: &str,
    timeout: std::time::Duration,
    retry_policy: RetryPolicy,
    next: Option<Box<WorkflowContinuation>>,
) -> WorkflowContinuation {
    WorkflowContinuation::Task {
        id: id.to_string(),
        func: None,
        timeout: Some(timeout),
        retry_policy: Some(retry_policy),
        version: None,
        next,
    }
}

/// A fast retry policy for tests: minimal delays, configurable max retries.
fn fast_retry(max_retries: u32) -> RetryPolicy {
    RetryPolicy {
        max_retries,
        initial_delay: std::time::Duration::from_millis(1),
        backoff_multiplier: 1.0,
        max_delay: None,
    }
}

// ========================================================================
// serialize_branch_results
// ========================================================================

#[test]
fn test_serialize_branch_results_roundtrip() {
    let results = vec![
        ("branch_a".to_string(), Bytes::from(vec![1, 2, 3])),
        ("branch_b".to_string(), Bytes::from(vec![4, 5])),
    ];

    let serialized = serialize_branch_results(&results, &JsonCodec).unwrap();
    let deserialized: NamedBranchResults = serde_json::from_slice(&serialized).unwrap();
    let map = deserialized.into_map();

    assert_eq!(map.len(), 2);
    assert_eq!(map["branch_a"], Bytes::from(vec![1, 2, 3]));
    assert_eq!(map["branch_b"], Bytes::from(vec![4, 5]));
}

#[test]
fn test_serialize_branch_results_empty() {
    let results: Vec<(String, Bytes)> = vec![];
    let serialized = serialize_branch_results(&results, &JsonCodec).unwrap();
    let deserialized: NamedBranchResults = serde_json::from_slice(&serialized).unwrap();
    assert!(deserialized.is_empty());
}

#[test]
fn test_serialize_branch_results_single() {
    let results = vec![("only".to_string(), Bytes::from("data"))];
    let serialized = serialize_branch_results(&results, &JsonCodec).unwrap();
    let deserialized: NamedBranchResults = serde_json::from_slice(&serialized).unwrap();
    let map = deserialized.into_map();
    assert_eq!(map.len(), 1);
    assert_eq!(map["only"], Bytes::from("data"));
}

// ========================================================================
// execute_continuation_sync
// ========================================================================

#[test]
fn test_sync_single_task() {
    let input = encode_u32(5);
    let cont = stub_node("add_one", None);

    let callback = |_id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val = decode_u32(&input);
        Ok(encode_u32(val + 1))
    };

    let result = execute_continuation_sync(&cont, input, &callback, &JsonCodec).unwrap();
    assert_eq!(decode_u32(&result), 6);
}

#[test]
fn test_sync_chained_tasks() {
    let double = stub_node("double", None);
    let add_one = stub_node("add_one", Some(Box::new(double)));
    let input = encode_u32(10);

    let callback = |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val = decode_u32(&input);
        match id {
            "add_one" => Ok(encode_u32(val + 1)),
            "double" => Ok(encode_u32(val * 2)),
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&add_one, input, &callback, &JsonCodec).unwrap();
    // 10 + 1 = 11, 11 * 2 = 22
    assert_eq!(decode_u32(&result), 22);
}

#[test]
fn test_sync_fork_with_join() {
    let branch_a = Arc::new(stub_node("branch_a", None));
    let branch_b = Arc::new(stub_node("branch_b", None));
    let join_task = stub_node("join", None);

    let fork = WorkflowContinuation::Fork {
        id: "fork".into(),
        branches: vec![branch_a, branch_b].into_boxed_slice(),
        join: Some(Box::new(join_task)),
    };

    let input = encode_u32(10);

    let callback = |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val: u32 = serde_json::from_slice(&input).unwrap_or(0);
        match id {
            "branch_a" => Ok(encode_u32(val * 2)),
            "branch_b" => Ok(encode_u32(val + 5)),
            "join" => {
                let branches: NamedBranchResults = serde_json::from_slice(&input).unwrap();
                let map = branches.into_map();
                let a = decode_u32(&map["branch_a"]);
                let b = decode_u32(&map["branch_b"]);
                Ok(encode_u32(a + b))
            }
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&fork, input, &callback, &JsonCodec).unwrap();
    // branch_a: 10*2=20, branch_b: 10+5=15, join: 20+15=35
    assert_eq!(decode_u32(&result), 35);
}

#[test]
fn test_sync_fork_without_join() {
    let branch_a = Arc::new(stub_node("branch_a", None));
    let branch_b = Arc::new(stub_node("branch_b", None));

    let fork = WorkflowContinuation::Fork {
        id: "fork".into(),
        branches: vec![branch_a, branch_b].into_boxed_slice(),
        join: None,
    };

    let input = encode_u32(10);

    let callback = |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val = decode_u32(&input);
        match id {
            "branch_a" => Ok(encode_u32(val * 2)),
            "branch_b" => Ok(encode_u32(val + 5)),
            _ => Err("Unknown".into()),
        }
    };

    // Without join, returns last branch result
    let result = execute_continuation_sync(&fork, input, &callback, &JsonCodec).unwrap();
    assert_eq!(decode_u32(&result), 15); // branch_b: 10+5
}

#[test]
fn test_sync_task_failure_propagates() {
    let cont = stub_node("fail_task", None);
    let input = encode_u32(1);

    let callback =
        |_id: &str, _input: Bytes| -> Result<Bytes, BoxError> { Err("task exploded".into()) };

    let result = execute_continuation_sync(&cont, input, &callback, &JsonCodec);
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("task exploded"));
}

// ========================================================================
// execute_continuation_async
// ========================================================================

#[tokio::test]
async fn test_async_single_task() {
    let input = encode_u32(5);
    let cont = task_node("add_one", |i: u32| async move { Ok(i + 1) }, None);

    let result = execute_continuation_async(&cont, input, &JsonCodec)
        .await
        .unwrap();
    assert_eq!(decode_u32(&result), 6);
}

#[tokio::test]
async fn test_async_chained_tasks() {
    let double = task_node("double", |i: u32| async move { Ok(i * 2) }, None);
    let add_one = task_node(
        "add_one",
        |i: u32| async move { Ok(i + 1) },
        Some(Box::new(double)),
    );

    let input = encode_u32(10);
    let result = execute_continuation_async(&add_one, input, &JsonCodec)
        .await
        .unwrap();
    assert_eq!(decode_u32(&result), 22);
}

#[tokio::test]
async fn test_async_fork_with_parallel_branches() {
    let branch_a = Arc::new(task_node(
        "branch_a",
        |i: u32| async move { Ok(i * 2) },
        None,
    ));
    let branch_b = Arc::new(task_node(
        "branch_b",
        |i: u32| async move { Ok(i + 5) },
        None,
    ));

    // No join - returns last branch result
    let fork = WorkflowContinuation::Fork {
        id: "fork".into(),
        branches: vec![branch_a, branch_b].into_boxed_slice(),
        join: None,
    };

    let input = encode_u32(10);
    let result = execute_continuation_async(&fork, input, &JsonCodec)
        .await
        .unwrap();
    assert_eq!(decode_u32(&result), 15); // branch_b: 10+5
}

#[tokio::test]
async fn test_async_task_no_implementation() {
    let cont = WorkflowContinuation::Task {
        id: "missing".into(),
        func: None,
        timeout: None,
        retry_policy: None,
        version: None,
        next: None,
    };

    let result = execute_continuation_async(&cont, Bytes::new(), &JsonCodec).await;
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("no implementation")
    );
}

#[tokio::test]
async fn test_async_task_failure_propagates() {
    let cont = task_node(
        "fail",
        |_i: u32| async move { Err::<u32, BoxError>("async task failed".into()) },
        None,
    );

    let input = encode_u32(1);
    let result = execute_continuation_async(&cont, input, &JsonCodec).await;
    assert!(result.is_err());
}

// ========================================================================
// Task timeout tests
// ========================================================================

#[tokio::test]
async fn test_async_task_completes_within_timeout() {
    let cont = WorkflowContinuation::Task {
        id: "fast".to_string(),
        func: Some(to_core_task(
            "fast",
            |i: u32| async move { Ok(i + 1) },
            codec(),
        )),
        timeout: Some(std::time::Duration::from_secs(5)),
        retry_policy: None,
        version: None,
        next: None,
    };

    let input = encode_u32(10);
    let result = execute_continuation_async(&cont, input, &JsonCodec).await;
    assert!(result.is_ok());
    assert_eq!(decode_u32(&result.unwrap()), 11);
}

#[tokio::test]
async fn test_async_task_exceeds_timeout() {
    let cont = WorkflowContinuation::Task {
        id: "slow".to_string(),
        func: Some(to_core_task(
            "slow",
            |i: u32| async move {
                // Sleep just long enough to exceed the timeout
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                Ok(i + 1)
            },
            codec(),
        )),
        // Deadline shorter than the sleep — post-execution check will fail
        timeout: Some(std::time::Duration::from_millis(5)),
        retry_policy: None,
        version: None,
        next: None,
    };

    let input = encode_u32(10);
    let result = execute_continuation_async(&cont, input, &JsonCodec).await;
    let err = result.unwrap_err();
    assert!(err.to_string().contains("timed out"));
    assert!(err.to_string().contains("slow"));
}

#[tokio::test]
async fn test_async_task_no_timeout_unlimited() {
    // Task with no timeout should complete regardless of runtime
    let cont = WorkflowContinuation::Task {
        id: "normal".to_string(),
        func: Some(to_core_task(
            "normal",
            |i: u32| async move {
                tokio::time::sleep(std::time::Duration::from_millis(5)).await;
                Ok(i + 1)
            },
            codec(),
        )),
        timeout: None,
        retry_policy: None,
        version: None,
        next: None,
    };

    let input = encode_u32(42);
    let result = execute_continuation_async(&cont, input, &JsonCodec).await;
    assert!(result.is_ok());
    assert_eq!(decode_u32(&result.unwrap()), 43);
}

#[tokio::test]
async fn test_checkpointing_task_timeout() {
    let backend = InMemoryBackend::new();
    let cont = WorkflowContinuation::Task {
        id: "slow".to_string(),
        func: None,
        timeout: Some(std::time::Duration::from_millis(10)),
        retry_policy: None,
        version: None,
        next: None,
    };

    let input = encode_u32(1);
    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash".into(), input.clone());
    snapshot.update_position(ExecutionPosition::AtTask {
        task_id: "slow".into(),
    });
    backend.save_snapshot(&snapshot).await.unwrap();

    let slow_task = |_id: &str, input: Bytes| async move {
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        Ok(input)
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &slow_task,
        &JsonCodec,
    )
    .await;

    let err = result.unwrap_err();
    assert!(err.to_string().contains("timed out"));
    assert!(err.to_string().contains("slow"));
}

#[tokio::test]
async fn test_checkpointing_skipped_tasks_bypass_timeout() {
    let backend = InMemoryBackend::new();
    // Task with very short timeout — but it's already cached, so timeout shouldn't matter
    let cont = WorkflowContinuation::Task {
        id: "cached".to_string(),
        func: None,
        timeout: Some(std::time::Duration::from_millis(1)),
        retry_policy: None,
        version: None,
        next: None,
    };

    let output = encode_u32(42);
    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash".into(), encode_u32(1));
    snapshot.update_position(ExecutionPosition::AtTask {
        task_id: "cached".into(),
    });
    snapshot.mark_task_completed("cached".to_string(), output.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let never_called = |_id: &str, _input: Bytes| async move {
        panic!("should not be called for cached tasks");
        #[allow(unreachable_code)]
        Ok(Bytes::new())
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        encode_u32(1),
        &mut snapshot,
        &backend,
        &never_called,
        &JsonCodec,
    )
    .await;

    assert!(result.is_ok());
    assert_eq!(decode_u32(&result.unwrap()), 42);
}

// ========================================================================
// prepare_run / prepare_resume / finalize_execution
// ========================================================================

#[tokio::test]
async fn test_prepare_run_creates_snapshot() {
    let backend = InMemoryBackend::new();
    let snapshot = prepare_run(
        "inst-1".into(),
        "hash-1".into(),
        Bytes::from("input"),
        "task-1".into(),
        &backend,
    )
    .await
    .unwrap();

    assert_eq!(snapshot.instance_id, "inst-1");
    assert_eq!(snapshot.definition_hash, "hash-1");
    assert!(snapshot.state.is_in_progress());

    // Verify it was saved to backend
    let loaded = backend.load_snapshot("inst-1").await.unwrap();
    assert_eq!(loaded.instance_id, "inst-1");
}

#[tokio::test]
async fn test_prepare_resume_ready() {
    let backend = InMemoryBackend::new();
    let snapshot = WorkflowSnapshot::with_initial_input(
        "inst-1".into(),
        "hash-1".into(),
        Bytes::from("input"),
    );
    backend.save_snapshot(&snapshot).await.unwrap();

    let outcome = prepare_resume("inst-1", "hash-1", &backend).await.unwrap();
    match outcome {
        ResumeOutcome::Ready {
            snapshot,
            input_bytes,
        } => {
            assert_eq!(snapshot.instance_id, "inst-1");
            assert_eq!(input_bytes, Bytes::from("input"));
        }
        _ => panic!("Expected Ready outcome"),
    }
}

#[tokio::test]
async fn test_prepare_resume_with_completed_tasks() {
    let backend = InMemoryBackend::new();
    let mut snapshot = WorkflowSnapshot::with_initial_input(
        "inst-1".into(),
        "hash-1".into(),
        Bytes::from("initial"),
    );
    snapshot.mark_task_completed("task-1".into(), Bytes::from("task1_output"));
    backend.save_snapshot(&snapshot).await.unwrap();

    let outcome = prepare_resume("inst-1", "hash-1", &backend).await.unwrap();
    match outcome {
        ResumeOutcome::Ready { input_bytes, .. } => {
            // Should use last task output, not initial input
            assert_eq!(input_bytes, Bytes::from("task1_output"));
        }
        _ => panic!("Expected Ready outcome"),
    }
}

#[tokio::test]
async fn test_prepare_resume_already_completed() {
    let backend = InMemoryBackend::new();
    let mut snapshot = WorkflowSnapshot::new("inst-1".into(), "hash-1".into());
    snapshot.mark_completed(Bytes::from("result"));
    backend.save_snapshot(&snapshot).await.unwrap();

    let outcome = prepare_resume("inst-1", "hash-1", &backend).await.unwrap();
    match outcome {
        ResumeOutcome::AlreadyTerminal(WorkflowStatus::Completed) => {}
        _ => panic!("Expected AlreadyTerminal(Completed)"),
    }
}

#[tokio::test]
async fn test_prepare_resume_already_failed() {
    let backend = InMemoryBackend::new();
    let mut snapshot = WorkflowSnapshot::new("inst-1".into(), "hash-1".into());
    snapshot.mark_failed("err".into());
    backend.save_snapshot(&snapshot).await.unwrap();

    let outcome = prepare_resume("inst-1", "hash-1", &backend).await.unwrap();
    match outcome {
        ResumeOutcome::AlreadyTerminal(WorkflowStatus::Failed(_)) => {}
        _ => panic!("Expected AlreadyTerminal(Failed)"),
    }
}

#[tokio::test]
async fn test_prepare_resume_already_cancelled() {
    let backend = InMemoryBackend::new();
    let mut snapshot = WorkflowSnapshot::new("inst-1".into(), "hash-1".into());
    snapshot.mark_cancelled(Some("reason".into()), Some("admin".into()), None);
    backend.save_snapshot(&snapshot).await.unwrap();

    let outcome = prepare_resume("inst-1", "hash-1", &backend).await.unwrap();
    match outcome {
        ResumeOutcome::AlreadyTerminal(WorkflowStatus::Cancelled { reason, .. }) => {
            assert_eq!(reason, Some("reason".into()));
        }
        _ => panic!("Expected AlreadyTerminal(Cancelled)"),
    }
}

#[tokio::test]
async fn test_prepare_resume_hash_mismatch() {
    let backend = InMemoryBackend::new();
    let snapshot = WorkflowSnapshot::new("inst-1".into(), "hash-1".into());
    backend.save_snapshot(&snapshot).await.unwrap();

    let result = prepare_resume("inst-1", "wrong-hash", &backend).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("mismatch"));
}

#[tokio::test]
async fn test_finalize_execution_success() {
    let backend = InMemoryBackend::new();
    let mut snapshot = WorkflowSnapshot::new("inst-1".into(), "hash-1".into());
    backend.save_snapshot(&snapshot).await.unwrap();

    let (status, output) = finalize_execution(Ok(Bytes::from("output")), &mut snapshot, &backend)
        .await
        .unwrap();

    match status {
        WorkflowStatus::Completed => {}
        _ => panic!("Expected Completed"),
    }
    assert_eq!(output, Some(Bytes::from("output")));

    let saved = backend.load_snapshot("inst-1").await.unwrap();
    assert!(saved.state.is_completed());
}

#[tokio::test]
async fn test_finalize_execution_failure() {
    let backend = InMemoryBackend::new();
    let mut snapshot = WorkflowSnapshot::new("inst-1".into(), "hash-1".into());
    backend.save_snapshot(&snapshot).await.unwrap();

    let (status, output) = finalize_execution(
        Err(RuntimeError::from(BoxError::from("task failed"))),
        &mut snapshot,
        &backend,
    )
    .await
    .unwrap();

    match status {
        WorkflowStatus::Failed(e) => {
            assert!(e.contains("task failed"));
        }
        _ => panic!("Expected Failed"),
    }
    assert!(output.is_none());

    let saved = backend.load_snapshot("inst-1").await.unwrap();
    assert!(saved.state.is_failed());
}

#[tokio::test]
async fn test_finalize_execution_cancellation() {
    let backend = InMemoryBackend::new();
    let mut snapshot = WorkflowSnapshot::new("inst-1".into(), "hash-1".into());
    // Mark as cancelled in backend so finalize can reload details
    snapshot.mark_cancelled(Some("timeout".into()), Some("system".into()), None);
    backend.save_snapshot(&snapshot).await.unwrap();

    // Reset local snapshot to in-progress for finalize logic
    let mut local_snapshot = WorkflowSnapshot::new("inst-1".into(), "hash-1".into());

    let (status, output) = finalize_execution(
        Err(WorkflowError::cancelled().into()),
        &mut local_snapshot,
        &backend,
    )
    .await
    .unwrap();

    match status {
        WorkflowStatus::Cancelled {
            reason,
            cancelled_by,
        } => {
            assert_eq!(reason, Some("timeout".into()));
            assert_eq!(cancelled_by, Some("system".into()));
        }
        _ => panic!("Expected Cancelled"),
    }
    assert!(output.is_none());
}

// ========================================================================
// execute_continuation_with_checkpointing
// ========================================================================

#[tokio::test]
async fn test_checkpointing_single_task() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(5);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let cont = stub_node("add_one", None);

    let callback = |id: &str, input: Bytes| {
        let id = id.to_string();
        async move {
            let val: u32 = serde_json::from_slice(&input)?;
            match id.as_str() {
                "add_one" => Ok(Bytes::from(serde_json::to_vec(&(val + 1))?)),
                _ => Err(format!("Unknown: {id}").into()),
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    assert_eq!(decode_u32(&result), 6);
    assert!(snapshot.get_task_result("add_one").is_some());
}

#[tokio::test]
async fn test_checkpointing_chain() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(10);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let double = stub_node("double", None);
    let add_one = stub_node("add_one", Some(Box::new(double)));

    let callback = |id: &str, input: Bytes| {
        let id = id.to_string();
        async move {
            let val: u32 = serde_json::from_slice(&input)?;
            match id.as_str() {
                "add_one" => Ok(Bytes::from(serde_json::to_vec(&(val + 1))?)),
                "double" => Ok(Bytes::from(serde_json::to_vec(&(val * 2))?)),
                _ => Err(format!("Unknown: {id}").into()),
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &add_one,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    assert_eq!(decode_u32(&result), 22); // (10+1)*2
    assert!(snapshot.get_task_result("add_one").is_some());
    assert!(snapshot.get_task_result("double").is_some());
}

#[tokio::test]
async fn test_checkpointing_skips_completed_tasks() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(10);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    // Pre-mark task as completed (simulates resume)
    snapshot.mark_task_completed("add_one".into(), encode_u32(11));
    backend.save_snapshot(&snapshot).await.unwrap();

    let double = stub_node("double", None);
    let add_one = stub_node("add_one", Some(Box::new(double)));

    let was_called = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let was_called_clone = was_called.clone();

    let callback = move |id: &str, input: Bytes| {
        let id = id.to_string();
        let was_called_inner = was_called_clone.clone();
        async move {
            let val: u32 = serde_json::from_slice(&input)?;
            match id.as_str() {
                "add_one" => {
                    was_called_inner.store(true, std::sync::atomic::Ordering::SeqCst);
                    Ok(Bytes::from(serde_json::to_vec(&(val + 1))?))
                }
                "double" => Ok(Bytes::from(serde_json::to_vec(&(val * 2))?)),
                _ => Err(format!("Unknown: {id}").into()),
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &add_one,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    // add_one should NOT have been called - it was already completed
    assert!(!was_called.load(std::sync::atomic::Ordering::SeqCst));
    // cached output 11 * 2 = 22
    assert_eq!(decode_u32(&result), 22);
}

#[tokio::test]
async fn test_checkpointing_fork_sequential() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(10);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let branch_a = Arc::new(stub_node("branch_a", None));
    let branch_b = Arc::new(stub_node("branch_b", None));
    let join_task = stub_node("join", None);

    let fork = WorkflowContinuation::Fork {
        id: "fork".into(),
        branches: vec![branch_a, branch_b].into_boxed_slice(),
        join: Some(Box::new(join_task)),
    };

    let callback = |id: &str, input: Bytes| {
        let id = id.to_string();
        async move {
            let val: u32 = serde_json::from_slice(&input).unwrap_or(0);
            match id.as_str() {
                "branch_a" => Ok(Bytes::from(serde_json::to_vec(&(val * 2))?)),
                "branch_b" => Ok(Bytes::from(serde_json::to_vec(&(val + 5))?)),
                "join" => {
                    let branches: NamedBranchResults = serde_json::from_slice(&input)?;
                    let map = branches.into_map();
                    let a: u32 = serde_json::from_slice(&map["branch_a"])?;
                    let b: u32 = serde_json::from_slice(&map["branch_b"])?;
                    Ok(Bytes::from(serde_json::to_vec(&(a + b))?))
                }
                _ => Err(format!("Unknown: {id}").into()),
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &fork,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    // branch_a: 10*2=20, branch_b: 10+5=15, join: 20+15=35
    assert_eq!(decode_u32(&result), 35);
}

#[tokio::test]
async fn test_checkpointing_cancellation() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(5);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    // Request cancellation before execution
    backend
        .store_signal(
            "inst-1",
            sayiir_core::snapshot::SignalKind::Cancel,
            sayiir_core::snapshot::SignalRequest::new(
                Some("test cancel".into()),
                Some("tester".into()),
            ),
        )
        .await
        .unwrap();

    let cont = stub_node("task1", None);

    let callback =
        |_id: &str, _input: Bytes| async { Err::<Bytes, BoxError>("Should not be called".into()) };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;

    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(matches!(
        err,
        RuntimeError::Workflow(WorkflowError::Cancelled { .. })
    ));
}

// ========================================================================
// get_resume_input
// ========================================================================

#[test]
fn test_get_resume_input_no_completed_tasks() {
    let snapshot = WorkflowSnapshot::with_initial_input(
        "inst-1".into(),
        "hash-1".into(),
        Bytes::from("initial"),
    );
    let input = get_resume_input(&snapshot).unwrap();
    assert_eq!(input, Bytes::from("initial"));
}

#[test]
fn test_get_resume_input_with_completed_tasks() {
    let mut snapshot = WorkflowSnapshot::with_initial_input(
        "inst-1".into(),
        "hash-1".into(),
        Bytes::from("initial"),
    );
    snapshot.mark_task_completed("task-1".into(), Bytes::from("task1_out"));
    let input = get_resume_input(&snapshot).unwrap();
    assert_eq!(input, Bytes::from("task1_out"));
}

#[test]
fn test_get_resume_input_not_in_progress() {
    let mut snapshot = WorkflowSnapshot::new("inst-1".into(), "hash-1".into());
    snapshot.mark_completed(Bytes::from("done"));
    let result = get_resume_input(&snapshot);
    assert!(result.is_err());
}

#[test]
fn test_get_resume_input_no_initial_input() {
    let snapshot = WorkflowSnapshot::new("inst-1".into(), "hash-1".into());
    let result = get_resume_input(&snapshot);
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("initial input not stored")
    );
}

// ========================================================================
// Delay tests
// ========================================================================

#[test]
fn test_sync_delay_passthrough() {
    let delay = WorkflowContinuation::Delay {
        id: "short_wait".into(),
        duration: std::time::Duration::from_millis(1),
        next: None,
    };

    let input = encode_u32(42);
    let callback = |_id: &str, _input: Bytes| -> Result<Bytes, BoxError> {
        panic!("callback should not be called for delay");
    };

    let result = execute_continuation_sync(&delay, input, &callback, &JsonCodec).unwrap();
    // Delay passes input through unchanged
    assert_eq!(decode_u32(&result), 42);
}

#[test]
fn test_sync_delay_in_chain() {
    let double = stub_node("double", None);
    let delay = WorkflowContinuation::Delay {
        id: "wait".into(),
        duration: std::time::Duration::from_millis(1),
        next: Some(Box::new(double)),
    };
    let add_one = stub_node("add_one", Some(Box::new(delay)));

    let input = encode_u32(10);
    let callback = |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val = decode_u32(&input);
        match id {
            "add_one" => Ok(encode_u32(val + 1)),
            "double" => Ok(encode_u32(val * 2)),
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&add_one, input, &callback, &JsonCodec).unwrap();
    // 10 + 1 = 11, delay (passthrough 11), 11 * 2 = 22
    assert_eq!(decode_u32(&result), 22);
}

#[tokio::test]
async fn test_async_delay_passthrough() {
    let delay = WorkflowContinuation::Delay {
        id: "short_wait".into(),
        duration: std::time::Duration::from_millis(1),
        next: None,
    };

    let input = encode_u32(99);
    let result = execute_continuation_async(&delay, input, &JsonCodec)
        .await
        .unwrap();
    assert_eq!(decode_u32(&result), 99);
}

#[tokio::test]
async fn test_async_delay_in_chain() {
    let double = task_node("double", |i: u32| async move { Ok(i * 2) }, None);
    let delay = WorkflowContinuation::Delay {
        id: "wait".into(),
        duration: std::time::Duration::from_millis(1),
        next: Some(Box::new(double)),
    };
    let add_one = task_node(
        "add_one",
        |i: u32| async move { Ok(i + 1) },
        Some(Box::new(delay)),
    );

    let input = encode_u32(5);
    let result = execute_continuation_async(&add_one, input, &JsonCodec)
        .await
        .unwrap();
    // 5 + 1 = 6, delay (passthrough 6), 6 * 2 = 12
    assert_eq!(decode_u32(&result), 12);
}

#[tokio::test]
async fn test_checkpointing_delay_returns_waiting() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(42);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let next_task = stub_node("process", None);
    let delay = WorkflowContinuation::Delay {
        id: "wait_1h".into(),
        duration: std::time::Duration::from_secs(3600),
        next: Some(Box::new(next_task)),
    };

    let callback =
        |_id: &str, _input: Bytes| async { Err::<Bytes, BoxError>("Should not be called".into()) };

    let result = execute_continuation_with_checkpointing(
        &delay,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;

    // Should return a Waiting error
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(matches!(
        err,
        RuntimeError::Workflow(WorkflowError::Waiting { .. })
    ));

    // Snapshot should be at AtDelay position with pass-through stored
    match &snapshot.state {
        WorkflowSnapshotState::InProgress { position, .. } => match position {
            ExecutionPosition::AtDelay {
                delay_id,
                next_task_id,
                ..
            } => {
                assert_eq!(delay_id, "wait_1h");
                assert_eq!(next_task_id.as_deref(), Some("process"));
            }
            other => panic!("Expected AtDelay, got {other:?}"),
        },
        other => panic!("Expected InProgress, got {other:?}"),
    }

    // Pass-through value should be stored
    let stored = snapshot.get_task_result("wait_1h").unwrap();
    assert_eq!(decode_u32(&stored.output), 42);
}

#[tokio::test]
async fn test_checkpointing_delay_skip_on_resume() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(42);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    // Pre-mark delay as completed (simulates resume after delay expired)
    snapshot.mark_task_completed("wait".into(), encode_u32(42));
    backend.save_snapshot(&snapshot).await.unwrap();

    let process = stub_node("process", None);
    let delay = WorkflowContinuation::Delay {
        id: "wait".into(),
        duration: std::time::Duration::from_secs(3600),
        next: Some(Box::new(process)),
    };

    let callback = |id: &str, input: Bytes| {
        let id = id.to_string();
        async move {
            let val: u32 = serde_json::from_slice(&input)?;
            match id.as_str() {
                "process" => Ok(Bytes::from(serde_json::to_vec(&(val + 10))?)),
                _ => Err(format!("Unknown: {id}").into()),
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &delay,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    // Delay was skipped (already completed), process received 42, output 52
    assert_eq!(decode_u32(&result), 52);
}

#[tokio::test]
async fn test_checkpointing_delay_cancellation() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(10);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    // Request cancellation
    backend
        .store_signal(
            "inst-1",
            sayiir_core::snapshot::SignalKind::Cancel,
            sayiir_core::snapshot::SignalRequest::new(
                Some("test cancel".into()),
                Some("tester".into()),
            ),
        )
        .await
        .unwrap();

    let delay = WorkflowContinuation::Delay {
        id: "wait".into(),
        duration: std::time::Duration::from_secs(3600),
        next: None,
    };

    let callback =
        |_id: &str, _input: Bytes| async { Err::<Bytes, BoxError>("Should not be called".into()) };

    let result = execute_continuation_with_checkpointing(
        &delay,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;

    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        RuntimeError::Workflow(WorkflowError::Cancelled { .. })
    ));
}

#[tokio::test]
async fn test_finalize_execution_waiting() {
    let backend = InMemoryBackend::new();
    let mut snapshot = WorkflowSnapshot::new("inst-1".into(), "hash-1".into());

    // Set up the snapshot as if it's parked at a delay
    let now = chrono::Utc::now();
    let wake_at = now + chrono::Duration::hours(1);
    snapshot.update_position(ExecutionPosition::AtDelay {
        delay_id: "my_delay".into(),
        entered_at: now,
        wake_at,
        next_task_id: Some("next_step".into()),
    });
    backend.save_snapshot(&snapshot).await.unwrap();

    let (status, output) = finalize_execution(
        Err(WorkflowError::Waiting { wake_at }.into()),
        &mut snapshot,
        &backend,
    )
    .await
    .unwrap();

    match status {
        WorkflowStatus::Waiting {
            wake_at: wa,
            delay_id,
        } => {
            assert_eq!(wa, wake_at);
            assert_eq!(delay_id, "my_delay");
        }
        _ => panic!("Expected Waiting status, got {status:?}"),
    }
    assert!(output.is_none());

    // Snapshot should still be in-progress (not completed or failed)
    let loaded = backend.load_snapshot("inst-1").await.unwrap();
    assert!(loaded.state.is_in_progress());
}

// ========================================================================
// Fork with delay (durable delays inside branches)
// ========================================================================

/// Helper: build a fork with a delay inside one branch.
///
/// Structure: `Fork(branch_a: task, branch_b: task -> delay -> task) -> join`
fn fork_with_delay_in_branch() -> WorkflowContinuation {
    let branch_a = Arc::new(stub_node("branch_a", None));

    let after_delay = stub_node("after_delay", None);
    let delay = WorkflowContinuation::Delay {
        id: "branch_delay".into(),
        duration: std::time::Duration::from_secs(3600),
        next: Some(Box::new(after_delay)),
    };
    let branch_b = Arc::new(stub_node("before_delay", Some(Box::new(delay))));

    let join_task = stub_node("join", None);

    WorkflowContinuation::Fork {
        id: "fork".into(),
        branches: vec![branch_a, branch_b].into_boxed_slice(),
        join: Some(Box::new(join_task)),
    }
}

type BoxFut = std::pin::Pin<Box<dyn std::future::Future<Output = Result<Bytes, BoxError>> + Send>>;

fn make_fork_callback() -> impl Fn(&str, Bytes) -> BoxFut + Send + Sync {
    |id: &str, input: Bytes| {
        let id = id.to_string();
        Box::pin(async move {
            let val: u32 = serde_json::from_slice(&input).unwrap_or(0);
            match id.as_str() {
                "branch_a" => Ok(encode_u32(val * 2)),
                "before_delay" => Ok(encode_u32(val + 100)),
                "after_delay" => Ok(encode_u32(val + 1)),
                "join" => {
                    let branches: sayiir_core::branch_results::NamedBranchResults =
                        serde_json::from_slice(&input)?;
                    let map = branches.into_map();
                    let a: u32 = serde_json::from_slice(&map["branch_a"])?;
                    // branch_b's ID is "before_delay" (first task in the chain)
                    let b: u32 = serde_json::from_slice(&map["before_delay"])?;
                    Ok(encode_u32(a + b))
                }
                other => Err(format!("Unknown task: {other}").into()),
            }
        })
    }
}

#[tokio::test]
async fn test_fork_with_delay_parks_at_fork() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(10);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let fork = fork_with_delay_in_branch();
    let callback = make_fork_callback();

    let result = execute_continuation_with_checkpointing(
        &fork,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;

    // Should return Waiting because branch_b hits a delay
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        RuntimeError::Workflow(WorkflowError::Waiting { .. })
    ));

    // Snapshot should be at AtFork position
    match &snapshot.state {
        WorkflowSnapshotState::InProgress { position, .. } => match position {
            ExecutionPosition::AtFork {
                fork_id,
                completed_branches,
                wake_at,
            } => {
                assert_eq!(fork_id, "fork");
                // branch_a completed, branch_b is waiting
                assert_eq!(completed_branches.len(), 1);
                assert!(completed_branches.contains_key("branch_a"));
                assert!(*wake_at > chrono::Utc::now());
            }
            other => panic!("Expected AtFork, got {other:?}"),
        },
        other => panic!("Expected InProgress, got {other:?}"),
    }

    // branch_a result should be cached
    assert!(snapshot.get_task_result("branch_a").is_some());
    // before_delay task result should be cached (saved during branch execution)
    assert!(snapshot.get_task_result("before_delay").is_some());
    // delay pass-through should be cached
    assert!(snapshot.get_task_result("branch_delay").is_some());
}

#[tokio::test]
async fn test_fork_with_delay_resumes_after_expiry() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(10);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    // Use a very short delay so it expires immediately
    let branch_a = Arc::new(stub_node("branch_a", None));
    let after_delay = stub_node("after_delay", None);
    let delay = WorkflowContinuation::Delay {
        id: "branch_delay".into(),
        duration: std::time::Duration::from_millis(1),
        next: Some(Box::new(after_delay)),
    };
    let branch_b = Arc::new(stub_node("before_delay", Some(Box::new(delay))));
    let join_task = stub_node("join", None);
    let fork = WorkflowContinuation::Fork {
        id: "fork".into(),
        branches: vec![branch_a, branch_b].into_boxed_slice(),
        join: Some(Box::new(join_task)),
    };

    let callback = make_fork_callback();

    // First execution — parks at fork
    let result = execute_continuation_with_checkpointing(
        &fork,
        input.clone(),
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;
    assert!(matches!(
        result.unwrap_err(),
        RuntimeError::Workflow(WorkflowError::Waiting { .. })
    ));

    // Wait for delay to expire
    tokio::time::sleep(std::time::Duration::from_millis(10)).await;

    // Reload snapshot from backend (simulates what resume() does)
    snapshot = backend.load_snapshot("inst-1").await.unwrap();

    // Re-execute — cached tasks and expired delay should be skipped
    let result = execute_continuation_with_checkpointing(
        &fork,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;

    assert!(
        result.is_ok(),
        "Expected Ok after delay expired, got {result:?}"
    );
}

#[tokio::test]
async fn test_fork_with_delays_in_multiple_branches() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(5);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    // Both branches have delays
    let after_delay_a = stub_node("after_a", None);
    let delay_a = WorkflowContinuation::Delay {
        id: "delay_a".into(),
        duration: std::time::Duration::from_secs(100),
        next: Some(Box::new(after_delay_a)),
    };
    let branch_a = Arc::new(delay_a);

    let after_delay_b = stub_node("after_b", None);
    let delay_b = WorkflowContinuation::Delay {
        id: "delay_b".into(),
        duration: std::time::Duration::from_secs(200),
        next: Some(Box::new(after_delay_b)),
    };
    let branch_b = Arc::new(delay_b);

    let join_task = stub_node("join", None);
    let fork = WorkflowContinuation::Fork {
        id: "fork".into(),
        branches: vec![branch_a, branch_b].into_boxed_slice(),
        join: Some(Box::new(join_task)),
    };

    let callback = |id: &str, input: Bytes| {
        let id = id.to_string();
        async move {
            match id.as_str() {
                "after_a" | "after_b" | "join" => Ok(input),
                other => Err(format!("Unknown task: {other}").into()),
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &fork,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;

    // Should return Waiting
    assert!(matches!(
        result.unwrap_err(),
        RuntimeError::Workflow(WorkflowError::Waiting { .. })
    ));

    // Should be at AtFork with NO completed branches (both waited)
    match &snapshot.state {
        WorkflowSnapshotState::InProgress { position, .. } => match position {
            ExecutionPosition::AtFork {
                completed_branches,
                wake_at,
                ..
            } => {
                assert!(
                    completed_branches.is_empty(),
                    "No branches completed, both hit delays"
                );
                // wake_at should be the max of the two delays (200s)
                let min_expected = chrono::Utc::now() + chrono::Duration::seconds(150);
                assert!(
                    *wake_at > min_expected,
                    "wake_at should be ~200s in the future, got {wake_at:?}"
                );
            }
            other => panic!("Expected AtFork, got {other:?}"),
        },
        other => panic!("Expected InProgress, got {other:?}"),
    }
}

#[tokio::test]
async fn test_fork_normal_branch_completes_delayed_branch_parks() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(10);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    // branch_a: normal task (completes immediately)
    // branch_b: delay (parks)
    let branch_a = Arc::new(stub_node("branch_a", None));
    let delay = WorkflowContinuation::Delay {
        id: "branch_delay".into(),
        duration: std::time::Duration::from_secs(3600),
        next: None,
    };
    let branch_b = Arc::new(delay);

    let join_task = stub_node("join", None);
    let fork = WorkflowContinuation::Fork {
        id: "fork".into(),
        branches: vec![branch_a, branch_b].into_boxed_slice(),
        join: Some(Box::new(join_task)),
    };

    let callback = |id: &str, input: Bytes| {
        let id = id.to_string();
        async move {
            match id.as_str() {
                "branch_a" => Ok(encode_u32(decode_u32(&input) * 2)),
                "join" => Ok(input),
                other => Err(format!("Unknown task: {other}").into()),
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &fork,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;

    assert!(matches!(
        result.unwrap_err(),
        RuntimeError::Workflow(WorkflowError::Waiting { .. })
    ));

    // branch_a should have completed, branch_b is waiting
    match &snapshot.state {
        WorkflowSnapshotState::InProgress { position, .. } => match position {
            ExecutionPosition::AtFork {
                completed_branches, ..
            } => {
                assert_eq!(completed_branches.len(), 1);
                assert!(completed_branches.contains_key("branch_a"));
                let result = &completed_branches["branch_a"];
                assert_eq!(decode_u32(&result.output), 20); // 10 * 2
            }
            other => panic!("Expected AtFork, got {other:?}"),
        },
        other => panic!("Expected InProgress, got {other:?}"),
    }
}

// ========================================================================
// Retry tests — sync
// ========================================================================

#[test]
fn test_sync_retry_succeeds_after_failures() {
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    // max_retries: 2 → backon max_times: 2 → 3 total calls allowed
    let cont = stub_node_with_retry("flaky", fast_retry(2), None);
    let input = encode_u32(10);

    let callback = move |_id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let attempt = attempts_clone.fetch_add(1, Ordering::SeqCst);
        if attempt < 2 {
            Err("transient error".into())
        } else {
            let val = decode_u32(&input);
            Ok(encode_u32(val + 1))
        }
    };

    let result = execute_continuation_sync(&cont, input, &callback, &JsonCodec).unwrap();
    assert_eq!(decode_u32(&result), 11);
    assert_eq!(attempts.load(Ordering::SeqCst), 3);
}

#[test]
fn test_sync_retry_exhaustion() {
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    // max_retries: 1 → backon max_times: 1 → 2 total calls, then error
    let cont = stub_node_with_retry("always_fail", fast_retry(1), None);
    let input = encode_u32(1);

    let callback = move |_id: &str, _input: Bytes| -> Result<Bytes, BoxError> {
        attempts_clone.fetch_add(1, Ordering::SeqCst);
        Err("permanent error".into())
    };

    let result = execute_continuation_sync(&cont, input, &callback, &JsonCodec);
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("permanent error"));
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

#[test]
fn test_sync_retry_no_retry_on_success() {
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    let cont = stub_node_with_retry("ok", fast_retry(2), None);
    let input = encode_u32(5);

    let callback = move |_id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        attempts_clone.fetch_add(1, Ordering::SeqCst);
        let val = decode_u32(&input);
        Ok(encode_u32(val + 1))
    };

    let result = execute_continuation_sync(&cont, input, &callback, &JsonCodec).unwrap();
    assert_eq!(decode_u32(&result), 6);
    assert_eq!(attempts.load(Ordering::SeqCst), 1);
}

#[test]
fn test_sync_retry_in_chain() {
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    let double = stub_node("double", None);
    let flaky = stub_node_with_retry("flaky", fast_retry(2), Some(Box::new(double)));
    let input = encode_u32(10);

    let callback = move |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val = decode_u32(&input);
        match id {
            "flaky" => {
                let attempt = attempts_clone.fetch_add(1, Ordering::SeqCst);
                if attempt < 1 {
                    Err("transient".into())
                } else {
                    Ok(encode_u32(val + 1))
                }
            }
            "double" => Ok(encode_u32(val * 2)),
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&flaky, input, &callback, &JsonCodec).unwrap();
    // flaky: 10+1=11 (after 1 retry), double: 11*2=22
    assert_eq!(decode_u32(&result), 22);
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

// ========================================================================
// Retry tests — async
// ========================================================================

#[tokio::test]
async fn test_async_retry_succeeds_after_failure() {
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    let cont = task_node_with_retry(
        "flaky",
        move |i: u32| {
            let a = attempts_clone.clone();
            async move {
                let attempt = a.fetch_add(1, Ordering::SeqCst);
                if attempt < 1 {
                    Err::<u32, BoxError>("transient".into())
                } else {
                    Ok(i + 1)
                }
            }
        },
        fast_retry(2),
        None,
    );

    let input = encode_u32(10);
    let result = execute_continuation_async(&cont, input, &JsonCodec)
        .await
        .unwrap();
    assert_eq!(decode_u32(&result), 11);
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn test_async_retry_exhaustion() {
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    let cont = task_node_with_retry(
        "always_fail",
        move |_i: u32| {
            let a = attempts_clone.clone();
            async move {
                a.fetch_add(1, Ordering::SeqCst);
                Err::<u32, BoxError>("permanent".into())
            }
        },
        fast_retry(1),
        None,
    );

    let input = encode_u32(1);
    let result = execute_continuation_async(&cont, input, &JsonCodec).await;
    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("permanent"));
    // max_retries: 1 → backon max_times: 1 → 2 total calls
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn test_async_retry_no_retry_on_success() {
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    let cont = task_node_with_retry(
        "ok",
        move |i: u32| {
            let a = attempts_clone.clone();
            async move {
                a.fetch_add(1, Ordering::SeqCst);
                Ok(i + 1)
            }
        },
        fast_retry(4),
        None,
    );

    let input = encode_u32(42);
    let result = execute_continuation_async(&cont, input, &JsonCodec)
        .await
        .unwrap();
    assert_eq!(decode_u32(&result), 43);
    assert_eq!(attempts.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn test_async_retry_with_timeout_triggers_retry() {
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    // First call: times out. Second call: completes fast.
    let cont = task_node_with_timeout_and_retry(
        "timeout_then_ok",
        move |i: u32| {
            let a = attempts_clone.clone();
            async move {
                let attempt = a.fetch_add(1, Ordering::SeqCst);
                if attempt == 0 {
                    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                }
                Ok(i + 1)
            }
        },
        std::time::Duration::from_millis(10),
        fast_retry(2),
        None,
    );

    let input = encode_u32(10);
    let result = execute_continuation_async(&cont, input, &JsonCodec)
        .await
        .unwrap();
    assert_eq!(decode_u32(&result), 11);
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn test_async_retry_in_chain() {
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    let double = task_node("double", |i: u32| async move { Ok(i * 2) }, None);
    let flaky = task_node_with_retry(
        "flaky",
        move |i: u32| {
            let a = attempts_clone.clone();
            async move {
                let attempt = a.fetch_add(1, Ordering::SeqCst);
                if attempt < 1 {
                    Err::<u32, BoxError>("transient".into())
                } else {
                    Ok(i + 1)
                }
            }
        },
        fast_retry(2),
        Some(Box::new(double)),
    );

    let input = encode_u32(5);
    let result = execute_continuation_async(&flaky, input, &JsonCodec)
        .await
        .unwrap();
    // flaky: 5+1=6 (after retry), double: 6*2=12
    assert_eq!(decode_u32(&result), 12);
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

// ========================================================================
// Retry tests — checkpointing
// ========================================================================

#[tokio::test]
async fn test_checkpointing_retry_succeeds_after_failure() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(10);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash".into(), input.clone());
    snapshot.update_position(ExecutionPosition::AtTask {
        task_id: "flaky".into(),
    });
    backend.save_snapshot(&snapshot).await.unwrap();

    let cont = stub_node_with_retry("flaky", fast_retry(2), None);
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    let callback = move |_id: &str, input: Bytes| {
        let a = attempts_clone.clone();
        async move {
            let attempt = a.fetch_add(1, Ordering::SeqCst);
            if attempt < 1 {
                Err::<Bytes, BoxError>("transient error".into())
            } else {
                let val: u32 = serde_json::from_slice(&input)?;
                Ok(Bytes::from(serde_json::to_vec(&(val + 1))?))
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    assert_eq!(decode_u32(&result), 11);
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
    // Task result is cached after success
    assert!(snapshot.get_task_result("flaky").is_some());
    // Retry state is cleared on success
    assert!(snapshot.get_retry_state("flaky").is_none());
}

#[tokio::test]
async fn test_checkpointing_retry_exhaustion() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(1);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash".into(), input.clone());
    snapshot.update_position(ExecutionPosition::AtTask {
        task_id: "always_fail".into(),
    });
    backend.save_snapshot(&snapshot).await.unwrap();

    let cont = stub_node_with_retry("always_fail", fast_retry(1), None);
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    let callback = move |_id: &str, _input: Bytes| {
        let a = attempts_clone.clone();
        async move {
            a.fetch_add(1, Ordering::SeqCst);
            Err::<Bytes, BoxError>("permanent error".into())
        }
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;

    assert!(result.is_err());
    assert!(result.unwrap_err().to_string().contains("permanent error"));
    // Checkpointing: initial + max_retries retries = 1 + 1 = 2 total
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn test_checkpointing_retry_state_persisted() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(10);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash".into(), input.clone());
    snapshot.update_position(ExecutionPosition::AtTask {
        task_id: "flaky".into(),
    });
    backend.save_snapshot(&snapshot).await.unwrap();

    let cont = stub_node_with_retry("flaky", fast_retry(4), None);
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    // Fail 3 times then succeed on 4th
    let callback = move |_id: &str, input: Bytes| {
        let a = attempts_clone.clone();
        async move {
            let attempt = a.fetch_add(1, Ordering::SeqCst);
            if attempt < 3 {
                Err::<Bytes, BoxError>(format!("error #{attempt}").into())
            } else {
                let val: u32 = serde_json::from_slice(&input)?;
                Ok(Bytes::from(serde_json::to_vec(&(val + 1))?))
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    assert_eq!(decode_u32(&result), 11);
    assert_eq!(attempts.load(Ordering::SeqCst), 4);

    // Retry state should be cleared after success
    assert!(snapshot.get_retry_state("flaky").is_none());

    // Snapshot was saved to backend during retries — verify it has the task result
    let persisted = backend.load_snapshot("inst-1").await.unwrap();
    assert!(persisted.get_task_result("flaky").is_some());
}

#[tokio::test]
async fn test_checkpointing_retry_with_timeout() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(10);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash".into(), input.clone());
    snapshot.update_position(ExecutionPosition::AtTask {
        task_id: "slow_then_fast".into(),
    });
    backend.save_snapshot(&snapshot).await.unwrap();

    // Timeout of 10ms; first attempt sleeps 200ms (triggers timeout), second is instant
    let cont = stub_node_with_timeout_and_retry(
        "slow_then_fast",
        std::time::Duration::from_millis(10),
        fast_retry(2),
        None,
    );

    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    let callback = move |_id: &str, input: Bytes| {
        let a = attempts_clone.clone();
        async move {
            let attempt = a.fetch_add(1, Ordering::SeqCst);
            if attempt == 0 {
                tokio::time::sleep(std::time::Duration::from_millis(200)).await;
            }
            Ok(input)
        }
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    assert_eq!(decode_u32(&result), 10);
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn test_checkpointing_retry_in_chain() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(5);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let double = stub_node("double", None);
    let flaky = stub_node_with_retry("flaky", fast_retry(2), Some(Box::new(double)));

    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    let callback = move |id: &str, input: Bytes| {
        let id = id.to_string();
        let a = attempts_clone.clone();
        async move {
            let val: u32 = serde_json::from_slice(&input)?;
            match id.as_str() {
                "flaky" => {
                    let attempt = a.fetch_add(1, Ordering::SeqCst);
                    if attempt < 1 {
                        Err::<Bytes, BoxError>("transient".into())
                    } else {
                        Ok(Bytes::from(serde_json::to_vec(&(val + 1))?))
                    }
                }
                "double" => Ok(Bytes::from(serde_json::to_vec(&(val * 2))?)),
                _ => Err(format!("Unknown: {id}").into()),
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &flaky,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    // flaky: 5+1=6 (after retry), double: 6*2=12
    assert_eq!(decode_u32(&result), 12);
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
    // Both tasks should be cached
    assert!(snapshot.get_task_result("flaky").is_some());
    assert!(snapshot.get_task_result("double").is_some());
}

// ========================================================================
// Timeout + chain tests
// ========================================================================

#[tokio::test]
async fn test_async_timeout_mid_chain_fails() {
    // First task succeeds, second task times out → chain fails
    let slow_task = WorkflowContinuation::Task {
        id: "slow".to_string(),
        func: Some(to_core_task(
            "slow",
            |i: u32| async move {
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                Ok(i * 2)
            },
            codec(),
        )),
        timeout: Some(std::time::Duration::from_millis(5)),
        retry_policy: None,
        version: None,
        next: None,
    };
    let fast_task = task_node(
        "fast",
        |i: u32| async move { Ok(i + 1) },
        Some(Box::new(slow_task)),
    );

    let input = encode_u32(10);
    let result = execute_continuation_async(&fast_task, input, &JsonCodec).await;
    let err = result.unwrap_err();
    assert!(err.to_string().contains("timed out"));
    assert!(err.to_string().contains("slow"));
}

#[tokio::test]
async fn test_async_timeout_passes_in_chain() {
    // Both tasks have timeouts but complete within them → chain succeeds
    let second = WorkflowContinuation::Task {
        id: "second".to_string(),
        func: Some(to_core_task(
            "second",
            |i: u32| async move { Ok(i * 2) },
            codec(),
        )),
        timeout: Some(std::time::Duration::from_secs(5)),
        retry_policy: None,
        version: None,
        next: None,
    };
    let first = WorkflowContinuation::Task {
        id: "first".to_string(),
        func: Some(to_core_task(
            "first",
            |i: u32| async move { Ok(i + 1) },
            codec(),
        )),
        timeout: Some(std::time::Duration::from_secs(5)),
        retry_policy: None,
        version: None,
        next: Some(Box::new(second)),
    };

    let input = encode_u32(10);
    let result = execute_continuation_async(&first, input, &JsonCodec)
        .await
        .unwrap();
    // first: 10+1=11, second: 11*2=22
    assert_eq!(decode_u32(&result), 22);
}

#[tokio::test]
async fn test_checkpointing_timeout_mid_chain() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(5);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    // fast_task → slow_task (times out)
    let slow_task = WorkflowContinuation::Task {
        id: "slow".to_string(),
        func: None,
        timeout: Some(std::time::Duration::from_millis(10)),
        retry_policy: None,
        version: None,
        next: None,
    };
    let fast_task = WorkflowContinuation::Task {
        id: "fast".to_string(),
        func: None,
        timeout: None,
        retry_policy: None,
        version: None,
        next: Some(Box::new(slow_task)),
    };

    let callback = |id: &str, input: Bytes| {
        let id = id.to_string();
        async move {
            match id.as_str() {
                "fast" => Ok(input),
                "slow" => {
                    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
                    Ok(input)
                }
                _ => Err(format!("Unknown: {id}").into()),
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &fast_task,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;

    let err = result.unwrap_err();
    assert!(err.to_string().contains("timed out"));
    assert!(err.to_string().contains("slow"));
    // First task should still be cached
    assert!(snapshot.get_task_result("fast").is_some());
}

// ========================================================================
// Delay edge cases
// ========================================================================

#[tokio::test]
async fn test_checkpointing_delay_terminal_parks() {
    // A delay with no next (terminal) should park and return Waiting
    let backend = InMemoryBackend::new();
    let input = encode_u32(42);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let delay = WorkflowContinuation::Delay {
        id: "final_wait".into(),
        duration: std::time::Duration::from_secs(3600),
        next: None,
    };

    let callback =
        |_id: &str, _input: Bytes| async { Err::<Bytes, BoxError>("Should not be called".into()) };

    let result = execute_continuation_with_checkpointing(
        &delay,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;

    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        RuntimeError::Workflow(WorkflowError::Waiting { .. })
    ));

    // next_task_id should be None for terminal delay
    match &snapshot.state {
        WorkflowSnapshotState::InProgress { position, .. } => match position {
            ExecutionPosition::AtDelay {
                delay_id,
                next_task_id,
                ..
            } => {
                assert_eq!(delay_id, "final_wait");
                assert!(next_task_id.is_none());
            }
            other => panic!("Expected AtDelay, got {other:?}"),
        },
        other => panic!("Expected InProgress, got {other:?}"),
    }

    // Pass-through value should be stored
    let stored = snapshot.get_task_result("final_wait").unwrap();
    assert_eq!(decode_u32(&stored.output), 42);
}

#[tokio::test]
async fn test_checkpointing_delay_after_task_chain() {
    // task → delay → task: first task completes, delay parks, resume completes chain
    let backend = InMemoryBackend::new();
    let input = encode_u32(10);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let process = stub_node("process", None);
    let delay = WorkflowContinuation::Delay {
        id: "wait".into(),
        duration: std::time::Duration::from_millis(1), // very short for resume test
        next: Some(Box::new(process)),
    };
    let prepare = stub_node("prepare", Some(Box::new(delay)));

    let callback = |id: &str, input: Bytes| {
        let id = id.to_string();
        async move {
            let val: u32 = serde_json::from_slice(&input)?;
            match id.as_str() {
                "prepare" => Ok(Bytes::from(serde_json::to_vec(&(val + 1))?)),
                "process" => Ok(Bytes::from(serde_json::to_vec(&(val * 2))?)),
                _ => Err(format!("Unknown: {id}").into()),
            }
        }
    };

    // First run: prepare completes, delay parks
    let result = execute_continuation_with_checkpointing(
        &prepare,
        input.clone(),
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;
    assert!(matches!(
        result.unwrap_err(),
        RuntimeError::Workflow(WorkflowError::Waiting { .. })
    ));
    assert!(snapshot.get_task_result("prepare").is_some());

    // Wait for delay to expire
    tokio::time::sleep(std::time::Duration::from_millis(10)).await;

    // Reload snapshot and re-execute — prepare is cached, delay skipped, process runs
    snapshot = backend.load_snapshot("inst-1").await.unwrap();
    let result = execute_continuation_with_checkpointing(
        &prepare,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    // prepare: 10+1=11, delay (passthrough 11), process: 11*2=22
    assert_eq!(decode_u32(&result), 22);
}

#[test]
fn test_sync_delay_multiple_in_chain() {
    // task → delay → delay → task: two consecutive delays pass input through
    let final_task = stub_node("final", None);
    let delay2 = WorkflowContinuation::Delay {
        id: "wait2".into(),
        duration: std::time::Duration::from_millis(1),
        next: Some(Box::new(final_task)),
    };
    let delay1 = WorkflowContinuation::Delay {
        id: "wait1".into(),
        duration: std::time::Duration::from_millis(1),
        next: Some(Box::new(delay2)),
    };
    let first = stub_node("first", Some(Box::new(delay1)));

    let input = encode_u32(7);
    let callback = |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val = decode_u32(&input);
        match id {
            "first" => Ok(encode_u32(val + 3)),
            "final" => Ok(encode_u32(val * 10)),
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&first, input, &callback, &JsonCodec).unwrap();
    // first: 7+3=10, delay1: pass 10, delay2: pass 10, final: 10*10=100
    assert_eq!(decode_u32(&result), 100);
}

#[tokio::test]
async fn test_async_delay_multiple_in_chain() {
    let final_task = task_node("final", |i: u32| async move { Ok(i * 10) }, None);
    let delay2 = WorkflowContinuation::Delay {
        id: "wait2".into(),
        duration: std::time::Duration::from_millis(1),
        next: Some(Box::new(final_task)),
    };
    let delay1 = WorkflowContinuation::Delay {
        id: "wait1".into(),
        duration: std::time::Duration::from_millis(1),
        next: Some(Box::new(delay2)),
    };
    let first = task_node(
        "first",
        |i: u32| async move { Ok(i + 3) },
        Some(Box::new(delay1)),
    );

    let input = encode_u32(7);
    let result = execute_continuation_async(&first, input, &JsonCodec)
        .await
        .unwrap();
    // first: 7+3=10, delay1: pass 10, delay2: pass 10, final: 10*10=100
    assert_eq!(decode_u32(&result), 100);
}

// ========================================================================
// Retry + delay combinations
// ========================================================================

#[test]
fn test_sync_retry_after_delay() {
    // delay → retry task: delay passes through, retry task eventually succeeds
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    let retry_task = stub_node_with_retry("retry_task", fast_retry(2), None);
    let delay = WorkflowContinuation::Delay {
        id: "wait".into(),
        duration: std::time::Duration::from_millis(1),
        next: Some(Box::new(retry_task)),
    };

    let input = encode_u32(10);
    let callback = move |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        match id {
            "retry_task" => {
                let attempt = attempts_clone.fetch_add(1, Ordering::SeqCst);
                if attempt < 1 {
                    Err("transient".into())
                } else {
                    let val = decode_u32(&input);
                    Ok(encode_u32(val + 1))
                }
            }
            _ => Err(format!("Unknown: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&delay, input, &callback, &JsonCodec).unwrap();
    assert_eq!(decode_u32(&result), 11);
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn test_async_retry_after_delay() {
    let attempts = Arc::new(AtomicU32::new(0));
    let attempts_clone = attempts.clone();

    let retry_task = task_node_with_retry(
        "retry_task",
        move |i: u32| {
            let a = attempts_clone.clone();
            async move {
                let attempt = a.fetch_add(1, Ordering::SeqCst);
                if attempt < 1 {
                    Err::<u32, BoxError>("transient".into())
                } else {
                    Ok(i + 1)
                }
            }
        },
        fast_retry(2),
        None,
    );

    let delay = WorkflowContinuation::Delay {
        id: "wait".into(),
        duration: std::time::Duration::from_millis(1),
        next: Some(Box::new(retry_task)),
    };

    let input = encode_u32(10);
    let result = execute_continuation_async(&delay, input, &JsonCodec)
        .await
        .unwrap();
    assert_eq!(decode_u32(&result), 11);
    assert_eq!(attempts.load(Ordering::SeqCst), 2);
}

// ========================================================================
// Proptests
// ========================================================================

mod proptests {
    use super::*;
    use proptest::prelude::*;

    // Property 1: Roundtrip identity — serialize then deserialize recovers the same entries.
    proptest! {
        #[test]
        fn serialize_deserialize_roundtrip(
            entries in proptest::collection::vec(
                (
                    "[a-z]{0,32}",
                    proptest::collection::vec(any::<u8>(), 0..64),
                ),
                0..8,
            )
        ) {
            let typed: Vec<(String, Bytes)> = entries
                .into_iter()
                .map(|(n, d)| (n, Bytes::from(d)))
                .collect();

            let serialized = serialize_branch_results(&typed, &JsonCodec).unwrap();
            let deserialized: NamedBranchResults = serde_json::from_slice(&serialized).unwrap();

            prop_assert_eq!(deserialized.as_slice(), typed.as_slice());
        }
    }

    // Property 11: `get_resume_input` always errors for non-InProgress states.
    proptest! {
        #[test]
        fn non_in_progress_always_errors(
            variant in 0..3u8,
            error_msg in "[a-zA-Z0-9 ]{0,32}",
            reason in prop::option::of("[a-zA-Z0-9 ]{0,32}"),
            cancelled_by in prop::option::of("[a-zA-Z0-9 ]{0,32}"),
            output_data in proptest::collection::vec(any::<u8>(), 0..32),
        ) {
            let mut snapshot = WorkflowSnapshot::new("inst".into(), "hash".into());
            match variant {
                0 => snapshot.mark_completed(Bytes::from(output_data)),
                1 => snapshot.mark_failed(error_msg),
                _ => snapshot.mark_cancelled(reason, cancelled_by, None),
            }

            let result = get_resume_input(&snapshot);
            prop_assert!(result.is_err(), "Expected Err for non-InProgress state");
        }
    }

    // Property 12: InProgress with no completed tasks returns the initial input.
    proptest! {
        #[test]
        fn in_progress_empty_tasks_returns_initial_input(
            input_data in proptest::collection::vec(any::<u8>(), 1..64),
        ) {
            let initial = Bytes::from(input_data);
            let snapshot = WorkflowSnapshot::with_initial_input(
                "inst".into(),
                "hash".into(),
                initial.clone(),
            );

            let result = get_resume_input(&snapshot).unwrap();
            prop_assert_eq!(result, initial);
        }
    }
}

// ── Branch tests ──────────────────────────────────────────────────────

fn branch_node(
    id: &str,
    key: &'static str,
    branches: std::collections::HashMap<String, Box<WorkflowContinuation>>,
    default: Option<Box<WorkflowContinuation>>,
    next: Option<Box<WorkflowContinuation>>,
) -> WorkflowContinuation {
    let c = codec();
    let key_task = to_core_task(
        id,
        move |_input: serde_json::Value| async move { Ok(key.to_string()) },
        c,
    );
    WorkflowContinuation::Branch {
        id: id.to_string(),
        key_fn: Some(key_task),
        branches,
        default,
        next,
    }
}

#[test]
fn test_sync_branch_selects_correct_branch() {
    let billing = stub_node("handle_billing", None);
    let tech = stub_node("handle_tech", None);

    let mut branches = std::collections::HashMap::new();
    branches.insert("billing".to_string(), Box::new(billing));
    branches.insert("tech".to_string(), Box::new(tech));

    let branch = branch_node("route", "billing", branches, None, None);

    let input = encode_u32(10);
    let callback = |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val = decode_u32(&input);
        match id {
            "route::key_fn" => Ok(Bytes::from(serde_json::to_vec("billing").unwrap())),
            "handle_billing" => Ok(encode_u32(val * 100)),
            "handle_tech" => Ok(encode_u32(val + 1)),
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&branch, input, &callback, &JsonCodec).unwrap();
    let envelope: serde_json::Value = serde_json::from_slice(&result).unwrap();
    assert_eq!(envelope["branch"], "billing");
    assert_eq!(envelope["result"], 1000); // 10 * 100
}

#[test]
fn test_sync_branch_uses_default() {
    let billing = stub_node("handle_billing", None);
    let fallback = stub_node("handle_fallback", None);

    let mut branches = std::collections::HashMap::new();
    branches.insert("billing".to_string(), Box::new(billing));

    let branch = branch_node(
        "route",
        "unknown_key",
        branches,
        Some(Box::new(fallback)),
        None,
    );

    let input = encode_u32(5);
    let callback = |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val = decode_u32(&input);
        match id {
            "route::key_fn" => Ok(Bytes::from(serde_json::to_vec("unknown_key").unwrap())),
            "handle_billing" => Ok(encode_u32(val * 100)),
            "handle_fallback" => Ok(encode_u32(val + 999)),
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&branch, input, &callback, &JsonCodec).unwrap();
    let envelope: serde_json::Value = serde_json::from_slice(&result).unwrap();
    assert_eq!(envelope["branch"], "unknown_key");
    assert_eq!(envelope["result"], 1004); // 5 + 999
}

#[test]
fn test_sync_branch_key_not_found() {
    let billing = stub_node("handle_billing", None);

    let mut branches = std::collections::HashMap::new();
    branches.insert("billing".to_string(), Box::new(billing));

    let branch = branch_node("route", "nonexistent", branches, None, None);

    let input = encode_u32(5);
    let callback = |id: &str, _input: Bytes| -> Result<Bytes, BoxError> {
        match id {
            "route::key_fn" => Ok(Bytes::from(serde_json::to_vec("nonexistent").unwrap())),
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let err = execute_continuation_sync(&branch, input, &callback, &JsonCodec).unwrap_err();
    let err_str = err.to_string();
    assert!(
        err_str.contains("no branch matches key 'nonexistent'"),
        "Error was: {err_str}"
    );
}

#[test]
fn test_sync_branch_then_next() {
    let billing = stub_node("handle_billing", None);

    let mut branches = std::collections::HashMap::new();
    branches.insert("billing".to_string(), Box::new(billing));

    let next = stub_node("finalize", None);
    let branch = branch_node("route", "billing", branches, None, Some(Box::new(next)));

    let input = encode_u32(10);
    let callback = |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        match id {
            "route::key_fn" => Ok(Bytes::from(serde_json::to_vec("billing").unwrap())),
            "handle_billing" => {
                let val = decode_u32(&input);
                Ok(encode_u32(val * 2))
            }
            "finalize" => {
                // Receives BranchEnvelope JSON
                let envelope: serde_json::Value = serde_json::from_slice(&input).unwrap();
                assert_eq!(envelope["branch"], "billing");
                #[allow(clippy::cast_possible_truncation)]
                let inner = envelope["result"].as_u64().unwrap() as u32;
                Ok(encode_u32(inner + 1))
            }
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&branch, input, &callback, &JsonCodec).unwrap();
    // handle_billing: 10*2=20, finalize: 20+1=21
    assert_eq!(decode_u32(&result), 21);
}

// Async and checkpointing branch tests are covered by the distributed runner tests
// in sayiir-runtime/src/runner/distributed.rs (test_route_*).

// ========================================================================
// Loop helpers
// ========================================================================

fn loop_body_task(
    id: &str,
    f: impl Fn(
        u32,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<Output = Result<sayiir_core::LoopResult<u32>, BoxError>> + Send,
        >,
    > + Send
    + Sync
    + 'static,
) -> WorkflowContinuation {
    let c = codec();
    WorkflowContinuation::Task {
        id: id.to_string(),
        func: Some(to_core_task(id, f, c)),
        timeout: None,
        retry_policy: None,
        version: None,
        next: None,
    }
}

// ========================================================================
// Loop tests — checkpointing (resume from checkpoint)
// ========================================================================

#[tokio::test]
async fn test_checkpointing_loop_basic() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(3);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let body = stub_node("countdown", None);
    let cont = WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 10,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::Fail,
        next: None,
    };

    let callback = |_id: &str, input: Bytes| async move {
        let n = decode_u32(&input);
        if n == 0 {
            Ok(encode_loop_done(0))
        } else {
            Ok(encode_loop_again(n - 1))
        }
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    assert_eq!(decode_u32(&result), 0);
    // Loop iteration counter should be cleared after completion
    assert_eq!(snapshot.loop_iteration("loop_0"), 0);
}

#[tokio::test]
async fn test_checkpointing_loop_resumes_from_iteration() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(5);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());

    // Simulate: 2 iterations already completed. Next input should be 3 (5→4→3).
    snapshot.set_loop_iteration("loop_0", 2);
    backend.save_snapshot(&snapshot).await.unwrap();

    let call_count = Arc::new(AtomicU32::new(0));
    let cc = call_count.clone();

    let body = stub_node("countdown", None);
    let cont = WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 10,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::Fail,
        next: None,
    };

    let callback = move |_id: &str, input: Bytes| {
        let cc = cc.clone();
        async move {
            cc.fetch_add(1, Ordering::SeqCst);
            let n = decode_u32(&input);
            if n == 0 {
                Ok(encode_loop_done(0))
            } else {
                Ok(encode_loop_again(n - 1))
            }
        }
    };

    // Resume with input 3 (what iteration 2 would have produced)
    let resume_input = encode_u32(3);

    let result = execute_continuation_with_checkpointing(
        &cont,
        resume_input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    assert_eq!(decode_u32(&result), 0);
    // Should have run 4 body executions (3→2→1→0 → Done)
    assert_eq!(call_count.load(Ordering::SeqCst), 4);
    // Loop iteration counter should be cleared after completion
    assert_eq!(snapshot.loop_iteration("loop_0"), 0);
}

// ========================================================================
// Loop tests — sync
// ========================================================================

fn encode_loop_again(val: u32) -> Bytes {
    sayiir_core::codec::encode_loop_envelope(
        sayiir_core::codec::LoopDecision::Again,
        &serde_json::to_vec(&val).unwrap(),
    )
}

fn encode_loop_done(val: u32) -> Bytes {
    sayiir_core::codec::encode_loop_envelope(
        sayiir_core::codec::LoopDecision::Done,
        &serde_json::to_vec(&val).unwrap(),
    )
}

fn loop_node(
    body_id: &str,
    max_iterations: u32,
    on_max: sayiir_core::workflow::MaxIterationsPolicy,
    next: Option<Box<WorkflowContinuation>>,
) -> WorkflowContinuation {
    WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(stub_node(body_id, None)),
        max_iterations,
        on_max,
        next: next.map(Into::into),
    }
}

#[test]
fn test_sync_loop_done_immediately() {
    use sayiir_core::workflow::MaxIterationsPolicy;

    let cont = loop_node("body", 10, MaxIterationsPolicy::Fail, None);
    let input = encode_u32(42);

    let callback = |_id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val = decode_u32(&input);
        Ok(encode_loop_done(val * 2))
    };

    let result = execute_continuation_sync(&cont, input, &callback, &JsonCodec).unwrap();
    assert_eq!(decode_u32(&result), 84);
}

#[test]
fn test_sync_loop_three_iterations() {
    use sayiir_core::workflow::MaxIterationsPolicy;

    let cont = loop_node("countdown", 10, MaxIterationsPolicy::Fail, None);
    let input = encode_u32(3);

    let callback = |_id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let n = decode_u32(&input);
        if n <= 0 {
            Ok(encode_loop_done(0))
        } else {
            Ok(encode_loop_again(n - 1))
        }
    };

    let result = execute_continuation_sync(&cont, input, &callback, &JsonCodec).unwrap();
    assert_eq!(decode_u32(&result), 0);
}

#[test]
fn test_sync_loop_max_iterations_fail() {
    use sayiir_core::workflow::MaxIterationsPolicy;

    let cont = loop_node("always_again", 3, MaxIterationsPolicy::Fail, None);
    let input = encode_u32(0);

    let callback = |_id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let n = decode_u32(&input);
        Ok(encode_loop_again(n + 1))
    };

    let err = execute_continuation_sync(&cont, input, &callback, &JsonCodec).unwrap_err();
    assert!(
        err.to_string().contains("max"),
        "expected MaxIterationsExceeded, got: {err}"
    );
}

#[test]
fn test_sync_loop_max_iterations_exit_with_last() {
    use sayiir_core::workflow::MaxIterationsPolicy;

    let cont = loop_node("always_again", 3, MaxIterationsPolicy::ExitWithLast, None);
    let input = encode_u32(0);

    let callback = |_id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let n = decode_u32(&input);
        Ok(encode_loop_again(n + 1))
    };

    let result = execute_continuation_sync(&cont, input, &callback, &JsonCodec).unwrap();
    // 0 → again(1) → again(2) → again(3) → max reached, exit with 3
    assert_eq!(decode_u32(&result), 3);
}

#[test]
fn test_sync_loop_in_chain() {
    use sayiir_core::workflow::MaxIterationsPolicy;

    let double = stub_node("double", None);
    let cont = loop_node(
        "countdown",
        10,
        MaxIterationsPolicy::Fail,
        Some(Box::new(double)),
    );
    let input = encode_u32(3);

    let callback = |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val = decode_u32(&input);
        match id {
            "countdown" => {
                if val <= 0 {
                    Ok(encode_loop_done(0))
                } else {
                    Ok(encode_loop_again(val - 1))
                }
            }
            "double" => Ok(encode_u32(val * 2)),
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&cont, input, &callback, &JsonCodec).unwrap();
    // 3 → 2 → 1 → 0 → done(0) → double → 0
    assert_eq!(decode_u32(&result), 0);
}

// ========================================================================
// Loop tests — async
// ========================================================================

#[tokio::test]
async fn test_async_loop_done_immediately() {
    use sayiir_core::LoopResult;

    let body = loop_body_task("body", |val| {
        Box::pin(async move { Ok(LoopResult::Done(val * 2)) })
    });
    let cont = WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 10,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::Fail,
        next: None,
    };
    let input = encode_u32(42);

    let result = execute_continuation_async(&cont, input, &JsonCodec)
        .await
        .unwrap();
    assert_eq!(decode_u32(&result), 84);
}

#[tokio::test]
async fn test_async_loop_max_iterations_fail() {
    use sayiir_core::LoopResult;

    let body = loop_body_task("always_again", |val| {
        Box::pin(async move { Ok(LoopResult::Again(val + 1)) })
    });
    let cont = WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 3,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::Fail,
        next: None,
    };
    let input = encode_u32(0);

    let err = execute_continuation_async(&cont, input, &JsonCodec)
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("max"),
        "expected MaxIterationsExceeded, got: {err}"
    );
}

// ========================================================================
// Loop inside fork branch — async
// ========================================================================

#[tokio::test]
async fn test_async_loop_inside_fork_branch() {
    use sayiir_core::LoopResult;
    use sayiir_core::task::{BranchOutputs, to_heterogeneous_join_task};

    // Branch A: a loop that counts down from input to 0
    let loop_body_a = loop_body_task("countdown", |n| {
        Box::pin(async move {
            if n == 0 {
                Ok(LoopResult::Done(100u32))
            } else {
                Ok(LoopResult::Again(n - 1))
            }
        })
    });
    let branch_a = Arc::new(WorkflowContinuation::Loop {
        id: "loop_a".into(),
        body: Box::new(loop_body_a),
        max_iterations: 10,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::Fail,
        next: None,
    });

    // Branch B: simple doubler
    let branch_b = Arc::new(task_node("double", |x: u32| async move { Ok(x * 2) }, None));

    // Join sums both branch results
    let join_fn = to_heterogeneous_join_task(
        "join",
        |outputs: BranchOutputs<JsonCodec>| async move {
            let a: u32 = outputs.get_by_id("loop_a")?;
            let b: u32 = outputs.get_by_id("double")?;
            Ok(a + b)
        },
        codec(),
    );
    let join_cont = WorkflowContinuation::Task {
        id: "join".to_string(),
        func: Some(join_fn),
        timeout: None,
        retry_policy: None,
        version: None,
        next: None,
    };

    let fork = WorkflowContinuation::Fork {
        id: "fork".into(),
        branches: vec![branch_a, branch_b].into_boxed_slice(),
        join: Some(Box::new(join_cont)),
    };
    let input = encode_u32(3);

    let result = execute_continuation_async(&fork, input, &JsonCodec)
        .await
        .unwrap();
    // loop_a: countdown 3→2→1→0 → Done(100), double: 3*2=6, join: 100+6=106
    assert_eq!(decode_u32(&result), 106);
}

// ========================================================================
// Loop tests — async (additional coverage)
// ========================================================================

#[tokio::test]
async fn test_async_loop_three_iterations() {
    use sayiir_core::LoopResult;

    let body = loop_body_task("countdown", |n| {
        Box::pin(async move {
            if n == 0 {
                Ok(LoopResult::Done(n))
            } else {
                Ok(LoopResult::Again(n - 1))
            }
        })
    });
    let cont = WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 10,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::Fail,
        next: None,
    };
    let input = encode_u32(3);

    let result = execute_continuation_async(&cont, input, &JsonCodec)
        .await
        .unwrap();
    assert_eq!(decode_u32(&result), 0);
}

#[tokio::test]
async fn test_async_loop_exit_with_last() {
    use sayiir_core::LoopResult;

    let body = loop_body_task("always_again", |val| {
        Box::pin(async move { Ok(LoopResult::Again(val + 1)) })
    });
    let cont = WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 3,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::ExitWithLast,
        next: None,
    };
    let input = encode_u32(0);

    let result = execute_continuation_async(&cont, input, &JsonCodec)
        .await
        .unwrap();
    // 0 → again(1) → again(2) → again(3) → max reached, exit with 3
    assert_eq!(decode_u32(&result), 3);
}

#[tokio::test]
async fn test_async_loop_in_chain() {
    use sayiir_core::LoopResult;

    let double = task_node("double", |x: u32| async move { Ok(x * 2) }, None);
    let body = loop_body_task("countdown", |n| {
        Box::pin(async move {
            if n == 0 {
                Ok(LoopResult::Done(10u32))
            } else {
                Ok(LoopResult::Again(n - 1))
            }
        })
    });
    let cont = WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 10,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::Fail,
        next: Some(Box::new(double).into()),
    };
    let input = encode_u32(3);

    let result = execute_continuation_async(&cont, input, &JsonCodec)
        .await
        .unwrap();
    // 3→2→1→0 → Done(10) → double → 20
    assert_eq!(decode_u32(&result), 20);
}

// ========================================================================
// Loop tests — checkpointing (additional coverage)
// ========================================================================

#[tokio::test]
async fn test_checkpointing_loop_caches_result_on_exit() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(2);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let body = stub_node("countdown", None);
    let cont = WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 10,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::Fail,
        next: None,
    };

    let callback = |_id: &str, input: Bytes| async move {
        let n = decode_u32(&input);
        if n == 0 {
            Ok(encode_loop_done(0))
        } else {
            Ok(encode_loop_again(n - 1))
        }
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    assert_eq!(decode_u32(&result), 0);

    // The loop node itself should have a cached result in the snapshot.
    let cached = snapshot.get_task_result("loop_0");
    assert!(cached.is_some(), "loop node should be cached after exit");
    assert_eq!(decode_u32(&cached.unwrap().output), 0);
}

#[tokio::test]
async fn test_checkpointing_loop_short_circuits_when_cached() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(99);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());

    // Pre-cache a result for the loop node.
    let cached_output = encode_u32(42);
    snapshot.mark_task_completed("loop_0".into(), cached_output.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let body = stub_node("body", None);
    let cont = WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 10,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::Fail,
        next: None,
    };

    let call_count = Arc::new(AtomicU32::new(0));
    let cc = call_count.clone();
    let callback = move |_id: &str, _input: Bytes| {
        let cc = cc.clone();
        async move {
            cc.fetch_add(1, Ordering::SeqCst);
            Ok(encode_loop_done(0))
        }
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    // Should return the cached result without executing any body tasks.
    assert_eq!(decode_u32(&result), 42);
    assert_eq!(call_count.load(Ordering::SeqCst), 0);
}

#[tokio::test]
async fn test_checkpointing_loop_exit_with_last() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(0);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let body = stub_node("always_again", None);
    let cont = WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 3,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::ExitWithLast,
        next: None,
    };

    let callback = |_id: &str, input: Bytes| async move {
        let n = decode_u32(&input);
        Ok(encode_loop_again(n + 1))
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    // 0 → again(1) → again(2) → again(3) → max reached, exit with 3
    assert_eq!(decode_u32(&result), 3);

    // Should be cached under the loop node.
    let cached = snapshot.get_task_result("loop_0");
    assert!(
        cached.is_some(),
        "loop node should be cached after exit_with_last"
    );
    assert_eq!(decode_u32(&cached.unwrap().output), 3);

    // Iteration counter should be cleared.
    assert_eq!(snapshot.loop_iteration("loop_0"), 0);
}

#[tokio::test]
async fn test_checkpointing_loop_in_chain() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(2);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let double = stub_node("double", None);
    let body = stub_node("countdown", None);
    let cont = WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 10,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::Fail,
        next: Some(Box::new(double).into()),
    };

    let callback = |id: &str, input: Bytes| {
        let id = id.to_string();
        async move {
            let val = decode_u32(&input);
            match id.as_str() {
                "countdown" => {
                    if val == 0 {
                        Ok(encode_loop_done(10))
                    } else {
                        Ok(encode_loop_again(val - 1))
                    }
                }
                "double" => Ok(encode_u32(val * 2)),
                _ => Err(format!("Unknown task: {id}").into()),
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    // 2→1→0 → Done(10) → double → 20
    assert_eq!(decode_u32(&result), 20);

    // Loop node should be cached (even though there's a next step).
    assert!(snapshot.get_task_result("loop_0").is_some());
}

#[tokio::test]
async fn test_checkpointing_loop_inside_fork_branch() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(2);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let body = stub_node("countdown", None);
    let loop_branch = Arc::new(WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 10,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::Fail,
        next: None,
    });

    let passthrough = Arc::new(stub_node("passthrough", None));

    let fork = WorkflowContinuation::Fork {
        id: "fork_0".into(),
        branches: vec![loop_branch, passthrough].into_boxed_slice(),
        join: None,
    };

    let callback = |id: &str, input: Bytes| {
        let id = id.to_string();
        async move {
            let val = decode_u32(&input);
            match id.as_str() {
                "countdown" => {
                    if val == 0 {
                        Ok(encode_loop_done(0))
                    } else {
                        Ok(encode_loop_again(val - 1))
                    }
                }
                "passthrough" => Ok(encode_u32(val)),
                _ => Err(format!("Unknown task: {id}").into()),
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &fork,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await;

    // Fork with no join returns the named results envelope.
    // Just verify it doesn't error — the loop inside a branch executes correctly.
    assert!(
        result.is_ok(),
        "loop inside fork branch should succeed: {:?}",
        result.err()
    );

    // The loop node should be cached in the snapshot.
    assert!(
        snapshot.get_task_result("loop_0").is_some(),
        "loop inside fork branch should be cached"
    );
}

#[tokio::test]
async fn test_checkpointing_loop_iteration_counter_persisted() {
    let backend = InMemoryBackend::new();
    let input = encode_u32(5);

    let mut snapshot =
        WorkflowSnapshot::with_initial_input("inst-1".into(), "hash-1".into(), input.clone());
    backend.save_snapshot(&snapshot).await.unwrap();

    let body = stub_node("countdown", None);
    let cont = WorkflowContinuation::Loop {
        id: "loop_0".into(),
        body: Box::new(body),
        max_iterations: 10,
        on_max: sayiir_core::workflow::MaxIterationsPolicy::Fail,
        next: None,
    };

    let call_count = Arc::new(AtomicU32::new(0));
    let cc = call_count.clone();

    let callback = move |_id: &str, input: Bytes| {
        let cc = cc.clone();
        async move {
            let n = decode_u32(&input);
            cc.fetch_add(1, Ordering::SeqCst);
            if n == 0 {
                Ok(encode_loop_done(0))
            } else {
                Ok(encode_loop_again(n - 1))
            }
        }
    };

    let result = execute_continuation_with_checkpointing(
        &cont,
        input,
        &mut snapshot,
        &backend,
        &callback,
        &JsonCodec,
    )
    .await
    .unwrap();

    assert_eq!(decode_u32(&result), 0);
    assert_eq!(call_count.load(Ordering::SeqCst), 6); // 5→4→3→2→1→0

    // After completion, the backend's snapshot should also have the cached result.
    let persisted = backend.load_snapshot("inst-1").await.unwrap();
    assert!(
        persisted.get_task_result("loop_0").is_some(),
        "loop result should be persisted to backend"
    );
    assert_eq!(persisted.loop_iteration("loop_0"), 0);
}

// ========================================================================
// Child Workflow tests
// ========================================================================

#[test]
fn test_sync_child_workflow_basic() {
    // parent: add_one → child(double → add_ten)
    let child_double = stub_node("double", None);
    let child_add_ten = stub_node("add_ten", Some(Box::new(child_double)));
    let child_cont = Arc::new(child_add_ten);

    let child_wf = WorkflowContinuation::ChildWorkflow {
        id: "child_0".into(),
        child: child_cont,
        next: None,
    };
    let parent = stub_node("add_one", Some(Box::new(child_wf)));

    let input = encode_u32(5);
    let callback = |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val = decode_u32(&input);
        match id {
            "add_one" => Ok(encode_u32(val + 1)),
            "add_ten" => Ok(encode_u32(val + 10)),
            "double" => Ok(encode_u32(val * 2)),
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&parent, input, &callback, &JsonCodec).unwrap();
    // 5 + 1 = 6, then child: 6 + 10 = 16, 16 * 2 = 32
    assert_eq!(decode_u32(&result), 32);
}

#[test]
fn test_sync_child_workflow_passes_output() {
    // parent: child(add_one) → double
    let child_add_one = Arc::new(stub_node("add_one", None));
    let double = stub_node("double", None);

    let child_wf = WorkflowContinuation::ChildWorkflow {
        id: "child_0".into(),
        child: child_add_one,
        next: Some(Box::new(double)),
    };

    let input = encode_u32(10);
    let callback = |id: &str, input: Bytes| -> Result<Bytes, BoxError> {
        let val = decode_u32(&input);
        match id {
            "add_one" => Ok(encode_u32(val + 1)),
            "double" => Ok(encode_u32(val * 2)),
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&child_wf, input, &callback, &JsonCodec).unwrap();
    // child: 10 + 1 = 11, then 11 * 2 = 22
    assert_eq!(decode_u32(&result), 22);
}

#[test]
fn test_sync_child_workflow_failure_propagates() {
    let child_fail = Arc::new(stub_node("fail_task", None));

    let child_wf = WorkflowContinuation::ChildWorkflow {
        id: "child_0".into(),
        child: child_fail,
        next: None,
    };

    let input = encode_u32(1);
    let callback = |id: &str, _input: Bytes| -> Result<Bytes, BoxError> {
        match id {
            "fail_task" => Err("child task failed".into()),
            _ => Err(format!("Unknown task: {id}").into()),
        }
    };

    let result = execute_continuation_sync(&child_wf, input, &callback, &JsonCodec);
    assert!(result.is_err());
}