aws-durable-execution-sdk 0.2.0

Rust SDK for AWS Lambda Durable Functions
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
//! Error types for durable operations.
//!
//! All error types are hand-written (no `thiserror`), `#[non_exhaustive]`,
//! and implement [`std::error::Error`]. Use the `kind()` accessor pattern
//! for matching error variants, and [`source()`](std::error::Error::source)
//! to reach the underlying cause.
//!
//! # `Display` convention
//!
//! Each layer's `Display` writes **one frame**: its own description, never
//! its source's text. Walking [`source()`](std::error::Error::source)
//! therefore never repeats text. To print the whole chain in one line, use
//! the alternate form `{:#}`, which walks the source chain from that layer
//! down. The message recorded on the wire is the message of the operation
//! failure that the error propagates, when it propagates one, and is
//! otherwise the chain's frames joined with `": "`, without the frame of a
//! [`TypedError`], whose type name the record carries as its type (see
//! [`wire_message`]).
//!
//! # Kinds classify, `source()` carries
//!
//! The `*ErrorKind` enums are pure classification: empty variants are unit
//! variants, and variants that retain structural facts (an attempt count,
//! a failed index) are newtype variants wrapping a payload struct with
//! accessors. The escaping error that caused the failure is never
//! stringified into a kind: it is carried by the error struct and
//! returned from `source()`.

use std::error::Error;
use std::fmt;

/// The boxed source type every error struct carries.
///
/// The `Send + Sync` bounds are load-bearing: all public error types are
/// `Send + Sync` (asserted at compile time below), and a bare
/// `Box<dyn Error>` would silently revoke that.
pub(crate) type Source = Box<dyn Error + Send + Sync + 'static>;

/// Maximum number of source-chain links walked when extracting wire
/// identity (the `TypedError` type name, `error_data`, `stack_trace`)
/// from an escaping error.
///
/// The walk reads the error itself and up to 10 causes, as the JS SDK
/// does: it checks the error's own data, then up to 10 causes. So a
/// payload survives the same nesting depth across SDKs.
const CHAIN_WALK_LIMIT: usize = 11;

/// Writes `frame` followed by every frame of `source`'s chain, separated
/// by `": "`.
///
/// This is the full-chain renderer: every alternate (`{:#}`) `Display`
/// implementation in this module funnels through it, and it writes every
/// frame, a [`TypedError`]'s type name included. The recorded message
/// uses [`chain_string`] instead, which omits the type names.
pub(crate) fn write_chain(
    f: &mut fmt::Formatter<'_>,
    frame: &dyn fmt::Display,
    mut source: Option<&(dyn Error + 'static)>,
) -> fmt::Result {
    write!(f, "{frame}")?;
    while let Some(s) = source {
        write!(f, ": {s}")?;
        source = s.source();
    }
    Ok(())
}

/// Flattens an error's chain into one line for a recorded message: the
/// `Display` frame of every error in the chain, in source order, joined
/// with `": "`, except the frame of each [`TypedError`].
///
/// A `TypedError`'s frame is its type name, which the record carries as
/// its `ErrorType`, so the message holds the wrapped error's text alone,
/// as JS records an error's `name` and `message` in separate fields.
/// `TypedError::with_type("PaymentError", "declined")` flattens to
/// `declined`. A `TypedError` always has a source, so the last frame of
/// a chain is never a `TypedError`'s and the result names every other
/// error.
pub(crate) fn chain_string(err: &(dyn Error + 'static)) -> String {
    let mut frames = Vec::new();
    let mut link = Some(err);
    while let Some(e) = link {
        if !e.is::<TypedError>() {
            frames.push(e.to_string());
        }
        link = e.source();
    }
    frames.join(": ")
}

/// The failure fields of a wire `ErrorObject`, as a named record.
///
/// Carries the four wire error fields: `error_type`, `error_message`,
/// `error_data`, and `stack_trace`. Reachable from a failed operation via
/// [`OperationError::wire`], and from a replayed failure's synthetic
/// source via [`ReplayedFailure::wire`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct WireError {
    error_type: Option<String>,
    error_message: Option<String>,
    error_data: Option<String>,
    stack_trace: Vec<String>,
}

impl WireError {
    /// Creates a wire error record from its type and message fields.
    pub(crate) fn new(
        error_type: Option<impl Into<String>>,
        error_message: Option<impl Into<String>>,
    ) -> Self {
        Self {
            error_type: error_type.map(Into::into),
            error_message: error_message.map(Into::into),
            error_data: None,
            stack_trace: Vec::new(),
        }
    }

    /// Sets the human-readable message.
    pub(crate) fn with_error_message(mut self, error_message: Option<impl Into<String>>) -> Self {
        self.error_message = error_message.map(Into::into);
        self
    }

    /// Sets the opaque `error_data` payload.
    pub(crate) fn with_error_data(mut self, error_data: Option<impl Into<String>>) -> Self {
        self.error_data = error_data.map(Into::into);
        self
    }

    /// Sets the stack trace frames.
    pub(crate) fn with_stack_trace(mut self, stack_trace: Vec<String>) -> Self {
        self.stack_trace = stack_trace;
        self
    }

    /// The wire `ErrorType`: the name of the error type that failed the
    /// operation, as recorded in the execution history.
    pub fn error_type(&self) -> Option<&str> {
        self.error_type.as_deref()
    }

    /// The wire `ErrorMessage`: the human-readable message.
    ///
    /// A failure that propagates another operation's failure records that
    /// operation's message. Any other failure records its error's chain,
    /// flattened into one line. Neither includes the name of a
    /// [`TypedError`], which the record carries as its type: a failure
    /// with `TypedError::with_type("PaymentError", "declined")` records the
    /// message `declined`.
    pub fn error_message(&self) -> Option<&str> {
        self.error_message.as_deref()
    }

    /// The wire `ErrorData`: an opaque payload attached to the failure.
    ///
    /// The SDK writes this field and passes it through boundaries, and
    /// **never dispatches on it**: the wire error fields can be supplied
    /// by an external caller (via `SendDurableExecutionCallbackFailure`),
    /// so typed reconstruction from an attacker-influenced payload is
    /// decode surface the SDK refuses to have. Interpret it yourself if
    /// you know its shape. The one record the SDK decodes is its own
    /// `select_ok` `AllFailed` aggregate, whose `error_data` is
    /// SDK-authored (never pass-through) and holds the losers' recorded
    /// failure fields; combinator replay decodes it defensively and only
    /// stores and re-exposes the decoded strings, never branching on them.
    pub fn error_data(&self) -> Option<&str> {
        self.error_data.as_deref()
    }

    /// The wire `StackTrace` frames, stored and exposed verbatim.
    ///
    /// The SDK never captures frames. This field exposes the frames a
    /// recorded record already carries: an external callback failure, a
    /// remote invoke, or a replayed record. A failure the SDK records
    /// live carries frames only when an error in its source chain
    /// already carried them. A Rust [`std::backtrace::Backtrace`] cannot
    /// be reconstructed from recorded frames, so these are
    /// store-and-expose only.
    pub fn stack_trace(&self) -> &[String] {
        &self.stack_trace
    }

    /// Converts this record into the SDK `ErrorObject` wire shape
    /// (internal).
    pub(crate) fn to_error_object(&self) -> aws_sdk_lambda::types::ErrorObject {
        let mut builder = aws_sdk_lambda::types::ErrorObject::builder();
        if let Some(t) = self.error_type() {
            builder = builder.error_type(t);
        }
        if let Some(m) = self.error_message() {
            builder = builder.error_message(m);
        }
        if let Some(d) = self.error_data() {
            builder = builder.error_data(d);
        }
        for frame in self.stack_trace() {
            builder = builder.stack_trace(frame);
        }
        builder.build()
    }
}

impl fmt::Display for WireError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (self.error_type.as_deref(), self.error_message.as_deref()) {
            (Some(t), Some(m)) => write!(f, "{t}: {m}"),
            (None, Some(m)) => write!(f, "{m}"),
            (Some(t), None) => write!(f, "{t}"),
            (None, None) => write!(f, "unknown error"),
        }
    }
}

/// The synthetic source attached to an error rebuilt from a checkpointed
/// failure on replay.
///
/// On the live path an operation error's `source()` is the escaping error
/// itself; after a replay only the wire record survives, so `source()`
/// returns this type carrying the recorded `error_type` and
/// `error_message` (plus `error_data` and `stack_trace` when recorded).
/// Downcast to it to read the wire fields programmatically.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ReplayedFailure {
    wire: WireError,
}

impl ReplayedFailure {
    /// Creates a replayed failure from the recorded wire fields.
    pub(crate) fn new(wire: WireError) -> Self {
        Self { wire }
    }

    /// Boxes a replayed failure as an error source.
    pub(crate) fn source_from(wire: WireError) -> Source {
        Box::new(Self::new(wire))
    }

    /// The recorded wire `ErrorType`.
    pub fn error_type(&self) -> Option<&str> {
        self.wire.error_type()
    }

    /// The recorded wire `ErrorMessage`.
    pub fn error_message(&self) -> Option<&str> {
        self.wire.error_message()
    }

    /// The full recorded wire failure record.
    pub fn wire(&self) -> &WireError {
        &self.wire
    }
}

impl fmt::Display for ReplayedFailure {
    /// Writes the recorded message as this frame.
    ///
    /// The recorded `error_type` is deliberately NOT folded into the
    /// text: it is data, answered by [`error_type()`](Self::error_type),
    /// so a failure observed live and the same failure observed on replay
    /// render identically.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (self.wire.error_message(), self.wire.error_type()) {
            (Some(m), _) => write!(f, "{m}"),
            (None, Some(t)) => write!(f, "{t}"),
            (None, None) => write!(f, "unknown error"),
        }
    }
}

impl Error for ReplayedFailure {}

/// Crate-internal error that adds one context frame on top of a cause,
/// without stringifying the cause into the frame.
#[derive(Debug)]
pub(crate) struct ContextualError {
    context: String,
    source: Source,
}

impl ContextualError {
    /// Boxes a context frame over `source` as an error source.
    pub(crate) fn source_from(context: impl Into<String>, source: impl Into<Source>) -> Source {
        Box::new(Self {
            context: context.into(),
            source: source.into(),
        })
    }
}

impl fmt::Display for ContextualError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write_chain(f, &self.context, self.source())
        } else {
            write!(f, "{}", self.context)
        }
    }
}

impl Error for ContextualError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&*self.source as &(dyn Error + 'static))
    }
}

/// An error wrapper that records its inner error's concrete type name for
/// the wire `ErrorType`.
///
/// Rust erases an error's concrete type the moment it is boxed into a
/// [`BoxError`](crate::BoxError): inside the SDK there is no runtime name
/// to recover, so an unwrapped error is recorded with the generic type
/// `"Error"`. Wrapping the error at the one place its type is still known
/// (its creation site) is the explicit alternative:
///
/// ```
/// use aws_durable_execution_sdk::{BoxError, TypedError};
///
/// #[derive(Debug)]
/// struct PaymentDeclined;
/// # impl std::fmt::Display for PaymentDeclined {
/// #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// #         write!(f, "payment declined")
/// #     }
/// # }
/// # impl std::error::Error for PaymentDeclined {}
///
/// let err: BoxError = Box::new(TypedError::new(PaymentDeclined));
/// // The step that fails with `err` records ErrorType "PaymentDeclined".
/// ```
///
/// [`with_error_data`](Self::with_error_data) attaches an opaque payload,
/// recorded as the wire `ErrorData`. The SDK never parses it, and it
/// never appears in the recorded message:
///
/// ```
/// use aws_durable_execution_sdk::TypedError;
///
/// let err = TypedError::with_type("PaymentError", "declined").with_error_data(r#"{"code":42}"#);
/// assert_eq!(err.error_type(), "PaymentError");
/// assert_eq!(err.error_data(), Some(r#"{"code":42}"#));
/// ```
///
/// The wrapper is one chain layer: its `Display` frame is the recorded
/// type name, and its [`source()`](std::error::Error::source) is the
/// wrapped error itself, so the concrete error stays reachable through
/// the ordinary `source()` downcast walk, and the alternate form `{:#}`
/// reads `"TransientError: temporary failure"`.
///
/// The recorded message never includes the type name, because the record
/// carries it as its type, as JS records an error's `name` and `message`
/// apart. A failure with `TypedError::with_type("PaymentError", "declined")`
/// records the type `PaymentError` and the message `declined`. When the
/// wrapped error propagates another operation's failure, the message is
/// that failure's recorded message.
#[derive(Debug)]
#[non_exhaustive]
pub struct TypedError {
    error_type: String,
    inner: Source,
    error_data: Option<String>,
}

impl TypedError {
    /// Wraps `err`, recording its concrete type's name (without module
    /// path) as the wire `ErrorType`.
    #[must_use]
    pub fn new<E: Error + Send + Sync + 'static>(err: E) -> Self {
        Self {
            error_type: short_type_name(std::any::type_name::<E>()),
            inner: Box::new(err),
            error_data: None,
        }
    }

    /// Wraps `err` under an explicitly chosen wire `ErrorType`.
    #[must_use]
    pub fn with_type(error_type: impl Into<String>, err: impl Into<Source>) -> Self {
        Self {
            error_type: error_type.into(),
            inner: err.into(),
            error_data: None,
        }
    }

    /// Attaches an opaque payload, recorded as the wire `ErrorData`.
    ///
    /// The SDK passes the payload through unparsed. It does not appear in
    /// this error's `Display` or in the recorded `ErrorMessage`.
    #[must_use]
    pub fn with_error_data(mut self, error_data: impl Into<String>) -> Self {
        self.error_data = Some(error_data.into());
        self
    }

    /// The payload attached with [`with_error_data`](Self::with_error_data),
    /// if any.
    pub fn error_data(&self) -> Option<&str> {
        self.error_data.as_deref()
    }

    /// The wire `ErrorType` recorded for this error.
    pub fn error_type(&self) -> &str {
        &self.error_type
    }

    /// The wrapped error.
    pub fn inner(&self) -> &(dyn Error + 'static) {
        &*self.inner
    }
}

impl fmt::Display for TypedError {
    /// Writes the recorded type name as this layer's frame; the wrapped
    /// error is the next frame in the chain.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write_chain(f, &self.error_type, self.source())
        } else {
            write!(f, "{}", self.error_type)
        }
    }
}

impl Error for TypedError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&*self.inner as &(dyn Error + 'static))
    }
}

/// Reduces `std::any::type_name` output to bare type names: every module
/// path segment is dropped, including inside generic arguments
/// (`a::B<c::D>` becomes `B<D>`).
fn short_type_name(full: &str) -> String {
    let mut result = String::with_capacity(full.len());
    let mut segment = String::new();
    for c in full.chars() {
        match c {
            ':' => segment.clear(),
            '<' | '>' | ',' | ' ' | '(' | ')' | '[' | ']' | '&' | ';' => {
                result.push_str(&segment);
                segment.clear();
                result.push(c);
            }
            _ => segment.push(c),
        }
    }
    result.push_str(&segment);
    result
}

/// Derives the wire failure record for an escaping error explicitly,
/// with no `Debug` scraping.
///
/// - `error_message` is the error's recorded message ([`wire_message`]):
///   the message of the first operation record its chain reaches through
///   the SDK's propagation carriers and [`TypedError`]s, else its
///   flattened source chain without the frames of [`TypedError`]s
///   ([`chain_string`]).
/// - `error_type` is taken from structured identity when the error *is*
///   one: an [`OperationError`] re-records its attached wire record's
///   type when it carries one (or a [`TypedError`]'s name from its
///   chain), falling back to its kind's registry name, so an explicitly
///   supplied user type survives re-recording across child-context and
///   map boundaries. A [`ReplayedFailure`] re-records its original type.
///   A plain user error has no recoverable type name in Rust (the
///   concrete type is erased when the caller boxes it), so it records
///   `fallback_type`.
/// - `error_data` is passed through from the first error in the source
///   chain (up to [`CHAIN_WALK_LIMIT`] links) that carries one: an
///   [`OperationError`] or [`ReplayedFailure`] whose record has data, or
///   a [`TypedError`] with [`TypedError::error_data`] set. So a payload
///   survives child-context and map boundaries. It is never synthesized
///   and never parsed.
/// - `stack_trace` is passed through from the first [`OperationError`] or
///   [`ReplayedFailure`] in the chain that carries frames. The SDK never
///   captures frames, so a chain with no recorded frames records none.
pub(crate) fn wire_error_for(err: &(dyn Error + 'static), fallback_type: &str) -> WireError {
    let error_type = if let Some(op) = err.downcast_ref::<OperationError>() {
        // An operation error's own recorded identity wins: the attached
        // wire record already names the user's type when one was
        // supplied, and a `TypedError` still in the chain names it
        // directly. Only an error with neither records its kind's
        // registry name.
        op.wire()
            .and_then(WireError::error_type)
            .map(str::to_owned)
            .or_else(|| typed_error_name(err))
            .unwrap_or_else(|| op.kind().wire_type_name().to_owned())
    } else if let Some(replayed) = err.downcast_ref::<ReplayedFailure>() {
        // Re-recording a replayed failure preserves its original type.
        replayed.error_type().unwrap_or(fallback_type).to_owned()
    } else {
        // A `TypedError` anywhere in the chain names the user's type
        // explicitly: the one non-erased source of a concrete name.
        typed_error_name(err).unwrap_or_else(|| fallback_type.to_owned())
    };
    wire_error_with_type(err, &error_type)
}

/// Walks the source chain (up to [`CHAIN_WALK_LIMIT`] links) for the first
/// [`TypedError`] and returns its recorded type name.
fn typed_error_name(err: &(dyn Error + 'static)) -> Option<String> {
    let mut link: Option<&(dyn Error + 'static)> = Some(err);
    for _ in 0..CHAIN_WALK_LIMIT {
        let e = link?;
        if let Some(typed) = e.downcast_ref::<TypedError>() {
            return Some(typed.error_type().to_owned());
        }
        link = e.source();
    }
    None
}

/// Like [`wire_error_for`], but with a caller-fixed wire `error_type`
/// (used where the type is a protocol discriminator, e.g. the combinator
/// replay markers). The message ([`wire_message`]) and the
/// `error_data`/`stack_trace` chain walk are identical.
pub(crate) fn wire_error_with_type(err: &(dyn Error + 'static), error_type: &str) -> WireError {
    let mut error_data = None;
    let mut stack_trace = Vec::new();
    let mut link: Option<&(dyn Error + 'static)> = Some(err);
    let mut walked = 0;
    while let Some(e) = link {
        if walked >= CHAIN_WALK_LIMIT {
            break;
        }
        if let Some(w) = wire_identity(e) {
            if error_data.is_none() {
                error_data = w.error_data().map(str::to_owned);
            }
            if stack_trace.is_empty() {
                stack_trace = w.stack_trace().to_vec();
            }
        } else if let Some(typed) = e.downcast_ref::<TypedError>()
            && error_data.is_none()
        {
            // A `TypedError` supplies data only; it carries no frames.
            error_data = typed.error_data().map(str::to_owned);
        }
        if error_data.is_some() && !stack_trace.is_empty() {
            break;
        }
        link = e.source();
        walked += 1;
    }

    WireError::new(Some(error_type), Some(wire_message(err)))
        .with_error_data(error_data)
        .with_stack_trace(stack_trace)
}

/// The recorded message of an escaping error.
///
/// An error that propagates another operation's failure records that
/// failure's recorded message, as JS does: the walk follows `source()`
/// through the SDK's propagation carriers ([`OperationError`] without a
/// record, the per-operation error structs, [`ChildFnError`],
/// [`ContextualError`] and [`TypedError`]) and returns the message of the
/// first record it reaches, an [`OperationError`] with a record or a
/// [`ReplayedFailure`], verbatim. It examines at most
/// [`CHAIN_WALK_LIMIT`] errors, counting `err`, and each [`TypedError`]
/// is one of them.
///
/// Every other case returns the flattened chain of `err`
/// ([`chain_string`]), which omits each [`TypedError`]'s type name: a
/// record without a message, which ends the walk, any other error on the
/// way (a serde error or a user wrapper, whose text the message keeps), a
/// carrier without a source, and a record past the limit.
pub(crate) fn wire_message(err: &(dyn Error + 'static)) -> String {
    let mut link = err;
    for _ in 0..CHAIN_WALK_LIMIT {
        if let Some(wire) = wire_identity(link) {
            return wire
                .error_message()
                .map_or_else(|| chain_string(err), str::to_owned);
        }
        if !is_propagation_carrier(link) {
            break;
        }
        match link.source() {
            Some(source) => link = source,
            None => break,
        }
    }
    chain_string(err)
}

/// Whether `err` only carries another error on its way to a record, so the
/// recorded-message walk follows its `source()`. An [`OperationError`]
/// with a record never reaches this check.
fn is_propagation_carrier(err: &(dyn Error + 'static)) -> bool {
    err.is::<OperationError>()
        || err.is::<StepError>()
        || err.is::<WaitError>()
        || err.is::<InvokeError>()
        || err.is::<CallbackError>()
        || err.is::<WaitForConditionError>()
        || err.is::<ChildContextError>()
        || err.is::<CombinatorError>()
        || err.is::<ChildFnError>()
        || err.is::<ContextualError>()
        || err.is::<TypedError>()
}

/// The error type of the fault that a retryable checkpoint failure records.
/// It ends the invocation, and the next invocation can recover. JS throws an
/// error of this class in the same case.
pub(crate) const CHECKPOINT_INVOCATION_FAILED_ERROR_TYPE: &str =
    "CheckpointUnrecoverableInvocationError";

/// The error type of the fault that a retryable serdes failure records. JS
/// throws an error of this class in the same case.
pub(crate) const SERDES_FAILED_ERROR_TYPE: &str = "SerdesFailedError";

/// The wire `ErrorType` recorded on the `FAILED` envelope when the
/// execution client fails permanently before the handler runs: a
/// non-retryable error of the bootstrap state read. It is the type JS
/// records for its `DurableExecutionClientError`.
pub(crate) const EXECUTION_CLIENT_ERROR_TYPE: &str = "DurableExecutionClientError";

/// The wire `ErrorType` recorded on the terminal `FAIL` an operation
/// persists when its result (or carried state) failed LOCAL serialization
/// before the outcome write (issue #43).
///
/// This type is the replay discriminator for the serialization
/// classification: the live path yields a `SerializationFailed`-kinded
/// error after persisting this record, and replay reconstructs the SAME
/// kind by matching this type, so a handler that branches on the kind
/// takes the same path live and replayed. It is a protocol discriminator
/// written via [`wire_error_with_type`], never derived from a user error's
/// own identity.
pub(crate) const SERIALIZATION_FAILED_ERROR_TYPE: &str = "SerializationError";

/// Builds the wire record a terminal `FAIL` carries when the operation's
/// result failed local serialization before its outcome write (issue #43).
///
/// The fixed [`SERIALIZATION_FAILED_ERROR_TYPE`] is what lets replay
/// reconstruct the serialization classification (see the constant's doc);
/// the message ([`wire_message`]) and the `error_data`/`stack_trace` chain
/// walk are the standard [`wire_error_with_type`] behavior.
pub(crate) fn serialization_failure_wire(err: &(dyn Error + 'static)) -> WireError {
    wire_error_with_type(err, SERIALIZATION_FAILED_ERROR_TYPE)
}

/// The wire `ErrorType` recorded on the terminal `FAIL` a
/// wait-for-condition operation persists when its wait strategy
/// exhausted (returned [`WaitDecision::Exhausted`]).
///
/// This type is the replay discriminator for the exhaustion
/// classification: the live path yields a
/// [`WaitForConditionErrorKind::MaxChecksExceeded`]-kinded error after
/// persisting this record, and replay reconstructs the SAME kind (with
/// the check count derived from the checkpoint record's attempt field)
/// by matching this type, so a handler that branches on the kind (or
/// reads [`MaxChecksExceeded::checks`]) takes the same path live and
/// replayed. It is a protocol discriminator written via
/// [`WireError::new`], never derived from a user error's own identity.
///
/// [`WaitDecision::Exhausted`]: crate::builders::wait_for_condition::WaitDecision::Exhausted
pub(crate) const WFC_EXHAUSTED_ERROR_TYPE: &str = "WaitForCondition.MaxChecksExceeded";

/// The wire `ErrorType` of the execution's `FAILED` record after a
/// non-retryable checkpoint failure. It is the type JS records for its
/// `CheckpointUnrecoverableExecutionError`. The SDK writes no further
/// update for any operation after the failure, so each operation's record
/// stays at the last update the service accepted.
pub(crate) const CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE: &str =
    "CheckpointUnrecoverableExecutionError";

/// Builds the execution's `FAILED` record after a non-retryable
/// checkpoint failure: [`CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE`] and the
/// message `[Unrecoverable Execution] Checkpoint failed: {m}`, as JS
/// writes. `{m}` is the record message of
/// [`client_error_record_message`](crate::client::client_error_record_message).
pub(crate) fn checkpoint_execution_failure_wire(
    err: &crate::client::ExecutionClientError,
) -> WireError {
    WireError::new(
        Some(CHECKPOINT_EXECUTION_FAILED_ERROR_TYPE),
        Some(format!(
            "[Unrecoverable Execution] Checkpoint failed: {}",
            crate::client::client_error_record_message(err)
        )),
    )
}

/// The message of the fault that a retryable checkpoint failure records:
/// `[Unrecoverable Invocation] Checkpoint failed: {m}`, as JS gives its
/// `CheckpointUnrecoverableInvocationError`. `{m}` is the record message
/// of [`client_error_record_message`](crate::client::client_error_record_message),
/// the text the non-retryable record of
/// [`checkpoint_execution_failure_wire`] uses.
pub(crate) fn checkpoint_invocation_failure_message(
    err: &crate::client::ExecutionClientError,
) -> String {
    format!(
        "[Unrecoverable Invocation] Checkpoint failed: {}",
        crate::client::client_error_record_message(err)
    )
}

/// Returns the wire record carried by `err`, when `err` is one of the
/// SDK's own wire-record-carrying types.
fn wire_identity<'a>(err: &'a (dyn Error + 'static)) -> Option<&'a WireError> {
    if let Some(op) = err.downcast_ref::<OperationError>() {
        return op.wire();
    }
    if let Some(replayed) = err.downcast_ref::<ReplayedFailure>() {
        return Some(replayed.wire());
    }
    None
}

/// The top-level error type returned by [`DurableFuture`](crate::DurableFuture).
///
/// Wraps a typed per-operation cause accessible via [`kind()`](Self::kind).
/// Match on the kind to determine the specific failure mode, and walk
/// [`source()`](std::error::Error::source) to reach the underlying cause:
/// on the live path that is the escaping error itself (downcastable to its
/// concrete type), and after a replay it is a [`ReplayedFailure`] carrying
/// the recorded wire fields.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::{OperationError, OperationErrorKind};
///
/// fn handle_error(err: &OperationError) {
///     match err.kind() {
///         OperationErrorKind::Step(step_err) => {
///             // The step's escaping error is reachable through source().
///             if let Some(cause) = std::error::Error::source(step_err) {
///                 tracing::error!(%cause, "step failed");
///             }
///         }
///         // `{:#}` prints the full chain; `{}` prints one frame.
///         _ => tracing::error!(error = format!("{err:#}"), "operation failed"),
///     }
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct OperationError {
    kind: OperationErrorKind,
    /// Boxed so the failure context does not widen every
    /// `Result<_, OperationError>` on the happy path.
    context: Option<Box<OperationContext>>,
}

/// The failure's wire context: the operation it belongs to and the wire
/// record it produced or replayed.
#[derive(Debug, Default)]
struct OperationContext {
    operation_id: Option<String>,
    status: Option<String>,
    wire: Option<WireError>,
}

impl OperationError {
    /// Returns the specific error kind for this operation failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use aws_durable_execution_sdk::{OperationError, OperationErrorKind, StepErrorKind};
    ///
    /// let err = OperationError::__test_error();
    /// if let OperationErrorKind::Step(step_err) = err.kind() {
    ///     assert!(matches!(step_err.kind(), StepErrorKind::ExecutionFailed { .. }));
    /// }
    /// ```
    pub fn kind(&self) -> &OperationErrorKind {
        &self.kind
    }

    /// The wire ID of the operation that failed, when known.
    pub fn operation_id(&self) -> Option<&str> {
        self.context.as_ref()?.operation_id.as_deref()
    }

    /// The operation's wire status (for example `FAILED` or `TIMED_OUT`),
    /// when known.
    pub fn status(&self) -> Option<&str> {
        self.context.as_ref()?.status.as_deref()
    }

    /// The wire failure record for this error, when one exists.
    ///
    /// On a replayed failure this is the record read back from the
    /// execution history; on a live failure it is the record the SDK
    /// wrote. `None` for errors that never reached the wire (for example
    /// a serialization failure before checkpointing).
    pub fn wire(&self) -> Option<&WireError> {
        self.context.as_ref()?.wire.as_ref()
    }

    /// Creates an `OperationError` from its kind (internal).
    pub(crate) fn from_kind(kind: OperationErrorKind) -> Self {
        Self {
            kind,
            context: None,
        }
    }

    /// Attaches the failing operation's wire ID and status (internal).
    pub(crate) fn with_operation(
        mut self,
        operation_id: impl Into<String>,
        status: impl Into<String>,
    ) -> Self {
        let context = self.context.get_or_insert_default();
        context.operation_id = Some(operation_id.into());
        context.status = Some(status.into());
        self
    }

    /// Attaches the wire failure record (internal).
    pub(crate) fn with_wire(mut self, wire: WireError) -> Self {
        self.context.get_or_insert_default().wire = Some(wire);
        self
    }

    /// Creates a test error (doc-hidden, for doctests only).
    #[doc(hidden)]
    #[must_use]
    pub fn __test_error() -> Self {
        Self::from_kind(OperationErrorKind::Step(StepError::new(
            StepErrorKind::ExecutionFailed,
            Some(Source::from("test")),
        )))
    }

    /// The operation family name used in this error's `Display` frame.
    fn family(&self) -> &'static str {
        match &self.kind {
            OperationErrorKind::Step(_) => "step",
            OperationErrorKind::Wait(_) => "wait",
            OperationErrorKind::Invoke(_) => "invoke",
            OperationErrorKind::Callback(_) => "callback",
            OperationErrorKind::WaitForCondition(_) => "wait_for_condition",
            OperationErrorKind::ChildContext(_) => "child_context",
            OperationErrorKind::Combinator(_) => "combinator",
            OperationErrorKind::NonDeterministicExecution(_) => "non_deterministic_execution",
        }
    }
}

impl fmt::Display for OperationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        struct Frame<'a>(&'a OperationError);
        impl fmt::Display for Frame<'_> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(f, "operation error: {}", self.0.family())
            }
        }
        if f.alternate() {
            write_chain(f, &Frame(self), self.source())
        } else {
            write!(f, "{}", Frame(self))
        }
    }
}

impl Error for OperationError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match &self.kind {
            OperationErrorKind::Step(e) => Some(e),
            OperationErrorKind::Wait(e) => Some(e),
            OperationErrorKind::Invoke(e) => Some(e),
            OperationErrorKind::Callback(e) => Some(e),
            OperationErrorKind::WaitForCondition(e) => Some(e),
            OperationErrorKind::ChildContext(e) => Some(e),
            OperationErrorKind::Combinator(e) => Some(e),
            OperationErrorKind::NonDeterministicExecution(e) => Some(e),
        }
    }
}

/// Classification of operation errors by operation type.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::{OperationError, OperationErrorKind};
///
/// fn is_retryable(err: &OperationError) -> bool {
///     // Callback timeouts are external; everything else is treated as
///     // internal in this example.
///     matches!(err.kind(), OperationErrorKind::Callback(_))
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub enum OperationErrorKind {
    /// A step operation failed.
    Step(StepError),
    /// A wait operation failed.
    Wait(WaitError),
    /// An invoke operation failed.
    Invoke(InvokeError),
    /// A callback operation failed.
    Callback(CallbackError),
    /// A wait-for-condition operation failed.
    WaitForCondition(WaitForConditionError),
    /// A child context operation failed.
    ChildContext(ChildContextError),
    /// A combinator operation failed.
    Combinator(CombinatorError),
    /// The handler produced operations in a different order than the
    /// checkpointed history: the execution is non-deterministic.
    NonDeterministicExecution(NonDeterministicExecutionError),
}

impl OperationErrorKind {
    /// The wire `ErrorType` name recorded for this kind when the failing
    /// error carries no more specific identity.
    pub(crate) fn wire_type_name(&self) -> &'static str {
        match self {
            Self::Step(_) => "StepError",
            Self::Wait(_) => "WaitError",
            Self::Invoke(_) => "InvokeError",
            Self::Callback(_) => "CallbackError",
            Self::WaitForCondition(_) => "WaitForConditionError",
            Self::ChildContext(_) => "ChildContextError",
            Self::Combinator(_) => "PromiseCombinatorError",
            Self::NonDeterministicExecution(_) => "NonDeterministicExecutionError",
        }
    }
}

impl fmt::Display for OperationErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Step(e) => write!(f, "step: {e}"),
            Self::Wait(e) => write!(f, "wait: {e}"),
            Self::Invoke(e) => write!(f, "invoke: {e}"),
            Self::Callback(e) => write!(f, "callback: {e}"),
            Self::WaitForCondition(e) => write!(f, "wait_for_condition: {e}"),
            Self::ChildContext(e) => write!(f, "child_context: {e}"),
            Self::Combinator(e) => write!(f, "combinator: {e}"),
            Self::NonDeterministicExecution(e) => write!(f, "non_deterministic_execution: {e}"),
        }
    }
}

/// The wire `ErrorMessage` recorded for an interrupted `AtMostOncePerRetry`
/// attempt, and the `source()` text of [`StepError::interrupted`]. It is the
/// message the JS SDK records.
pub(crate) const STEP_INTERRUPTED_MESSAGE: &str = "The step execution process was initiated but failed to reach completion due to an interruption.";

/// Error from a step operation.
///
/// Use [`kind()`](Self::kind) to determine the failure mode and
/// [`source()`](std::error::Error::source) to reach the escaping error.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::{StepError, StepErrorKind};
///
/// fn describe(err: &StepError) -> String {
///     match err.kind() {
///         // The body's error, also when the retry strategy stopped. Its
///         // `source()` is that error, and `{:#}` flattens the chain.
///         StepErrorKind::ExecutionFailed { .. } => format!("body failed: {err:#}"),
///         _ => format!("{err:#}"),
///     }
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct StepError {
    kind: StepErrorKind,
    source: Option<Source>,
}

impl StepError {
    /// Returns the specific kind of step error.
    pub fn kind(&self) -> &StepErrorKind {
        &self.kind
    }

    /// Creates the error a retry strategy receives for a step body, a
    /// `wait_for_callback` submitter or a `with_retry` attempt that
    /// returned `source`.
    ///
    /// Its kind is [`StepErrorKind::ExecutionFailed`], and its
    /// [`source()`](std::error::Error::source) is `source`. A test uses it
    /// to call a retry strategy with the error the SDK passes.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use aws_durable_execution_sdk::{RetryDecision, StepError, StepErrorKind};
    ///
    /// /// Retries a body error twice, one second apart, and never retries an
    /// /// interrupted attempt.
    /// fn strategy(err: &StepError, attempt: u32) -> RetryDecision {
    ///     if matches!(err.kind(), StepErrorKind::Interrupted { .. }) || attempt >= 3 {
    ///         RetryDecision::Stop
    ///     } else {
    ///         RetryDecision::retry(Duration::from_secs(1))
    ///     }
    /// }
    ///
    /// assert_eq!(
    ///     strategy(&StepError::execution_failed("throttled"), 1),
    ///     RetryDecision::retry(Duration::from_secs(1))
    /// );
    /// assert_eq!(strategy(&StepError::execution_failed("throttled"), 3), RetryDecision::Stop);
    /// assert_eq!(strategy(&StepError::interrupted(), 1), RetryDecision::Stop);
    /// ```
    #[must_use]
    pub fn execution_failed(source: impl Into<crate::BoxError>) -> Self {
        Self::new(StepErrorKind::ExecutionFailed, Some(source.into()))
    }

    /// Creates the error a retry strategy receives for an interrupted
    /// `AtMostOncePerRetry` attempt.
    ///
    /// Its kind is [`StepErrorKind::Interrupted`], and its
    /// [`source()`](std::error::Error::source) displays the message the SDK
    /// records for an interrupted attempt: `The step execution process was
    /// initiated but failed to reach completion due to an interruption.`
    #[must_use]
    pub fn interrupted() -> Self {
        Self::new(
            StepErrorKind::Interrupted,
            Some(STEP_INTERRUPTED_MESSAGE.into()),
        )
    }

    /// Creates a `StepError` from its kind and source (internal).
    pub(crate) fn new(kind: StepErrorKind, source: Option<Source>) -> Self {
        Self { kind, source }
    }

    /// Moves the source out of this error (internal).
    pub(crate) fn into_source(self) -> Option<Source> {
        self.source
    }
}

impl fmt::Display for StepError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write_chain(f, &self.kind, self.source())
        } else {
            write!(f, "{}", self.kind)
        }
    }
}

impl Error for StepError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
    }
}

/// Specific kinds of step failures.
///
/// Kinds classify; the escaping error is carried by [`StepError`] and
/// returned from its [`source()`](std::error::Error::source).
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::StepErrorKind;
///
/// fn body_failed(kind: &StepErrorKind) -> bool {
///     // Unit kind variants are `#[non_exhaustive]`: match them with
///     // `{ .. }` so a future field cannot break the pattern.
///     matches!(kind, StepErrorKind::ExecutionFailed { .. })
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub enum StepErrorKind {
    /// The step body returned an error. A retry strategy receives this kind
    /// for the body's error, and the step returns it once the strategy
    /// stops. The error's `source()` is the body's error.
    #[non_exhaustive]
    ExecutionFailed,
    /// A serialization or deserialization error occurred.
    #[non_exhaustive]
    SerializationFailed,
    /// An `AtMostOncePerRetry` attempt started but recorded no outcome.
    ///
    /// The SDK did not run the body again. It recorded the attempt as a
    /// failure with error type `StepInterruptedError` and asked the retry
    /// strategy whether to schedule another attempt.
    #[non_exhaustive]
    Interrupted,
}

impl fmt::Display for StepErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ExecutionFailed => write!(f, "execution failed"),
            Self::SerializationFailed => write!(f, "serialization failed"),
            Self::Interrupted => write!(f, "step interrupted"),
        }
    }
}

/// Error from a wait operation.
///
/// Use [`kind()`](Self::kind) to determine the failure mode.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::{WaitError, WaitErrorKind};
///
/// fn describe(err: &WaitError) -> String {
///     match err.kind() {
///         WaitErrorKind::UnexpectedStatus(details) => {
///             format!("cannot resume from status {}", details.status())
///         }
///         _ => format!("{err:#}"),
///     }
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct WaitError {
    kind: WaitErrorKind,
    source: Option<Source>,
}

impl WaitError {
    /// Returns the specific kind of wait error.
    pub fn kind(&self) -> &WaitErrorKind {
        &self.kind
    }

    /// Creates a `WaitError` from its kind and source (internal).
    pub(crate) fn new(kind: WaitErrorKind, source: Option<Source>) -> Self {
        Self { kind, source }
    }
}

impl fmt::Display for WaitError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write_chain(f, &self.kind, self.source())
        } else {
            write!(f, "{}", self.kind)
        }
    }
}

impl Error for WaitError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
    }
}

/// Specific kinds of wait failures.
///
/// A checkpoint write failure is deliberately NOT a kind here: a failed
/// wait START write unwinds the handler through the unrecoverable path
/// (issue #43), so user code never observes it as a `WaitError`.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::WaitErrorKind;
///
/// fn is_unexpected_status(kind: &WaitErrorKind) -> bool {
///     matches!(kind, WaitErrorKind::UnexpectedStatus(_))
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub enum WaitErrorKind {
    /// The wait's checkpointed record carries a status the SDK cannot
    /// resume from.
    UnexpectedStatus(UnexpectedStatus),
}

impl fmt::Display for WaitErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnexpectedStatus(details) => write!(f, "{details}"),
        }
    }
}

/// Details of a [`WaitErrorKind::UnexpectedStatus`] failure.
#[derive(Debug)]
#[non_exhaustive]
pub struct UnexpectedStatus {
    status: String,
}

impl UnexpectedStatus {
    /// Creates the payload (internal).
    pub(crate) fn new(status: impl Into<String>) -> Self {
        Self {
            status: status.into(),
        }
    }

    /// The unexpected status found in the checkpoint log.
    pub fn status(&self) -> &str {
        &self.status
    }
}

impl fmt::Display for UnexpectedStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "unexpected checkpointed status: {}", self.status)
    }
}

/// Error from an invoke operation.
///
/// # Examples
///
/// ```
/// use std::error::Error as _;
///
/// use aws_durable_execution_sdk::{InvokeError, InvokeErrorKind, ReplayedFailure};
///
/// fn remote_error_type(err: &InvokeError) -> Option<&str> {
///     match err.kind() {
///         InvokeErrorKind::FunctionFailed { .. } => err
///             .source()?
///             .downcast_ref::<ReplayedFailure>()?
///             .error_type(),
///         _ => None,
///     }
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct InvokeError {
    kind: InvokeErrorKind,
    source: Option<Source>,
}

impl InvokeError {
    /// Returns the specific kind of invoke error.
    pub fn kind(&self) -> &InvokeErrorKind {
        &self.kind
    }

    /// Creates an `InvokeError` from its kind and source (internal).
    pub(crate) fn new(kind: InvokeErrorKind, source: Option<Source>) -> Self {
        Self { kind, source }
    }
}

impl fmt::Display for InvokeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write_chain(f, &self.kind, self.source())
        } else {
            write!(f, "{}", self.kind)
        }
    }
}

impl Error for InvokeError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
    }
}

/// Specific kinds of invoke failures.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::InvokeErrorKind;
///
/// fn failed_in_function(kind: &InvokeErrorKind) -> bool {
///     // Unit kind variants are `#[non_exhaustive]`: match them with
///     // `{ .. }` so a future field cannot break the pattern.
///     matches!(kind, InvokeErrorKind::FunctionFailed { .. })
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub enum InvokeErrorKind {
    /// The invoke's record ended `FAILED`, `TIMED_OUT`, `STOPPED` or
    /// `CANCELLED`.
    ///
    /// The error's [`wire()`](crate::OperationError::wire) and its
    /// [`ReplayedFailure`] source carry the record's error type, message,
    /// data and stack trace. A record without a message, or with an empty
    /// one, gives the message `Invoke failed`.
    #[non_exhaustive]
    FunctionFailed,
    /// A serialization or deserialization error occurred.
    #[non_exhaustive]
    SerializationFailed,
}

impl fmt::Display for InvokeErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FunctionFailed => write!(f, "function failed"),
            Self::SerializationFailed => write!(f, "serialization failed"),
        }
    }
}

/// Error from a callback operation.
///
/// Follows the graded external/internal split: external errors are
/// caused by the caller's system (timeout, invalid data), and internal
/// errors are SDK or service failures. For an
/// [`ExternalFailure`](CallbackErrorKind::ExternalFailure), the wire
/// record is reachable through the error's
/// [`source()`](std::error::Error::source) (a [`ReplayedFailure`]) and
/// through [`OperationError::wire`]. From `create_callback`, it keeps
/// the callback record's error type, error data and stack trace. From
/// `wait_for_callback`, it has the type `Callback.ExternalFailure` and
/// keeps the callback record's error data. Both keep a nonempty message
/// and otherwise use `Callback failed`.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::{CallbackError, CallbackErrorKind};
///
/// fn describe(err: &CallbackError) -> String {
///     match err.kind() {
///         CallbackErrorKind::TimedOut { .. } => "timed out".to_owned(),
///         // The failure record travels on `source()`. Its type is the
///         // external caller's from `create_callback`, and
///         // `Callback.ExternalFailure` from `wait_for_callback`.
///         CallbackErrorKind::ExternalFailure { .. } => format!("{err:#}"),
///         _ => format!("{err:#}"),
///     }
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct CallbackError {
    kind: CallbackErrorKind,
    source: Option<Source>,
}

impl CallbackError {
    /// Returns the specific kind of callback error.
    pub fn kind(&self) -> &CallbackErrorKind {
        &self.kind
    }

    /// Creates a `CallbackError` from its kind and source (internal).
    pub(crate) fn new(kind: CallbackErrorKind, source: Option<Source>) -> Self {
        Self { kind, source }
    }
}

impl fmt::Display for CallbackError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write_chain(f, &self.kind, self.source())
        } else {
            write!(f, "{}", self.kind)
        }
    }
}

impl Error for CallbackError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
    }
}

/// Specific kinds of callback failures.
///
/// The external/internal split separates user-attributable errors
/// (timeout, invalid payload) from SDK/service failures.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::CallbackErrorKind;
///
/// fn is_external(kind: &CallbackErrorKind) -> bool {
///     matches!(
///         kind,
///         CallbackErrorKind::TimedOut { .. }
///             | CallbackErrorKind::HeartbeatTimedOut { .. }
///             | CallbackErrorKind::ExternalFailure { .. }
///             | CallbackErrorKind::SubmitterFailed { .. }
///     )
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub enum CallbackErrorKind {
    /// The callback timed out waiting for completion.
    ///
    /// The enclosing error's [`OperationError::wire`] record keeps the
    /// callback record's message and error data. An absent or empty message
    /// becomes `Callback timed out`. From `wait_for_callback`, the wire
    /// record has type `Callback.Timeout`.
    #[non_exhaustive]
    TimedOut,
    /// The callback heartbeat timed out (no keep-alive received in time).
    ///
    /// The service records a heartbeat timeout as a `TIMED_OUT` callback
    /// with the error type `Callback.Heartbeat`. Both `create_callback`
    /// and `wait_for_callback` report it with this kind. The enclosing
    /// error's [`OperationError::wire`] record keeps the callback record's
    /// message and error data. An absent or empty message becomes
    /// `Callback timed out`. From `wait_for_callback`, the wire record has
    /// type `Callback.Heartbeat`.
    #[non_exhaustive]
    HeartbeatTimedOut,
    /// The callback record is `FAILED`, `CANCELLED` or `STOPPED`, whatever
    /// its error type: an external system failed the callback, or the
    /// service cancelled or stopped it.
    ///
    /// The failure fields travel as wire data. Read them from the error's
    /// [`source()`](std::error::Error::source) (a [`ReplayedFailure`]) or
    /// from [`OperationError::wire`]. From `create_callback`, the wire
    /// record keeps the callback record's error type, error data and stack
    /// trace. It keeps a nonempty message and otherwise uses
    /// `Callback failed`. From `wait_for_callback`, the wire record has the
    /// type `Callback.ExternalFailure`. It keeps the callback record's error
    /// data and the same normalized message. The callback operation's
    /// stored record keeps the external type and original message field.
    #[non_exhaustive]
    ExternalFailure,
    /// The callback payload could not be deserialized.
    ///
    /// This is a payload decode failure that the serdes did not mark with
    /// [`RetryableSerdesError`](crate::serdes::RetryableSerdesError); a
    /// marked failure ends the invocation instead. From `create_callback`,
    /// `create_callback(..).await` succeeds, and
    /// [`Callback::result`](crate::builders::callback::Callback::result) or
    /// [`Callback::spawn_result`](crate::builders::callback::Callback::spawn_result) returns
    /// this permanent error, live and on replay. From
    /// `wait_for_callback`, the outer operation's record has already
    /// succeeded with the raw payload, and this error is the decode of that
    /// payload with the operation's serdes. So every invocation that reads
    /// the record fails the same way.
    #[non_exhaustive]
    DeserializationFailed,
    /// An internal SDK or service error occurred.
    #[non_exhaustive]
    Internal,
    /// The `wait_for_callback` submitter failed and its retry strategy stopped.
    ///
    /// Live, `source()` is the submitter step's `OperationError`. On replay,
    /// `source()` is a `ReplayedFailure` holding the recorded outer failure.
    #[non_exhaustive]
    SubmitterFailed,
}

impl fmt::Display for CallbackErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TimedOut => write!(f, "callback timed out"),
            Self::HeartbeatTimedOut => write!(f, "callback heartbeat timed out"),
            Self::ExternalFailure => write!(f, "external failure"),
            Self::DeserializationFailed => write!(f, "deserialization failed"),
            Self::Internal => write!(f, "internal error"),
            Self::SubmitterFailed => write!(f, "submitter failed"),
        }
    }
}

/// Error from a wait-for-condition operation.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::{WaitForConditionError, WaitForConditionErrorKind};
///
/// fn checks_used(err: &WaitForConditionError) -> Option<u32> {
///     match err.kind() {
///         WaitForConditionErrorKind::MaxChecksExceeded(details) => Some(details.checks()),
///         _ => None,
///     }
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct WaitForConditionError {
    kind: WaitForConditionErrorKind,
    source: Option<Source>,
}

impl WaitForConditionError {
    /// Returns the specific kind of wait-for-condition error.
    pub fn kind(&self) -> &WaitForConditionErrorKind {
        &self.kind
    }

    /// Creates a `WaitForConditionError` from its kind and source (internal).
    pub(crate) fn new(kind: WaitForConditionErrorKind, source: Option<Source>) -> Self {
        Self { kind, source }
    }
}

impl fmt::Display for WaitForConditionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write_chain(f, &self.kind, self.source())
        } else {
            write!(f, "{}", self.kind)
        }
    }
}

impl Error for WaitForConditionError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
    }
}

/// Specific kinds of wait-for-condition failures.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::WaitForConditionErrorKind;
///
/// fn check_function_failed(kind: &WaitForConditionErrorKind) -> bool {
///     matches!(kind, WaitForConditionErrorKind::CheckFailed { .. })
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub enum WaitForConditionErrorKind {
    /// The check function returned an error.
    #[non_exhaustive]
    CheckFailed,
    /// The maximum number of checks was exceeded.
    MaxChecksExceeded(MaxChecksExceeded),
    /// A serialization error occurred on the state.
    #[non_exhaustive]
    SerializationFailed,
}

impl fmt::Display for WaitForConditionErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CheckFailed => write!(f, "check failed"),
            Self::MaxChecksExceeded(details) => write!(f, "{details}"),
            Self::SerializationFailed => write!(f, "serialization failed"),
        }
    }
}

/// Details of a [`WaitForConditionErrorKind::MaxChecksExceeded`] failure.
#[derive(Debug)]
#[non_exhaustive]
pub struct MaxChecksExceeded {
    checks: u32,
}

impl MaxChecksExceeded {
    /// Creates the payload (internal).
    pub(crate) fn new(checks: u32) -> Self {
        Self { checks }
    }

    /// The number of checks performed.
    pub fn checks(&self) -> u32 {
        self.checks
    }
}

impl fmt::Display for MaxChecksExceeded {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "max checks exceeded: {}", self.checks)
    }
}

/// Error from a child context (sub-orchestration) operation.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::{ChildContextError, ChildContextErrorKind};
///
/// fn child_body_failed(err: &ChildContextError) -> bool {
///     matches!(err.kind(), ChildContextErrorKind::ChildFailed { .. })
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct ChildContextError {
    kind: ChildContextErrorKind,
    source: Option<Source>,
}

impl ChildContextError {
    /// Returns the specific kind of child context error.
    pub fn kind(&self) -> &ChildContextErrorKind {
        &self.kind
    }

    /// Creates a `ChildContextError` from its kind and source (internal).
    pub(crate) fn new(kind: ChildContextErrorKind, source: Option<Source>) -> Self {
        Self { kind, source }
    }
}

impl fmt::Display for ChildContextError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write_chain(f, &self.kind, self.source())
        } else {
            write!(f, "{}", self.kind)
        }
    }
}

impl Error for ChildContextError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source.as_deref().map(|s| s as &(dyn Error + 'static))
    }
}

/// Specific kinds of child context failures.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::ChildContextErrorKind;
///
/// fn is_internal(kind: &ChildContextErrorKind) -> bool {
///     matches!(kind, ChildContextErrorKind::Internal { .. })
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub enum ChildContextErrorKind {
    /// The child function returned an error.
    #[non_exhaustive]
    ChildFailed,
    /// An internal error occurred setting up the child context.
    #[non_exhaustive]
    Internal,
    /// A map or parallel completion predicate completed the batch as failed
    /// (`CUSTOM_COMPLETION_FAILED`), and no item failed.
    #[non_exhaustive]
    BatchCompletionFailed,
    /// A [`BranchHandle`](crate::BranchHandle) has no result: the
    /// `parallel_mixed` operation that owns its branch has not returned, the
    /// branch never started, or the batch completed while the branch still
    /// ran.
    #[non_exhaustive]
    NotCompleted,
}

impl fmt::Display for ChildContextErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ChildFailed => write!(f, "child failed"),
            Self::Internal => write!(f, "internal error"),
            Self::BatchCompletionFailed => write!(f, "batch completed as failed"),
            Self::NotCompleted => write!(f, "branch has no result"),
        }
    }
}

/// Error from a combinator operation (`try_join_all`, `join_all`,
/// `select_ok`, `race`).
///
/// The combinator preserves the losing futures' errors as errors:
/// [`source()`](std::error::Error::source) returns the first loser, and
/// [`failures()`](Self::failures) returns every loser (in input order for
/// [`CombinatorErrorKind::AllFailed`]).
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::{CombinatorError, CombinatorErrorKind};
///
/// fn report(err: &CombinatorError) {
///     if let CombinatorErrorKind::AllFailed { .. } = err.kind() {
///         for loser in err.failures() {
///             tracing::error!(error = format!("{loser}"), "branch failed");
///         }
///     }
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct CombinatorError {
    kind: CombinatorErrorKind,
    failures: Vec<Source>,
}

impl CombinatorError {
    /// Creates a `CombinatorError` from a kind and its losing errors
    /// (internal).
    pub(crate) fn new(kind: CombinatorErrorKind, failures: Vec<Source>) -> Self {
        Self { kind, failures }
    }

    /// Returns the specific kind of combinator error.
    pub fn kind(&self) -> &CombinatorErrorKind {
        &self.kind
    }

    /// The underlying failures, preserved as errors.
    ///
    /// For [`CombinatorErrorKind::JoinFailed`] and
    /// [`CombinatorErrorKind::FirstSettledFailed`] this holds the single
    /// losing error; for [`CombinatorErrorKind::AllFailed`] it holds every
    /// loser in input order. After a replay, each entry is a
    /// [`ReplayedFailure`] rebuilt from the recorded wire fields.
    pub fn failures(&self) -> &[Box<dyn Error + Send + Sync + 'static>] {
        &self.failures
    }
}

impl fmt::Display for CombinatorError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write_chain(f, &self.kind, self.source())
        } else {
            write!(f, "{}", self.kind)
        }
    }
}

impl Error for CombinatorError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.failures
            .first()
            .map(|s| &**s as &(dyn Error + 'static))
    }
}

/// Specific kinds of combinator failures.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::CombinatorErrorKind;
///
/// fn first_failed_index(kind: &CombinatorErrorKind) -> Option<usize> {
///     match kind {
///         CombinatorErrorKind::JoinFailed(details) => Some(details.failed_index()),
///         _ => None,
///     }
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub enum CombinatorErrorKind {
    /// One or more futures in `try_join_all` failed.
    JoinFailed(JoinFailed),
    /// All futures in `select_ok` failed.
    ///
    /// Every loser's error is reachable through
    /// [`CombinatorError::failures`].
    #[non_exhaustive]
    AllFailed,
    /// The first settled future in `race` was a failure.
    ///
    /// `race` propagates the first outcome to settle, success or failure.
    /// When that outcome is a failure, the losing future's error is
    /// carried as the error's source.
    #[non_exhaustive]
    FirstSettledFailed,
    /// The combinator was called with no futures.
    ///
    /// Returned by `race` and `select_ok`, which cannot produce a winner
    /// from an empty input. `try_join_all` and `join_all` instead resolve
    /// successfully to an empty collection.
    #[non_exhaustive]
    EmptyInput,
    /// An internal error occurred.
    #[non_exhaustive]
    Internal,
}

impl fmt::Display for CombinatorErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::JoinFailed(details) => write!(f, "{details}"),
            Self::AllFailed => write!(f, "all futures failed"),
            Self::FirstSettledFailed => write!(f, "first settled future failed"),
            Self::EmptyInput => write!(f, "combinator called with no futures"),
            Self::Internal => write!(f, "internal error"),
        }
    }
}

/// Details of a [`CombinatorErrorKind::JoinFailed`] failure.
#[derive(Debug)]
#[non_exhaustive]
pub struct JoinFailed {
    failed_index: usize,
}

impl JoinFailed {
    /// Creates the payload (internal).
    pub(crate) fn new(failed_index: usize) -> Self {
        Self { failed_index }
    }

    /// The index of the first failed future in the combinator's input.
    pub fn failed_index(&self) -> usize {
        self.failed_index
    }
}

impl fmt::Display for JoinFailed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "join failed at index {}", self.failed_index)
    }
}

/// Error raised when replay cannot faithfully reproduce the checkpointed
/// history: the claimed operation does not match the record at its slot
/// (the handler produced operations in a different order between
/// invocations), or the record carries a status this SDK version cannot
/// interpret.
///
/// This is a fatal, non-recoverable error: the execution must be failed and
/// cannot be retried without resetting the checkpoint log.
///
/// There is no foreign cause to carry (the report *is* the
/// error), so this type has no source; its structural facts live behind
/// the kind payload's accessors (see [`OperationMismatch`] and
/// [`UnrecognizedStatus`]).
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::{
///     NonDeterministicExecutionError, NonDeterministicExecutionErrorKind,
/// };
///
/// fn report(err: &NonDeterministicExecutionError) {
///     match err.kind() {
///         NonDeterministicExecutionErrorKind::OperationMismatch(details) => {
///             tracing::error!(
///                 wire_id = details.wire_id(),
///                 expected = details.expected(),
///                 actual = details.actual(),
///                 "non-deterministic replay detected"
///             );
///         }
///         // The enum is `#[non_exhaustive]`: new mismatch kinds may be
///         // added without a major version bump.
///         _ => tracing::error!("non-deterministic replay detected"),
///     }
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct NonDeterministicExecutionError {
    kind: NonDeterministicExecutionErrorKind,
}

impl NonDeterministicExecutionError {
    /// Returns the specific kind of non-determinism error.
    pub fn kind(&self) -> &NonDeterministicExecutionErrorKind {
        &self.kind
    }

    /// Creates a `NonDeterministicExecutionError` from its kind (internal).
    pub(crate) fn from_kind(kind: NonDeterministicExecutionErrorKind) -> Self {
        Self { kind }
    }
}

impl fmt::Display for NonDeterministicExecutionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.kind)
    }
}

impl Error for NonDeterministicExecutionError {}

/// Specific kinds of non-deterministic execution failures.
///
/// # Examples
///
/// ```
/// use aws_durable_execution_sdk::NonDeterministicExecutionErrorKind;
///
/// fn mismatch_slot(kind: &NonDeterministicExecutionErrorKind) -> Option<&str> {
///     match kind {
///         NonDeterministicExecutionErrorKind::OperationMismatch(details) => {
///             Some(details.wire_id())
///         }
///         _ => None,
///     }
/// }
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub enum NonDeterministicExecutionErrorKind {
    /// The claimed operation's identity (type, sub-type, or name) does not
    /// match the checkpointed record at the same positional slot.
    OperationMismatch(OperationMismatch),
    /// The checkpointed record carries a status this SDK version does not
    /// recognize, so replay cannot interpret the recorded outcome.
    ///
    /// This arises when the durable execution service introduces a new
    /// operation status that predates this SDK build. Guessing is unsafe in
    /// both directions, treating a possibly-terminal operation as
    /// re-runnable re-executes completed work, and fabricating a terminal
    /// outcome returns a result that was never recorded, so the execution
    /// fails naming the raw status. Upgrading the SDK to a version that
    /// understands the status is the remedy.
    UnrecognizedStatus(UnrecognizedStatus),
}

impl fmt::Display for NonDeterministicExecutionErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::OperationMismatch(details) => write!(f, "{details}"),
            Self::UnrecognizedStatus(details) => write!(f, "{details}"),
        }
    }
}

/// Details of a [`NonDeterministicExecutionErrorKind::OperationMismatch`]
/// failure.
#[derive(Debug)]
#[non_exhaustive]
pub struct OperationMismatch {
    wire_id: String,
    expected: String,
    actual: String,
}

impl OperationMismatch {
    /// Creates the payload (internal).
    pub(crate) fn new(
        wire_id: impl Into<String>,
        expected: impl Into<String>,
        actual: impl Into<String>,
    ) -> Self {
        Self {
            wire_id: wire_id.into(),
            expected: expected.into(),
            actual: actual.into(),
        }
    }

    /// The wire ID (SHA-256 hex) of the positional slot that mismatched.
    pub fn wire_id(&self) -> &str {
        &self.wire_id
    }

    /// Human-readable description of what the checkpoint log expected.
    pub fn expected(&self) -> &str {
        &self.expected
    }

    /// Human-readable description of what the handler claimed.
    pub fn actual(&self) -> &str {
        &self.actual
    }
}

impl fmt::Display for OperationMismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "operation at wire id {} does not match checkpoint: \
             expected {}, got {}",
            self.wire_id, self.expected, self.actual
        )
    }
}

/// Details of a [`NonDeterministicExecutionErrorKind::UnrecognizedStatus`]
/// failure.
#[derive(Debug)]
#[non_exhaustive]
pub struct UnrecognizedStatus {
    wire_id: String,
    status: String,
}

impl UnrecognizedStatus {
    /// Creates the payload (internal).
    pub(crate) fn new(wire_id: impl Into<String>, status: impl Into<String>) -> Self {
        Self {
            wire_id: wire_id.into(),
            status: status.into(),
        }
    }

    /// The wire ID (SHA-256 hex) of the operation whose record carries the
    /// unrecognized status.
    pub fn wire_id(&self) -> &str {
        &self.wire_id
    }

    /// The raw status value the service reported, verbatim.
    pub fn status(&self) -> &str {
        &self.status
    }
}

impl fmt::Display for UnrecognizedStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "operation at wire id {} replayed with unrecognized status {:?}: \
             this SDK version cannot interpret the recorded outcome; \
             upgrade the SDK to a version that understands this status",
            self.wire_id, self.status
        )
    }
}

/// Crate-internal error carrier for `run_in_child_context`, `parallel`, and
/// `map` closure bodies.
///
/// Public closure boundaries take [`crate::BoxError`]; the SDK converts a
/// `BoxError` into this type at the boundary and grades it into
/// [`ChildContextErrorKind::ChildFailed`] when a child body fails. It
/// carries the escaping error as its source rather than flattening it, so
/// the child-boundary pass-through guarantee (`error_data`, downcastable
/// cause) holds. It is not part of the public API.
#[derive(Debug)]
pub(crate) struct ChildFnError {
    source: Source,
}

impl ChildFnError {
    /// Creates a new `ChildFnError` carrying the given source.
    #[must_use]
    pub(crate) fn new(source: impl Into<Source>) -> Self {
        Self {
            source: source.into(),
        }
    }

    /// Moves the carried error out (internal).
    pub(crate) fn into_source(self) -> Source {
        self.source
    }

    /// The wire record a failed child, map item or branch writes: derived
    /// from the error the body returned, with fallback type `"Error"`.
    ///
    /// The record is derived from the body error, not from this carrier.
    /// The carrier is an internal Rust type. Deriving from it would record
    /// its name as the type and prefix its own text to the message. So the
    /// record follows [`wire_error_for`]'s rule applied to the body error:
    /// a body that propagates an operation failure records that failure's
    /// recorded message ([`wire_message`]).
    pub(crate) fn failure_wire(&self) -> WireError {
        wire_error_for(&*self.source, "Error")
    }
}

impl fmt::Display for ChildFnError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            write_chain(f, &"child function error", self.source())
        } else {
            write!(f, "child function error")
        }
    }
}

impl Error for ChildFnError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&*self.source as &(dyn Error + 'static))
    }
}

impl From<OperationError> for ChildFnError {
    fn from(err: OperationError) -> Self {
        Self {
            source: Box::new(err),
        }
    }
}

impl From<crate::BoxError> for ChildFnError {
    /// Converts a user-facing [`crate::BoxError`] into the internal
    /// carrier, preserving the error itself as the source.
    fn from(err: crate::BoxError) -> Self {
        Self { source: err }
    }
}

// Static assertions: all public error types must be Send + Sync + 'static.
// These compile-time checks prevent accidental regressions: the `source`
// fields' `Send + Sync` bounds are what keep them true. The helper is
// genuinely called during const evaluation, so no dead-code override is
// needed (and `#[expect(dead_code)]` here diverges across toolchains).
const _: () = {
    const fn assert_send_sync_static<T: Send + Sync + 'static>() {}
    assert_send_sync_static::<OperationError>();
    assert_send_sync_static::<OperationErrorKind>();
    assert_send_sync_static::<StepError>();
    assert_send_sync_static::<StepErrorKind>();
    assert_send_sync_static::<WaitError>();
    assert_send_sync_static::<WaitErrorKind>();
    assert_send_sync_static::<UnexpectedStatus>();
    assert_send_sync_static::<InvokeError>();
    assert_send_sync_static::<InvokeErrorKind>();
    assert_send_sync_static::<CallbackError>();
    assert_send_sync_static::<CallbackErrorKind>();
    assert_send_sync_static::<WaitForConditionError>();
    assert_send_sync_static::<WaitForConditionErrorKind>();
    assert_send_sync_static::<MaxChecksExceeded>();
    assert_send_sync_static::<ChildContextError>();
    assert_send_sync_static::<ChildContextErrorKind>();
    assert_send_sync_static::<CombinatorError>();
    assert_send_sync_static::<CombinatorErrorKind>();
    assert_send_sync_static::<JoinFailed>();
    assert_send_sync_static::<NonDeterministicExecutionError>();
    assert_send_sync_static::<NonDeterministicExecutionErrorKind>();
    assert_send_sync_static::<OperationMismatch>();
    assert_send_sync_static::<WireError>();
    assert_send_sync_static::<TypedError>();
    assert_send_sync_static::<ReplayedFailure>();
    assert_send_sync_static::<ContextualError>();
    assert_send_sync_static::<ChildFnError>();
    assert_send_sync_static::<crate::serdes::FileSystemSerdesError>();
};

/// A failed step's error as an operation returns it: a
/// `Step(ExecutionFailed)` [`OperationError`] carrying `wire` as its record,
/// whose source is a [`ReplayedFailure`] of the same record (test helper).
#[cfg(test)]
pub(crate) fn recorded_step_error(wire: WireError) -> OperationError {
    OperationError::from_kind(OperationErrorKind::Step(StepError::new(
        StepErrorKind::ExecutionFailed,
        Some(ReplayedFailure::source_from(wire.clone())),
    )))
    .with_wire(wire)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The retryable checkpoint failure's message is JS's: the prefix
    /// `[Unrecoverable Invocation] Checkpoint failed: ` and the error's
    /// record message.
    #[test]
    fn checkpoint_invocation_failure_message_is_js_form() {
        let err = crate::client::ExecutionClientError::new(
            crate::client::ExecutionClientErrorScope::Invocation,
            "throttled",
        );
        assert_eq!(
            checkpoint_invocation_failure_message(&err),
            "[Unrecoverable Invocation] Checkpoint failed: throttled"
        );
    }
    /// A concrete user error type for downcast tests.
    #[derive(Debug)]
    struct UserBoom {
        detail: &'static str,
    }
    impl fmt::Display for UserBoom {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "user boom: {}", self.detail)
        }
    }
    impl Error for UserBoom {}

    fn step_error_with_user_source() -> OperationError {
        OperationError::from_kind(OperationErrorKind::Step(StepError::new(
            StepErrorKind::ExecutionFailed,
            Some(Box::new(UserBoom { detail: "flaky" })),
        )))
    }

    /// Walks the full `source()` chain and returns each layer's display.
    fn causal_chain(err: &dyn Error) -> Vec<String> {
        let mut chain = vec![err.to_string()];
        let mut current: &dyn Error = err;
        while let Some(next) = current.source() {
            chain.push(next.to_string());
            current = next;
        }
        chain
    }

    // Acceptance: live-path downcast

    #[test]
    fn live_failure_exposes_concrete_error_type_through_source_downcast() {
        let err = step_error_with_user_source();
        // Walk the chain until the caller's concrete type is found.
        let mut current: Option<&(dyn Error + 'static)> = err.source();
        let mut found = None;
        while let Some(e) = current {
            if let Some(user) = e.downcast_ref::<UserBoom>() {
                found = Some(user);
                break;
            }
            current = e.source();
        }
        let user = found.expect("caller's concrete error must be reachable via source()");
        assert_eq!(user.detail, "flaky");
    }

    // Acceptance: Display frames, alternate chain, no repeats

    #[test]
    fn display_writes_one_frame_and_alternate_walks_chain() {
        let err = step_error_with_user_source();

        // `{}` yields one frame, no cause text.
        let plain = format!("{err}");
        assert_eq!(plain, "operation error: step");

        // `{:#}` yields the chain.
        let alternate = format!("{err:#}");
        assert_eq!(
            alternate,
            "operation error: step: execution failed: user boom: flaky"
        );
    }

    #[test]
    fn walking_source_does_not_repeat_text() {
        let err = step_error_with_user_source();
        let chain = causal_chain(&err);
        // OperationError -> StepError -> UserBoom.
        assert_eq!(
            chain,
            vec![
                "operation error: step".to_owned(),
                "execution failed".to_owned(),
                "user boom: flaky".to_owned(),
            ]
        );
        // No frame's text appears in another frame.
        for (i, frame) in chain.iter().enumerate() {
            for (j, other) in chain.iter().enumerate() {
                if i != j {
                    assert!(
                        !other.contains(frame.as_str()),
                        "frame {i} ({frame:?}) repeats inside frame {j} ({other:?})"
                    );
                }
            }
        }
    }

    // Replay source

    #[test]
    fn replayed_failure_carries_wire_fields() {
        let wire = WireError::new(Some("NotApproved"), Some("request was denied"))
            .with_error_data(Some("{\"code\":42}"));
        let err = OperationError::from_kind(OperationErrorKind::Step(StepError::new(
            StepErrorKind::ExecutionFailed,
            Some(ReplayedFailure::source_from(wire)),
        )));
        // kind() is meaningful after a replay.
        let OperationErrorKind::Step(step_err) = err.kind() else {
            unreachable!("constructed as a step error");
        };
        assert!(matches!(step_err.kind(), StepErrorKind::ExecutionFailed));
        // The synthetic source carries the wire error_type and message.
        let source = Error::source(step_err).expect("replay attaches a source");
        let replayed = source
            .downcast_ref::<ReplayedFailure>()
            .expect("replay source must be a ReplayedFailure");
        assert_eq!(replayed.error_type(), Some("NotApproved"));
        assert_eq!(replayed.error_message(), Some("request was denied"));
        assert_eq!(replayed.wire().error_data(), Some("{\"code\":42}"));
    }

    // Wire derivation

    #[test]
    fn wire_error_for_flattens_chain_once_and_uses_fallback_type() {
        let err = step_error_with_user_source();
        let wire = wire_error_for(&err, "Error");
        // The message is the flattened chain (single flattening site).
        assert_eq!(
            wire.error_message(),
            Some("operation error: step: execution failed: user boom: flaky")
        );
        // No structured identity in the chain: falls back to the kind's
        // wire name because the top error is an OperationError.
        assert_eq!(wire.error_type(), Some("StepError"));
        // No link carries frames, and the SDK captures none.
        assert_eq!(wire.stack_trace(), [] as [String; 0]);
        // No error_data anywhere in the chain: none synthesized.
        assert_eq!(wire.error_data(), None);
    }

    #[test]
    fn wire_error_passes_through_recorded_frames() {
        let err = ContextualError::source_from(
            "ctx",
            ReplayedFailure::source_from(
                WireError::new(Some("T"), Some("m"))
                    .with_stack_trace(vec!["frame-a".into(), "frame-b".into()]),
            ),
        );
        let wire = wire_error_for(&*err, "Error");
        assert_eq!(
            wire.stack_trace(),
            &["frame-a".to_owned(), "frame-b".to_owned()]
        );
    }

    #[test]
    fn typed_error_error_data_precedence() {
        fn boom() -> UserBoom {
            UserBoom { detail: "x" }
        }
        fn replayed(d: &str) -> Source {
            ReplayedFailure::source_from(
                WireError::new(Some("Inner"), Some("inner")).with_error_data(Some(d)),
            )
        }
        fn row1() -> Source {
            Box::new(TypedError::with_type("PaymentError", boom()).with_error_data("data-a"))
        }
        fn layered(layers: usize) -> Source {
            let mut inner = row1();
            for i in 0..layers {
                inner = ContextualError::source_from(format!("layer {i}"), inner);
            }
            inner
        }

        let rows: Vec<(usize, Source, Option<&str>)> = vec![
            (1, row1(), Some("data-a")),
            (
                2,
                Box::new(TypedError::with_type("P", replayed("data-b")).with_error_data("data-a")),
                Some("data-a"),
            ),
            (
                3,
                Box::new(TypedError::with_type("P", replayed("data-b"))),
                Some("data-b"),
            ),
            (4, layered(1), Some("data-a")),
            (5, Box::new(TypedError::with_type("P", boom())), None),
            // The `TypedError` is link 10.
            (6, layered(9), Some("data-a")),
            // The `TypedError` is link 11, the last error the walk reads.
            (7, layered(10), Some("data-a")),
            // The `TypedError` is link 12, past the walk.
            (8, layered(11), None),
        ];
        for (row, err, expected) in &rows {
            let wire = wire_error_for(&**err, "Error");
            assert_eq!(wire.error_data(), *expected, "row {row}");
            if *row == 1 {
                assert_eq!(wire.error_type(), Some("PaymentError"));
                assert!(
                    !wire.error_message().unwrap_or_default().contains("data-a"),
                    "the data never appears in the message: {:?}",
                    wire.error_message()
                );
            }
        }
    }

    #[test]
    fn step_error_constructors_build_strategy_inputs() {
        let failed = StepError::execution_failed("throttled");
        assert!(matches!(failed.kind(), StepErrorKind::ExecutionFailed));
        assert_eq!(
            failed.source().map(ToString::to_string).as_deref(),
            Some("throttled")
        );

        let interrupted = StepError::interrupted();
        assert!(matches!(interrupted.kind(), StepErrorKind::Interrupted));
        assert_eq!(
            interrupted.source().map(ToString::to_string).as_deref(),
            Some(
                "The step execution process was initiated but failed to reach completion due to an interruption."
            )
        );
    }

    #[test]
    fn wire_error_for_plain_user_error_uses_fallback() {
        let err = UserBoom { detail: "plain" };
        let wire = wire_error_for(&err, "Error");
        assert_eq!(wire.error_type(), Some("Error"));
        assert_eq!(wire.error_message(), Some("user boom: plain"));
    }

    #[test]
    fn error_data_survives_child_boundary_via_cause_chain() {
        // An inner failure that carries wire data (e.g. an external
        // callback failure read back from the wire)...
        let inner_wire = WireError::new(Some("VendorError"), Some("denied"))
            .with_error_data(Some("opaque-payload"));
        let inner = OperationError::from_kind(OperationErrorKind::Callback(CallbackError::new(
            CallbackErrorKind::ExternalFailure,
            Some(ReplayedFailure::source_from(inner_wire.clone())),
        )))
        .with_wire(inner_wire);

        // ...escapes through a child-context boundary.
        let child_fn = ChildFnError::from(inner);
        let wire = child_fn.failure_wire();

        // The opaque payload survives the boundary via the cause chain.
        assert_eq!(wire.error_data(), Some("opaque-payload"));
        // It is passed through, never parsed: the value is byte-identical.
        assert_eq!(wire.error_data(), Some("opaque-payload"));
    }

    #[test]
    fn wire_error_re_records_replayed_failure_type() {
        // Re-recording a replayed failure directly preserves its type...
        let recorded = WireError::new(Some("MyDomainError"), Some("原因"));
        let replayed = ReplayedFailure::new(recorded.clone());
        let wire = wire_error_for(&replayed, "Error");
        assert_eq!(wire.error_type(), Some("MyDomainError"));

        // ...and an operation error wrapping it re-records its attached
        // wire identity: the explicitly supplied type survives the
        // boundary instead of degrading to the kind's registry name.
        let err = OperationError::from_kind(OperationErrorKind::Step(StepError::new(
            StepErrorKind::ExecutionFailed,
            Some(ReplayedFailure::source_from(recorded.clone())),
        )))
        .with_wire(recorded);
        let wire = wire_error_for(&err, "Error");
        assert_eq!(wire.error_type(), Some("MyDomainError"));
        assert_eq!(
            err.wire().and_then(WireError::error_type),
            Some("MyDomainError")
        );

        // An operation error with no attached wire and no typed identity
        // in its chain still falls back to the kind's registry name.
        let bare = OperationError::from_kind(OperationErrorKind::Step(StepError::new(
            StepErrorKind::ExecutionFailed,
            Some(Source::from("plain failure")),
        )));
        let wire = wire_error_for(&bare, "Error");
        assert_eq!(wire.error_type(), Some("StepError"));
    }

    // Structural facts behind accessors

    #[test]
    fn step_error_kind_accessor() {
        let err = StepError::new(StepErrorKind::ExecutionFailed, Some(Source::from("fail")));
        match err.kind() {
            StepErrorKind::ExecutionFailed => {}
            other => unreachable!("unexpected kind: {other:?}"),
        }
    }

    #[test]
    fn operation_mismatch_accessors() {
        let details = OperationMismatch::new("abc123", "Step/Step", "Wait/Wait");
        assert_eq!(details.wire_id(), "abc123");
        assert_eq!(details.expected(), "Step/Step");
        assert_eq!(details.actual(), "Wait/Wait");
        let err = NonDeterministicExecutionError::from_kind(
            NonDeterministicExecutionErrorKind::OperationMismatch(details),
        );
        // The mismatch report is the error: no source to carry.
        assert!(Error::source(&err).is_none());
        assert!(err.to_string().contains("abc123"));
    }

    // Combinators keep every loser

    #[test]
    fn combinator_all_failed_keeps_every_loser() {
        let losers: Vec<Source> = vec![
            Box::new(UserBoom { detail: "a" }),
            Box::new(UserBoom { detail: "b" }),
        ];
        let err = CombinatorError::new(CombinatorErrorKind::AllFailed, losers);
        assert_eq!(err.failures().len(), 2);
        // source() returns the first loser.
        let first = Error::source(&err).expect("has a source");
        assert!(first.downcast_ref::<UserBoom>().is_some());
        // Every loser is reachable, as an error, not a string.
        let details: Vec<&str> = err
            .failures()
            .iter()
            .filter_map(|l| l.downcast_ref::<UserBoom>().map(|u| u.detail))
            .collect();
        assert_eq!(details, vec!["a", "b"]);
    }

    #[test]
    fn combinator_join_failed_keeps_loser_and_index() {
        let err = CombinatorError::new(
            CombinatorErrorKind::JoinFailed(JoinFailed::new(2)),
            vec![Box::new(UserBoom { detail: "loser" })],
        );
        match err.kind() {
            CombinatorErrorKind::JoinFailed(details) => assert_eq!(details.failed_index(), 2),
            other => unreachable!("unexpected kind: {other:?}"),
        }
        let source = Error::source(&err).expect("loser preserved");
        assert!(source.downcast_ref::<UserBoom>().is_some());
    }

    // ChildFnError carries the error

    #[test]
    fn child_fn_error_preserves_operation_error() {
        let op = step_error_with_user_source();
        let child_err = ChildFnError::from(op);
        let source = Error::source(&child_err).expect("carries the error");
        assert!(source.downcast_ref::<OperationError>().is_some());
        // Frame stays clean; the chain is reachable via {:#}.
        assert_eq!(child_err.to_string(), "child function error");
        assert!(format!("{child_err:#}").contains("user boom: flaky"));
    }

    // Display conventions across variants

    #[test]
    fn every_operation_family_displays_its_frame() {
        let cases: Vec<(OperationError, &str)> = vec![
            (
                OperationError::from_kind(OperationErrorKind::Step(StepError::new(
                    StepErrorKind::ExecutionFailed,
                    None,
                ))),
                "step",
            ),
            (
                OperationError::from_kind(OperationErrorKind::Wait(WaitError::new(
                    WaitErrorKind::UnexpectedStatus(UnexpectedStatus::new("Failed")),
                    None,
                ))),
                "wait",
            ),
            (
                OperationError::from_kind(OperationErrorKind::Invoke(InvokeError::new(
                    InvokeErrorKind::FunctionFailed,
                    None,
                ))),
                "invoke",
            ),
            (
                OperationError::from_kind(OperationErrorKind::Callback(CallbackError::new(
                    CallbackErrorKind::TimedOut,
                    None,
                ))),
                "callback",
            ),
            (
                OperationError::from_kind(OperationErrorKind::WaitForCondition(
                    WaitForConditionError::new(
                        WaitForConditionErrorKind::MaxChecksExceeded(MaxChecksExceeded::new(2)),
                        None,
                    ),
                )),
                "wait_for_condition",
            ),
            (
                OperationError::from_kind(OperationErrorKind::ChildContext(
                    ChildContextError::new(ChildContextErrorKind::ChildFailed, None),
                )),
                "child_context",
            ),
            (
                OperationError::from_kind(OperationErrorKind::Combinator(CombinatorError::new(
                    CombinatorErrorKind::Internal,
                    vec![Box::new(UserBoom { detail: "x" })],
                ))),
                "combinator",
            ),
            (
                OperationError::from_kind(OperationErrorKind::NonDeterministicExecution(
                    NonDeterministicExecutionError::from_kind(
                        NonDeterministicExecutionErrorKind::OperationMismatch(
                            OperationMismatch::new("abc123", "Step/Step", "Wait/Wait"),
                        ),
                    ),
                )),
                "non_deterministic_execution",
            ),
        ];
        for (err, family) in &cases {
            assert_eq!(format!("{err}"), format!("operation error: {family}"));
            // The chain never repeats text across frames.
            let chain = causal_chain(err);
            for (i, frame) in chain.iter().enumerate() {
                for (j, other) in chain.iter().enumerate() {
                    if i != j {
                        assert!(
                            !other.contains(frame.as_str()),
                            "family {family}: frame {i} repeats in frame {j}: {chain:?}"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn callback_submitter_failed_displays_its_kind() {
        let err = CallbackError::new(
            CallbackErrorKind::SubmitterFailed,
            Some(Source::from("submission failed")),
        );
        assert_eq!(err.to_string(), "submitter failed");
        assert_eq!(format!("{err:#}"), "submitter failed: submission failed");
    }

    #[test]
    fn callback_error_graded_split() {
        let timed_out = CallbackError::new(CallbackErrorKind::TimedOut, None);
        assert!(matches!(timed_out.kind(), CallbackErrorKind::TimedOut));

        let heartbeat = CallbackError::new(CallbackErrorKind::HeartbeatTimedOut, None);
        assert!(matches!(
            heartbeat.kind(),
            CallbackErrorKind::HeartbeatTimedOut
        ));

        let wire = WireError::new(Some("UserError"), Some("denied"));
        let external = CallbackError::new(
            CallbackErrorKind::ExternalFailure,
            Some(ReplayedFailure::source_from(wire)),
        );
        assert!(matches!(
            external.kind(),
            CallbackErrorKind::ExternalFailure
        ));
        // The wire fields the external caller reported are on the source.
        let source = Error::source(&external).expect("external carries wire source");
        let replayed = source.downcast_ref::<ReplayedFailure>().expect("replayed");
        assert_eq!(replayed.error_type(), Some("UserError"));

        let internal = CallbackError::new(CallbackErrorKind::Internal, Some(Source::from("oops")));
        assert!(matches!(internal.kind(), CallbackErrorKind::Internal));
    }

    #[test]
    fn operation_context_is_reachable() {
        let wire = WireError::new(Some("StepError"), Some("execution failed: boom"));
        let err = step_error_with_user_source()
            .with_operation("abc123", "FAILED")
            .with_wire(wire);
        assert_eq!(err.operation_id(), Some("abc123"));
        assert_eq!(err.status(), Some("FAILED"));
        assert_eq!(
            err.wire().and_then(WireError::error_type),
            Some("StepError")
        );
    }

    #[test]
    fn typed_error_names_the_users_type_on_the_wire() {
        let err = TypedError::new(UserBoom { detail: "typed" });
        assert_eq!(err.error_type(), "UserBoom");

        // The wire record derives the user's type from the wrapper...
        let wire = wire_error_for(&err, "Error");
        assert_eq!(wire.error_type(), Some("UserBoom"));
        assert_eq!(wire.error_message(), Some("user boom: typed"));

        // ...including through intermediate carriers (a child boundary).
        let child =
            ChildFnError::new(Box::new(TypedError::new(UserBoom { detail: "deep" })) as Source);
        let wire = child.failure_wire();
        assert_eq!(wire.error_type(), Some("UserBoom"));
    }

    #[test]
    fn typed_error_keeps_concrete_error_downcastable() {
        let err = TypedError::with_type("TransientError", UserBoom { detail: "x" });
        // The wrapped error is the next chain link: downcast reaches it.
        let source = Error::source(&err).expect("wraps the error");
        assert!(source.downcast_ref::<UserBoom>().is_some());
        // `Display` writes the type name alone, and the alternate form
        // names the type once, then the error's own frame.
        assert_eq!(err.to_string(), "TransientError");
        assert_eq!(format!("{err:#}"), "TransientError: user boom: x");
    }

    #[test]
    fn short_type_name_strips_module_paths() {
        assert_eq!(
            short_type_name("my_crate::errors::TransientError"),
            "TransientError"
        );
        assert_eq!(short_type_name("TransientError"), "TransientError");
        assert_eq!(
            short_type_name("wrapper::Holder<inner::Thing, other::T>"),
            "Holder<Thing, T>"
        );
    }

    #[test]
    fn contextual_error_adds_frame_without_flattening() {
        let source = ContextualError::source_from("checkpoint succeed", UserBoom { detail: "io" });
        assert_eq!(source.to_string(), "checkpoint succeed");
        let inner = source.source().expect("keeps cause");
        assert_eq!(inner.to_string(), "user boom: io");
    }

    /// The recorded step of the `wire_message` tests: message `inner`.
    fn recorded_step() -> OperationError {
        recorded_step_error(WireError::new(Some("InnerType"), Some("inner")))
    }

    /// The flattened chain of [`recorded_step`].
    const RECORDED_STEP_CHAIN: &str = "operation error: step: execution failed: inner";

    #[test]
    fn recorded_step_flattens_to_its_frames() {
        assert_eq!(chain_string(&recorded_step()), RECORDED_STEP_CHAIN);
    }

    #[test]
    fn wire_message_uses_the_first_record() {
        assert_eq!(wire_message(&recorded_step()), "inner");

        let contextual = ContextualError::source_from(
            "ctx",
            ReplayedFailure::source_from(WireError::new(Some("T"), Some("m"))),
        );
        assert_eq!(wire_message(&*contextual), "m");

        let outer_with_message =
            OperationError::from_kind(OperationErrorKind::ChildContext(ChildContextError::new(
                ChildContextErrorKind::ChildFailed,
                Some(Box::new(recorded_step())),
            )))
            .with_wire(WireError::new(Some("OuterType"), Some("outer")));
        assert_eq!(wire_message(&outer_with_message), "outer");

        // A record without a message stops the walk: the deeper record's
        // message is not used.
        let outer_without_message =
            OperationError::from_kind(OperationErrorKind::ChildContext(ChildContextError::new(
                ChildContextErrorKind::ChildFailed,
                Some(Box::new(recorded_step())),
            )))
            .with_wire(WireError::new(Some("OuterType"), None::<String>));
        assert_eq!(
            wire_message(&outer_without_message),
            "operation error: child_context: child failed: operation error: step: execution failed: inner"
        );

        let replayed_without_message =
            ReplayedFailure::new(WireError::new(Some("T"), None::<String>));
        assert_eq!(wire_message(&replayed_without_message), "T");

        let empty = recorded_step_error(WireError::new(Some("T"), Some("")));
        assert_eq!(wire_message(&empty), "");
    }

    /// A test wrapper of another crate's kind: not a propagation carrier.
    #[derive(Debug)]
    struct Wrapper(Source);
    impl fmt::Display for Wrapper {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "wrapper")
        }
    }
    impl Error for Wrapper {
        fn source(&self) -> Option<&(dyn Error + 'static)> {
            Some(&*self.0 as &(dyn Error + 'static))
        }
    }

    #[test]
    #[expect(clippy::too_many_lines)] // reason: one row per carrier and per stopping case
    fn wire_message_walks_only_transparent_carriers() {
        let boxed = || -> Source { Box::new(recorded_step()) };
        let carriers: Vec<(&str, Box<dyn Error + 'static>)> = vec![
            (
                "OperationError without a record",
                Box::new(OperationError::from_kind(OperationErrorKind::ChildContext(
                    ChildContextError::new(ChildContextErrorKind::ChildFailed, Some(boxed())),
                ))),
            ),
            (
                "StepError",
                Box::new(StepError::new(
                    StepErrorKind::ExecutionFailed,
                    Some(boxed()),
                )),
            ),
            (
                "WaitError",
                Box::new(WaitError::new(
                    WaitErrorKind::UnexpectedStatus(UnexpectedStatus::new("FAILED")),
                    Some(boxed()),
                )),
            ),
            (
                "InvokeError",
                Box::new(InvokeError::new(
                    InvokeErrorKind::FunctionFailed,
                    Some(boxed()),
                )),
            ),
            (
                "CallbackError",
                Box::new(CallbackError::new(
                    CallbackErrorKind::SubmitterFailed,
                    Some(boxed()),
                )),
            ),
            (
                "WaitForConditionError",
                Box::new(WaitForConditionError::new(
                    WaitForConditionErrorKind::CheckFailed,
                    Some(boxed()),
                )),
            ),
            (
                "ChildContextError",
                Box::new(ChildContextError::new(
                    ChildContextErrorKind::ChildFailed,
                    Some(boxed()),
                )),
            ),
            (
                "CombinatorError",
                Box::new(CombinatorError::new(
                    CombinatorErrorKind::FirstSettledFailed,
                    vec![boxed()],
                )),
            ),
            ("ChildFnError", Box::new(ChildFnError::new(boxed()))),
            (
                "ContextualError",
                ContextualError::source_from("ctx", boxed()),
            ),
        ];
        for (name, carrier) in &carriers {
            assert_eq!(wire_message(&**carrier), "inner", "{name}");
        }

        // A carrier without a source ends the walk.
        let sourceless = StepError::new(StepErrorKind::ExecutionFailed, None);
        assert_eq!(wire_message(&sourceless), "execution failed");

        // A `TypedError` is a carrier too: the walk passes through it.
        let typed = TypedError::with_type("OuterType", recorded_step());
        assert_eq!(wire_message(&typed), "inner");

        // Any other error stops the walk, and the message is the
        // flattened chain.
        let wrapper = Wrapper(boxed());
        assert_eq!(
            wire_message(&wrapper),
            format!("wrapper: {RECORDED_STEP_CHAIN}")
        );
        let client = crate::client::ExecutionClientError::with_source(
            crate::client::ExecutionClientErrorScope::Invocation,
            "checkpoint failed",
            recorded_step(),
        );
        assert_eq!(
            wire_message(&client),
            format!("durable: client: checkpoint failed: {RECORDED_STEP_CHAIN}")
        );
        let serde_error = match serde_json::from_str::<u32>("x") {
            Err(e) => e,
            Ok(v) => unreachable!("`x` is not a u32: {v}"),
        };
        let serialization = StepError::new(
            StepErrorKind::SerializationFailed,
            Some(Box::new(serde_error)),
        );
        assert_eq!(
            wire_message(&serialization),
            "serialization failed: expected value at line 1 column 1"
        );

        // The walk examines at most `CHAIN_WALK_LIMIT` errors.
        let layered = |layers: usize| -> Source {
            (0..layers).fold(boxed(), |source, _| {
                ContextualError::source_from("ctx", source)
            })
        };
        assert_eq!(wire_message(&*layered(10)), "inner");
        let past_the_limit = layered(11);
        assert_eq!(
            wire_message(&*past_the_limit),
            chain_string(&*past_the_limit)
        );
        assert_ne!(wire_message(&*past_the_limit), "inner");
    }

    /// A `TypedError` is one examined link of the recorded-message walk:
    /// nine contextual layers and a `TypedError` reach the record at the
    /// eleventh link, and ten layers and a `TypedError` do not.
    #[test]
    fn wire_message_counts_a_typed_error_as_one_link() {
        let typed_over = |layers: usize| -> Source {
            let typed: Source = Box::new(TypedError::with_type("T", recorded_step()));
            (0..layers).fold(typed, |source, _| {
                ContextualError::source_from("ctx", source)
            })
        };
        assert_eq!(wire_message(&*typed_over(9)), "inner");
        assert_eq!(
            wire_message(&*typed_over(10)),
            "ctx: ctx: ctx: ctx: ctx: ctx: ctx: ctx: ctx: ctx: \
             operation error: step: execution failed: inner"
        );
    }

    /// A `TypedError` around a record without a message: the walk stops
    /// at that record and the message is the original error's flattened
    /// chain, without the type name.
    #[test]
    fn wire_message_typed_record_without_message_flattens_the_chain() {
        let typed = TypedError::with_type(
            "Typed",
            recorded_step_error(WireError::new(Some("RecordType"), None::<String>)),
        );
        assert_eq!(
            wire_message(&typed),
            "operation error: step: execution failed: RecordType"
        );
        let empty = TypedError::with_type(
            "Typed",
            recorded_step_error(WireError::new(Some("RecordType"), Some(""))),
        );
        assert_eq!(wire_message(&empty), "");
    }

    /// A test error with one frame and an optional source.
    #[derive(Debug)]
    struct Frame(&'static str, Option<Source>);
    impl fmt::Display for Frame {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}", self.0)
        }
    }
    impl Error for Frame {
        fn source(&self) -> Option<&(dyn Error + 'static)> {
            self.1.as_deref().map(|s| s as &(dyn Error + 'static))
        }
    }

    #[derive(Debug)]
    struct PaymentDeclined;
    impl fmt::Display for PaymentDeclined {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "payment declined")
        }
    }
    impl Error for PaymentDeclined {}

    /// Each row of the issue's table: the recorded type and message of a
    /// `TypedError` chain, and its flattened chain without type names.
    #[test]
    fn chain_string_omits_typed_error_frames() {
        let failed_step = || recorded_step_error(WireError::new(Some("StepType"), Some("boom")));
        let rows: Vec<(Box<dyn Error + 'static>, &str, &str, &str)> = vec![
            (
                Box::new(TypedError::with_type("PaymentError", "declined")),
                "PaymentError",
                "declined",
                "declined",
            ),
            (
                Box::new(TypedError::new(PaymentDeclined)),
                "PaymentDeclined",
                "payment declined",
                "payment declined",
            ),
            (
                Box::new(TypedError::with_type("PaymentError", failed_step())),
                "PaymentError",
                "boom",
                "operation error: step: execution failed: boom",
            ),
            (
                Box::new(Frame(
                    "charging",
                    Some(Box::new(TypedError::with_type("PaymentError", "declined"))),
                )),
                "PaymentError",
                "charging: declined",
                "charging: declined",
            ),
            (
                Box::new(TypedError::with_type("A", TypedError::with_type("B", "x"))),
                "A",
                "x",
                "x",
            ),
            (
                Box::new(TypedError::with_type(
                    "Typed",
                    Frame("a", Some(Box::new(Frame("b", None)))),
                )),
                "Typed",
                "a: b",
                "a: b",
            ),
        ];
        for (err, error_type, message, chain) in &rows {
            let wire = wire_error_for(&**err, "Error");
            assert_eq!(wire.error_type(), Some(*error_type), "{err:#}");
            assert_eq!(wire.error_message(), Some(*message), "{err:#}");
            assert_eq!(chain_string(&**err), *chain, "{err:#}");
        }
    }

    #[test]
    fn wire_message_preserves_non_message_fields() {
        let inner_wire = || {
            WireError::new(Some("InnerType"), Some("inner"))
                .with_error_data(Some("inner-data"))
                .with_stack_trace(vec!["inner-frame".to_owned()])
        };
        let child =
            OperationError::from_kind(OperationErrorKind::ChildContext(ChildContextError::new(
                ChildContextErrorKind::ChildFailed,
                Some(Box::new(recorded_step_error(inner_wire()))),
            )));
        let wire = wire_error_for(&child, "Error");
        assert_eq!(wire.error_type(), Some("ChildContextError"));
        assert_eq!(wire.error_message(), Some("inner"));
        assert_eq!(wire.error_data(), Some("inner-data"));
        assert_eq!(wire.stack_trace(), ["inner-frame"]);

        let contextual =
            ContextualError::source_from("serialize", recorded_step_error(inner_wire()));
        let wire = serialization_failure_wire(&*contextual);
        assert_eq!(wire.error_type(), Some("SerializationError"));
        assert_eq!(wire.error_message(), Some("inner"));
        assert_eq!(wire.error_data(), Some("inner-data"));
        assert_eq!(wire.stack_trace(), ["inner-frame"]);

        // A `TypedError` names the type, and the record below it still
        // supplies the message, data and stack.
        let typed = TypedError::with_type("Typed", recorded_step_error(inner_wire()));
        let wire = wire_error_for(&typed, "Error");
        assert_eq!(wire.error_type(), Some("Typed"));
        assert_eq!(wire.error_message(), Some("inner"));
        assert_eq!(wire.error_data(), Some("inner-data"));
        assert_eq!(wire.stack_trace(), ["inner-frame"]);

        // Its own data wins over the record's.
        let typed = TypedError::with_type("Typed", recorded_step_error(inner_wire()))
            .with_error_data("typed-data");
        let wire = wire_error_for(&typed, "Error");
        assert_eq!(wire.error_type(), Some("Typed"));
        assert_eq!(wire.error_message(), Some("inner"));
        assert_eq!(wire.error_data(), Some("typed-data"));
        assert_eq!(wire.stack_trace(), ["inner-frame"]);
    }
}