faucet-core 1.14.0

Shared types, traits, and utilities for the faucet-stream ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
//! Multi-edge pipeline topology — fan-out (tee), fan-in (merge), and
//! hash-join over an explicit node graph (issues #71 and #72).
//!
//! The single-source→single-sink [`Pipeline`](crate::Pipeline) covers the
//! common case. A [`Topology`] generalizes it to a directed acyclic graph of
//! typed nodes connected by edges, so one run can *tee* a source's records to
//! several sinks, *merge* several sources into one sink, or *join* two
//! upstreams by key. It is the in-process primitive behind the CLI's
//! `pipeline.nodes` / `edges` topology mode.
//!
//! ## Node kinds
//!
//! | Kind | In | Out | Semantics |
//! |------|----|-----|-----------|
//! | [`NodeKind::Source`] | 0 | 1 | Drives [`Source::stream_pages`]. |
//! | [`NodeKind::Transform`] | 1 | 1 | Applies compiled transform stages per page. |
//! | [`NodeKind::Tee`] | 1 | N | Clones each page to every downstream edge. |
//! | [`NodeKind::Merge`] | N | 1 | Forwards pages from all inputs in arrival order. |
//! | [`NodeKind::Join`] | 2 | 1 | Hash-join: buffer the build edge, enrich the probe edge. |
//! | [`NodeKind::Sink`] | 1 | 0 | Drives [`run_stream`] (write → flush → persist). |
//!
//! ## Execution
//!
//! Each node runs as a cooperatively-scheduled future; edges are bounded
//! [`tokio::sync::mpsc`] channels so the slowest consumer paces its producer
//! (backpressure). No OS threads are spawned — the topology runs on whatever
//! runtime drives [`Topology::run`], overlapping the nodes' I/O. Sink nodes
//! reuse [`run_stream`], so DLQ routing, bookmark persistence, and the full
//! observability metric set come for free.
//!
//! ## State
//!
//! Each terminal sink owns its bookmark under `{pipeline}::{node_id}`. On
//! restart the source resumes from the sinks' stored bookmark only when *every*
//! sink has one and they all agree (exactly-once orders committed positions
//! instead — see below); otherwise the source replays in full, so sinks that
//! may diverge must be idempotent — a faster sink will re-see already-written
//! pages. A state-store read error fails the run rather than replaying.
//!
//! Resuming is deliberately conservative, because the only safe direction to err
//! is *replay* (duplicates) and never *skip* (loss) — see [`start_bookmark`]:
//!
//! - **One source node only.** With two or more sources there is no way to tell
//!   which source a given sink's bookmark came from, so applying one to all of
//!   them would resume a source at a position that is not its own. Multi-source
//!   graphs therefore replay in full.
//! - **Comparable, agreeing bookmarks only.** Sink bookmarks are compared for
//!   equality, not ordered. Resume positions are frequently structured (CDC LSN
//!   maps, Kafka offset maps), and [`json_gt`](crate::replication::json_gt)'s
//!   object arm orders by *serialized
//!   text*, which is not the replication order — so a "minimum" picked that way
//!   can sit ahead of the true minimum and skip records. Divergent bookmarks
//!   therefore replay in full rather than guess.
//! - **Exactly-once orders by committed position.** Each sink's position comes
//!   from its state, overridden by the bookmark embedded in its commit token
//!   when the token is ahead. The source resumes from the earliest position;
//!   a sink ahead of it skips what it already committed — by position when the
//!   source can order its positions ([`Source::position_le`]), otherwise by its
//!   commit-token sequence, with every sink started at the laggard's sequence so
//!   the sequences keep comparing across sinks.
//! - **A merge that rejoins one source's copies gates the positions.** After a
//!   tee fans a source out and a merge joins the branches back, a position is
//!   forwarded only once every branch has delivered it, so a sink never persists
//!   a position while another branch's copy of that page is still in flight. A
//!   join may not read both of its sides from one upstream node: it drains its
//!   build side first, which would block the shared upstream forever.
//!
//! A sink node in `write_mode: overwrite` stages before its first write and swaps
//! its staging in — then persists its position — only once every node of the
//! graph has succeeded and the run was not cancelled; otherwise it discards the
//! staging. A sink whose input closed because an upstream node failed reports
//! that failure instead of a successful, partial run.
//!
//! ## Governance passes
//!
//! Sink nodes reuse [`run_stream`], so the masking / quality / contract /
//! schema-drift passes and the resilience policy apply exactly as they do to a
//! single-source pipeline — supply them via
//! [`Topology::run_with`]. Masking is destination-scoped and is
//! therefore keyed by sink node id.

use crate::dlq::DlqConfig;
use crate::error::FaucetError;
use crate::join::HashJoin;
use crate::observability::{Labels, RunStreamOptions, instrumented_apply_stages};
use crate::pipeline::{DEFAULT_BATCH_SIZE, StreamPage, run_stream};
use crate::stage::CompiledStage;
use crate::state::StateStore;
use crate::traits::{Sink, Source};
use futures::StreamExt;
use metrics::{Label, SharedString, counter, histogram};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

pub use crate::join::{JoinConfig, JoinMode, KeyNormalize, OnCollision, OnDuplicate, Projection};

/// Default bounded-channel capacity for topology edges.
pub const DEFAULT_CHANNEL_CAPACITY: usize = 4;

/// A join node: the pure [`JoinConfig`] plus the labels of its two incoming
/// edges identifying which upstream is the build (right) side and which is the
/// probe (left) side.
#[derive(Debug, Clone)]
pub struct JoinNode {
    /// Pure join logic configuration.
    pub config: JoinConfig,
    /// Label of the incoming edge feeding the build (right) side.
    pub build_edge: String,
    /// Label of the incoming edge feeding the probe (left) side.
    pub probe_edge: String,
}

/// A typed topology node.
pub enum NodeKind {
    /// A data source (0 in, 1 out).
    Source(Box<dyn Source>),
    /// Transform stages applied per page (1 in, 1 out).
    Transform(Vec<CompiledStage>),
    /// Fan-out: clone each page to every downstream edge (1 in, N out).
    Tee {
        /// Bounded-channel capacity for each outgoing edge.
        capacity: usize,
        /// Optional expected fan-out (outgoing edge count) sanity check.
        fanout: Option<usize>,
    },
    /// Fan-in: forward pages from all inputs in arrival order (N in, 1 out).
    Merge,
    /// Hash-join two upstreams by key (2 in, 1 out).
    Join(JoinNode),
    /// A data sink (1 in, 0 out).
    Sink(Box<dyn Sink>),
}

impl std::fmt::Debug for NodeKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.kind_str())
    }
}

impl NodeKind {
    /// Short name of this node kind, used in errors and metric labels.
    pub fn kind_str(&self) -> &'static str {
        match self {
            NodeKind::Source(_) => "source",
            NodeKind::Transform(_) => "transform",
            NodeKind::Tee { .. } => "tee",
            NodeKind::Merge => "merge",
            NodeKind::Join(_) => "join",
            NodeKind::Sink(_) => "sink",
        }
    }

    fn is_source(&self) -> bool {
        matches!(self, NodeKind::Source(_))
    }

    fn is_sink(&self) -> bool {
        matches!(self, NodeKind::Sink(_))
    }
}

/// A node in the topology: a stable id plus its typed kind.
#[derive(Debug)]
pub struct Node {
    /// Stable node id (used as the metric `node` label and state-key suffix).
    pub id: String,
    /// The node's kind.
    pub kind: NodeKind,
}

/// A directed edge from one node's output to another's input.
#[derive(Debug, Clone)]
pub struct Edge {
    /// Producer node id.
    pub from: String,
    /// Consumer node id.
    pub to: String,
    /// Optional edge label, used by [`NodeKind::Join`] to distinguish its
    /// build edge from its probe edge.
    pub label: Option<String>,
}

/// What to do when a node fails.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TopologyOnError {
    /// Abort the whole topology on the first node failure (default).
    #[default]
    Propagate,
    /// Let every node run to completion; collect and report failures without
    /// aborting healthy branches.
    Continue,
}

/// The per-run governance passes applied to every sink node.
///
/// These are the same passes [`crate::Pipeline`] applies in matrix mode; a
/// topology wires them through [`run_stream`] per sink node so a graph pipeline
/// gets identical enforcement. Masking is destination-scoped (a rule may name
/// the sinks it applies to), so it is keyed by **sink node id** and compiled by
/// the caller; the rest are pipeline-wide.
///
/// `#[non_exhaustive]`: construct with [`TopologyGovernance::new`] (or
/// `Default`) and assign the fields you need. This is deliberate — adding a pass
/// later would otherwise be a major-version break for every downstream crate,
/// which is exactly the trap `TopologyOptions` is already in.
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct TopologyGovernance {
    /// Compiled data-quality checks, applied per page in every sink node.
    #[cfg(feature = "quality")]
    pub quality: Option<Arc<crate::quality::CompiledQuality>>,
    /// Compiled data contract, applied per page in every sink node.
    #[cfg(feature = "contract")]
    pub contract: Option<Arc<crate::contract::CompiledContract>>,
    /// Compiled masking policy per sink node id. A sink node with no entry runs
    /// no masking pass (the caller found no rule that applies to it).
    #[cfg(feature = "masking")]
    pub masking_by_sink: HashMap<String, Arc<crate::masking::CompiledMasking>>,
    /// Compiled schema-drift policy, applied per page in every sink node.
    pub schema_drift: Option<crate::drift::SchemaDriftPolicy>,
    /// Resilience policy (retry / circuit breaker / poison) for sink-side
    /// writes, flushes, and state puts.
    pub resilience: Option<crate::resilience::ResiliencePolicy>,
    /// Delivery guarantee for every sink node (#458).
    ///
    /// `ExactlyOnce` gives each sink node its own commit-token scope — its state
    /// key, `{pipeline}::{node_id}` — so a sink that durably committed a page
    /// skips it on resume independently of its siblings. Lives here rather than on
    /// [`TopologyOptions`] because that struct is exhaustively constructible
    /// through the public API, so a new field there is a major break; this one is
    /// `#[non_exhaustive]`. It is a per-sink write policy either way.
    ///
    /// The caller is responsible for the gate (deterministic-replay source,
    /// idempotent sinks, durable state, no DLQ) — `run_stream` re-checks the sink
    /// side and downgrades with a warning rather than pretending.
    pub delivery: crate::idempotency::DeliveryMode,
    /// Each sink node's DLQ as a governed destination (#870), built by the
    /// caller with [`Governance::dlq_config`](crate::governance::Governance::dlq_config).
    /// A sink node with no entry writes to [`TopologyOptions::dlq`].
    pub dlq_by_sink: HashMap<String, DlqConfig>,
}

impl TopologyGovernance {
    /// A governance set with no passes configured.
    pub fn new() -> Self {
        Self::default()
    }
}

/// Per-run options for [`Topology::run`].
#[derive(Clone)]
pub struct TopologyOptions {
    /// Pipeline name (metric `pipeline` label).
    pub pipeline_name: String,
    /// Run id (span attribute).
    pub run_id: String,
    /// Batch-size hint passed to source nodes' `stream_pages`.
    pub batch_size: usize,
    /// State store shared by every sink node (each under `{pipeline}::{node_id}`).
    pub state_store: Option<Arc<dyn StateStore>>,
    /// DLQ applied to every sink node.
    pub dlq: Option<DlqConfig>,
    /// Cooperative cancellation.
    pub cancel: Option<CancellationToken>,
    /// Failure policy.
    pub on_error: TopologyOnError,
    /// Default bounded-channel capacity for edges not fed by a tee.
    pub default_channel_capacity: usize,
}

/// How long a node gets to stop at its next page boundary and flush after another
/// node has failed under [`TopologyOnError::Propagate`], before it is aborted.
///
/// Mirrors the CLI executor's `on_error: stop` grace: without it a buffered sink
/// is dropped mid-write, orphaning a multipart upload or leaving a footer-less
/// Parquet file (#146 H16, #456 M1). The window opens only once a failure has
/// cancelled the run, so a healthy run is never bounded by it.
pub const STOP_FLUSH_GRACE: Duration = Duration::from_secs(30);

impl Default for TopologyOptions {
    fn default() -> Self {
        Self {
            pipeline_name: "unnamed".into(),
            run_id: String::new(),
            batch_size: DEFAULT_BATCH_SIZE,
            state_store: None,
            dlq: None,
            cancel: None,
            on_error: TopologyOnError::default(),
            default_channel_capacity: DEFAULT_CHANNEL_CAPACITY,
        }
    }
}

impl TopologyOptions {
    /// New options with the given pipeline name.
    pub fn new(pipeline_name: impl Into<String>) -> Self {
        Self {
            pipeline_name: pipeline_name.into(),
            ..Default::default()
        }
    }

    /// Attach a state store.
    pub fn with_state_store(mut self, store: Arc<dyn StateStore>) -> Self {
        self.state_store = Some(store);
        self
    }

    /// Attach a DLQ applied to every sink node.
    pub fn with_dlq(mut self, dlq: DlqConfig) -> Self {
        self.dlq = Some(dlq);
        self
    }

    /// Attach a cancellation token.
    pub fn with_cancel(mut self, cancel: CancellationToken) -> Self {
        self.cancel = Some(cancel);
        self
    }

    /// Set the failure policy.
    pub fn with_on_error(mut self, on_error: TopologyOnError) -> Self {
        self.on_error = on_error;
        self
    }

    /// Set the batch-size hint.
    pub fn with_batch_size(mut self, batch_size: usize) -> Self {
        self.batch_size = batch_size;
        self
    }
}

/// Typed class of a node's failure, for callers that react to a *kind* of
/// failure rather than report it (PRINCIPLES §6 — never recover a class by
/// grepping a message).
///
/// Non-exhaustive: new classes are additive, so matching must carry a `_` arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NodeErrorKind {
    /// [`FaucetError::CircuitOpen`] — the resilience circuit breaker tripped.
    /// `faucet schedule` delays its next tick by the policy cooldown rather
    /// than re-firing immediately at a destination that just tripped.
    CircuitOpen,
    /// Any other failure. Deliberately distinct from `None`, which means the
    /// node did not fail at all.
    Other,
}

impl NodeErrorKind {
    /// Classify a node's failure while the typed error is still intact.
    ///
    /// One table, at the boundary where the error is stringified — the whole
    /// point of the field is that no consumer has to re-derive this from prose.
    pub fn classify(error: &FaucetError) -> Self {
        match error {
            FaucetError::CircuitOpen { .. } => Self::CircuitOpen,
            _ => Self::Other,
        }
    }
}

/// What one node did, for callers that need per-node attribution (the CLI emits
/// notifications and evaluates SLAs per **sink node**, which needs to know which
/// node failed — [`TopologyResult::errors`] is a flat list of messages).
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct NodeReport {
    /// Node id.
    pub node_id: String,
    /// Node kind (`"source"`, `"sink"`, …).
    pub kind: &'static str,
    /// Records written (sink nodes only; 0 elsewhere).
    pub records: usize,
    /// Final bookmark (sink nodes only).
    pub bookmark: Option<Value>,
    /// The node's failure, if it failed.
    pub error: Option<String>,
    /// Typed class of [`error`](Self::error), for callers that react to a kind
    /// of failure rather than render it. `None` when the node succeeded.
    ///
    /// Additive on a `#[non_exhaustive]` struct, so a minor bump under the
    /// declared semver contract.
    pub error_kind: Option<NodeErrorKind>,
}

/// A topology run with per-node attribution.
///
/// `#[non_exhaustive]`: this is an output callers read, never construct, so
/// keeping it open means a future per-node field is a minor release rather than
/// a breaking one — the mistake [`TopologyResult`] cannot now undo.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct TopologyRun {
    /// The aggregate result, identical to what [`Topology::run`] returns.
    pub result: TopologyResult,
    /// One entry per node, in the graph's deterministic (sorted-id) order.
    pub nodes: Vec<NodeReport>,
    /// Records emitted per **source** node, keyed by node id (#459). Lives here
    /// rather than on [`TopologyResult`] so adding it stays a minor change.
    pub per_source: HashMap<String, usize>,
}

/// Outcome of a topology run.
#[derive(Debug, Clone, Default)]
pub struct TopologyResult {
    /// Total records written across all sink nodes.
    pub records_written: usize,
    /// Per-sink-node records written, keyed by node id.
    pub per_sink: HashMap<String, usize>,
    /// Per-sink-node final bookmark, keyed by node id.
    pub bookmarks: HashMap<String, Option<Value>>,
    /// Node failures observed under [`TopologyOnError::Continue`] (empty under
    /// `Propagate`, which returns `Err` on the first failure instead).
    pub errors: Vec<String>,
}

/// One incoming edge of a node: its optional label plus the receiving end of
/// the channel.
struct InEdge {
    label: Option<String>,
    from: String,
    rx: mpsc::Receiver<StreamPage>,
}

/// Pop the single input receiver from a one-input node's edge list.
fn take_single(mut ins: Vec<InEdge>) -> Option<mpsc::Receiver<StreamPage>> {
    ins.drain(..).next().map(|ie| ie.rx)
}

/// Remove and return the input receiver whose edge carries `label`.
fn take_by_label(ins: &mut Vec<InEdge>, label: &str) -> Option<mpsc::Receiver<StreamPage>> {
    ins.iter()
        .position(|ie| ie.label.as_deref() == Some(label))
        .map(|pos| ins.remove(pos).rx)
}

/// What a completed node future reports back.
enum NodeOutcome {
    Sink {
        node_id: String,
        records: usize,
        bookmark: Option<Value>,
        /// Kept so a fully successful graph can finalize it (#753).
        sink: Box<dyn Sink>,
        /// Where an overwrite sink's bookmark goes once its staging is
        /// swapped in (#789 CORE-14).
        deferred: Option<DeferredState>,
    },
    /// A source node and how many records it emitted. Needed so a lineage /
    /// catalog edge can report the volume *that input* contributed rather than
    /// the sink's total, which would over-count a merge (#459).
    Source {
        node_id: String,
        records: usize,
    },
    Other,
}

/// A directed acyclic graph of typed nodes.
///
/// Build one with [`Topology::builder`], then drive it with [`Topology::run`].
#[derive(Debug)]
pub struct Topology {
    nodes: Vec<Node>,
    edges: Vec<Edge>,
}

impl Topology {
    /// Start building a topology.
    pub fn builder() -> TopologyBuilder {
        TopologyBuilder::default()
    }

    /// The nodes, in insertion order.
    pub fn nodes(&self) -> &[Node] {
        &self.nodes
    }

    /// The edges, in insertion order.
    pub fn edges(&self) -> &[Edge] {
        &self.edges
    }

    /// Validate the graph: unique ids, existing endpoints, per-kind arity,
    /// tee fan-out, join edge labels, acyclicity, and source→sink
    /// reachability. Returns [`FaucetError::Config`] with a descriptive
    /// message on the first violation.
    pub fn validate(&self) -> Result<(), FaucetError> {
        if self.nodes.is_empty() {
            return Err(cfg("topology has no nodes"));
        }

        // Unique ids.
        let mut seen = HashSet::new();
        for n in &self.nodes {
            if !seen.insert(n.id.as_str()) {
                return Err(cfg(format!("duplicate node id '{}'", n.id)));
            }
        }
        let ids: HashSet<&str> = seen;

        // Edge endpoints exist.
        for e in &self.edges {
            if !ids.contains(e.from.as_str()) {
                return Err(cfg(format!(
                    "edge references unknown 'from' node '{}'",
                    e.from
                )));
            }
            if !ids.contains(e.to.as_str()) {
                return Err(cfg(format!("edge references unknown 'to' node '{}'", e.to)));
            }
        }

        // In/out degrees.
        let mut in_deg: HashMap<&str, usize> = HashMap::new();
        let mut out_deg: HashMap<&str, usize> = HashMap::new();
        for e in &self.edges {
            *out_deg.entry(e.from.as_str()).or_default() += 1;
            *in_deg.entry(e.to.as_str()).or_default() += 1;
        }

        let mut has_source = false;
        let mut has_sink = false;
        for n in &self.nodes {
            let i = in_deg.get(n.id.as_str()).copied().unwrap_or(0);
            let o = out_deg.get(n.id.as_str()).copied().unwrap_or(0);
            match &n.kind {
                NodeKind::Source(source) => {
                    has_source = true;
                    arity(&n.id, "source", i == 0, o == 1, "0 in, exactly 1 out")?;
                    if source.consumes_destructively() {
                        return Err(cfg(format!(
                            "source '{}' ({}) acknowledges messages as it is read past each \
                             page, and a graph polls its sources ahead of its sinks, so a \
                             failed or cancelled sink would lose messages that were already \
                             acked; run this source in a linear pipeline instead",
                            n.id,
                            source.connector_name()
                        )));
                    }
                }
                NodeKind::Transform(_) => {
                    arity(&n.id, "transform", i == 1, o == 1, "exactly 1 in, 1 out")?;
                }
                NodeKind::Tee { fanout, .. } => {
                    arity(&n.id, "tee", i == 1, o >= 2, "exactly 1 in, 2+ out")?;
                    if let Some(f) = fanout
                        && *f != o
                    {
                        return Err(cfg(format!(
                            "tee '{}' declares fanout {f} but has {o} outgoing edges",
                            n.id
                        )));
                    }
                }
                NodeKind::Merge => {
                    arity(&n.id, "merge", i >= 2, o == 1, "2+ in, exactly 1 out")?;
                }
                NodeKind::Join(j) => {
                    arity(&n.id, "join", i == 2, o == 1, "exactly 2 in, 1 out")?;
                    self.validate_join_edges(&n.id, j)?;
                }
                NodeKind::Sink(_) => {
                    has_sink = true;
                    arity(&n.id, "sink", i == 1, o == 0, "exactly 1 in, 0 out")?;
                }
            }
        }

        if !has_source {
            return Err(cfg("topology has no source node"));
        }
        if !has_sink {
            return Err(cfg("topology has no sink node"));
        }

        self.detect_cycle()?;
        self.check_reachability()?;
        self.check_join_inputs()?;
        Ok(())
    }

    /// A join drains its whole build side before it reads the probe side, so its
    /// two inputs must not share an upstream node. A tee feeding both sides blocks
    /// on the probe send once that channel fills, the build side never closes, and
    /// the run hangs (#789 CORE-13).
    fn check_join_inputs(&self) -> Result<(), FaucetError> {
        let mut rev: HashMap<&str, Vec<&Edge>> = HashMap::new();
        for e in &self.edges {
            rev.entry(e.to.as_str()).or_default().push(e);
        }
        for n in &self.nodes {
            let NodeKind::Join(j) = &n.kind else {
                continue;
            };
            let side = |label: &str| -> Option<HashSet<String>> {
                let from = rev
                    .get(n.id.as_str())?
                    .iter()
                    .find(|e| e.label.as_deref() == Some(label))?
                    .from
                    .as_str();
                let mut set = ancestors_of(from, &rev);
                set.insert(from.to_string());
                Some(set)
            };
            let (Some(build), Some(probe)) = (side(&j.build_edge), side(&j.probe_edge)) else {
                continue;
            };
            let mut shared: Vec<&String> = build.intersection(&probe).collect();
            shared.sort();
            if let Some(node) = shared.first() {
                return Err(cfg(format!(
                    "join '{}' reads both its build and probe sides from node '{node}'; the \
                     join drains its build side before reading the probe side, so a shared \
                     upstream blocks once the probe channel fills and the run never ends. \
                     Feed the two sides from separate source nodes",
                    n.id
                )));
            }
        }
        Ok(())
    }

    fn validate_join_edges(&self, node_id: &str, j: &JoinNode) -> Result<(), FaucetError> {
        let labels: Vec<&str> = self
            .edges
            .iter()
            .filter(|e| e.to == node_id)
            .filter_map(|e| e.label.as_deref())
            .collect();
        for want in [j.build_edge.as_str(), j.probe_edge.as_str()] {
            if !labels.contains(&want) {
                return Err(cfg(format!(
                    "join '{node_id}' has no incoming edge labelled '{want}' (known labels: {labels:?})"
                )));
            }
        }
        if j.build_edge == j.probe_edge {
            return Err(cfg(format!(
                "join '{node_id}' build_edge and probe_edge must differ"
            )));
        }
        Ok(())
    }

    /// DFS cycle detection (three-color).
    fn detect_cycle(&self) -> Result<(), FaucetError> {
        let mut adj: HashMap<&str, Vec<&str>> = HashMap::new();
        for e in &self.edges {
            adj.entry(e.from.as_str()).or_default().push(e.to.as_str());
        }
        #[derive(Clone, Copy, PartialEq)]
        enum Color {
            White,
            Gray,
            Black,
        }
        let mut color: HashMap<&str, Color> = self
            .nodes
            .iter()
            .map(|n| (n.id.as_str(), Color::White))
            .collect();

        // Iterative DFS to avoid stack overflow on deep graphs.
        for start in self.nodes.iter().map(|n| n.id.as_str()) {
            if color[start] != Color::White {
                continue;
            }
            let mut stack: Vec<(&str, usize)> = vec![(start, 0)];
            *color.get_mut(start).unwrap() = Color::Gray;
            while let Some((node, idx)) = stack.last().copied() {
                let neighbours = adj.get(node).map(|v| v.as_slice()).unwrap_or(&[]);
                if idx < neighbours.len() {
                    stack.last_mut().unwrap().1 += 1;
                    let next = neighbours[idx];
                    match color[next] {
                        Color::Gray => {
                            return Err(cfg(format!("topology has a cycle through node '{next}'")));
                        }
                        Color::White => {
                            *color.get_mut(next).unwrap() = Color::Gray;
                            stack.push((next, 0));
                        }
                        Color::Black => {}
                    }
                } else {
                    *color.get_mut(node).unwrap() = Color::Black;
                    stack.pop();
                }
            }
        }
        Ok(())
    }

    /// Every source must reach at least one sink, and every sink must be
    /// reachable from at least one source.
    fn check_reachability(&self) -> Result<(), FaucetError> {
        let mut adj: HashMap<&str, Vec<&str>> = HashMap::new();
        let mut radj: HashMap<&str, Vec<&str>> = HashMap::new();
        for e in &self.edges {
            adj.entry(e.from.as_str()).or_default().push(e.to.as_str());
            radj.entry(e.to.as_str()).or_default().push(e.from.as_str());
        }
        let sink_ids: HashSet<&str> = self
            .nodes
            .iter()
            .filter(|n| n.kind.is_sink())
            .map(|n| n.id.as_str())
            .collect();
        let source_ids: HashSet<&str> = self
            .nodes
            .iter()
            .filter(|n| n.kind.is_source())
            .map(|n| n.id.as_str())
            .collect();

        for src in &source_ids {
            if !reaches_any(src, &adj, &sink_ids) {
                return Err(cfg(format!("source '{src}' does not reach any sink node")));
            }
        }
        for sink in &sink_ids {
            if !reaches_any(sink, &radj, &source_ids) {
                return Err(cfg(format!(
                    "sink '{sink}' is not reachable from any source node"
                )));
            }
        }
        Ok(())
    }

    /// Run the topology to completion with no governance passes.
    ///
    /// Equivalent to [`Topology::run_with`] with a default
    /// [`TopologyGovernance`] — kept as-is so existing callers are unaffected.
    pub async fn run(self, opts: TopologyOptions) -> Result<TopologyResult, FaucetError> {
        self.run_with(opts, TopologyGovernance::default()).await
    }

    /// Run the topology to completion, applying `governance` to every sink node.
    ///
    /// Separate from [`Topology::run`] rather than a field on
    /// [`TopologyOptions`]: that struct is exhaustively constructible through the
    /// public API, so adding a field to it would be a major-version break for
    /// every downstream crate. A new method is additive.
    pub async fn run_with(
        self,
        opts: TopologyOptions,
        governance: TopologyGovernance,
    ) -> Result<TopologyResult, FaucetError> {
        self.run_reported(opts, governance).await.map(|r| r.result)
    }

    /// [`Topology::run_with`] with **per-node attribution**.
    ///
    /// The CLI emits notifications and evaluates SLAs per *sink node*, which needs
    /// to know which node failed; [`TopologyResult::errors`] is only a flat list
    /// of messages. Additive rather than a change to `run_with`'s return type,
    /// which would break every caller (#459).
    pub async fn run_reported(
        self,
        opts: TopologyOptions,
        governance: TopologyGovernance,
    ) -> Result<TopologyRun, FaucetError> {
        match self.run_attributed(opts, governance).await {
            (_, Some(e)) => Err(e),
            (run, None) => Ok(run),
        }
    }

    /// [`Topology::run_reported`] that keeps the per-node attribution when the
    /// run fails.
    ///
    /// `run_reported` returns only the error under [`TopologyOnError::Propagate`],
    /// so a caller reporting per sink node (notifications, SLA, lineage) had
    /// nothing to report from and skipped the failure entirely (#789 CLI-18).
    /// Here the [`TopologyRun`] is always returned, alongside the error that
    /// `run_reported` would have returned. A sink that a failed node feeds is
    /// reported as failed too: its input closing looked like a normal end of
    /// stream, but it never received its complete input.
    #[allow(clippy::disallowed_methods)] // a runtime timer, not a connector backend call
    pub async fn run_attributed(
        self,
        opts: TopologyOptions,
        governance: TopologyGovernance,
    ) -> (TopologyRun, Option<FaucetError>) {
        if let Err(e) = self.validate() {
            return (TopologyRun::default(), Some(e));
        }
        let facts = GraphFacts::of(&self.nodes, &self.edges);
        let Topology { nodes, edges } = self;

        let order: Vec<(String, &'static str)> = nodes
            .iter()
            .map(|n| (n.id.clone(), n.kind.kind_str()))
            .collect();

        // Sources are shared (`Arc`) so a sink node can ask the graph's source to
        // order two of its positions when it skips pages it already committed.
        let mut sources: HashMap<String, Arc<dyn Source>> = HashMap::new();
        let mut rest: Vec<Node> = Vec::with_capacity(nodes.len());
        for n in nodes {
            match n.kind {
                NodeKind::Source(s) => {
                    sources.insert(n.id, Arc::from(s));
                }
                kind => rest.push(Node { id: n.id, kind }),
            }
        }
        let source_count = sources.len();
        let only_source: Option<Arc<dyn Source>> = if source_count == 1 {
            sources.values().next().cloned()
        } else {
            None
        };

        // Capacity per outgoing edge: a tee's edges use its configured
        // capacity; everything else uses the default.
        let tee_cap: HashMap<String, usize> = rest
            .iter()
            .filter_map(|n| match &n.kind {
                NodeKind::Tee { capacity, .. } => Some((n.id.clone(), *capacity)),
                _ => None,
            })
            .collect();

        // The graph's source replay capability. Only meaningful with exactly one
        // source — which is also the only shape exactly-once is allowed in (#458).
        let source_replay = only_source.as_ref().map(|s| s.replay_guarantee());
        // How sink nodes store their bookmarks (#736): owned by the graph's
        // only source when there is one; a multi-source graph never resumes
        // from a sink bookmark, so its bookmarks are owned by the graph.
        let codec = only_source
            .as_ref()
            .map(|s| crate::state_version::StateCodec::for_source(s.as_ref(), false))
            .unwrap_or(crate::state_version::StateCodec {
                owner: "topology".into(),
                schema: 0,
                legacy: false,
            });

        let sink_refs: Vec<(String, Option<&dyn Sink>)> = rest
            .iter()
            .filter_map(|n| match &n.kind {
                NodeKind::Sink(s) => Some((n.id.clone(), Some(s.as_ref()))),
                _ => None,
            })
            .collect();
        let plan = match compute_resume(
            &opts,
            &sink_refs,
            source_count,
            governance.delivery,
            only_source.as_deref(),
        )
        .await
        {
            Ok(p) => p,
            Err(e) => return (TopologyRun::default(), Some(e)),
        };
        drop(sink_refs);

        // Every node runs under one cooperative token: a caller's cancel reaches
        // it, and under `Propagate` a node failure cancels it so the siblings stop
        // at their next page boundary — including a node parked on a full or empty
        // channel, which a token checked only after `recv` returns never reaches
        // (#789 CORE-13).
        let coop = opts.cancel.clone().unwrap_or_default().child_token();
        let failed: FailedNodes = Arc::new(std::sync::Mutex::new(HashMap::new()));

        // Build channels.
        let mut outs: HashMap<String, Vec<mpsc::Sender<StreamPage>>> = HashMap::new();
        let mut ins: HashMap<String, Vec<InEdge>> = HashMap::new();
        for e in &edges {
            let cap = tee_cap
                .get(e.from.as_str())
                .copied()
                .unwrap_or(opts.default_channel_capacity)
                .max(1);
            let (tx, rx) = mpsc::channel(cap);
            outs.entry(e.from.clone()).or_default().push(tx);
            ins.entry(e.to.clone()).or_default().push(InEdge {
                label: e.label.clone(),
                from: e.from.clone(),
                rx,
            });
        }

        // Build one future per node. `Send + 'static` so each node can own a
        // task (see the spawn below).
        type NodeFut = Pin<Box<dyn Future<Output = Result<NodeOutcome, FaucetError>> + Send>>;
        let mut by_id: HashMap<String, NodeFut> = HashMap::new();
        let source_kinds: HashMap<String, &'static str> = sources
            .iter()
            .map(|(id, s)| (id.clone(), s.connector_name()))
            .collect();

        for (id, source) in sources {
            let node_outs = outs.remove(&id).unwrap_or_default();
            let keep = node_outs.clone();
            let fut: NodeFut = Box::pin(run_source_node(
                Labels::new(opts.pipeline_name.clone(), id.clone(), opts.run_id.clone()),
                source,
                plan.start.clone(),
                opts.batch_size,
                node_outs,
                coop.clone(),
            ));
            by_id.insert(
                id.clone(),
                track_failure(id, fut, keep, Arc::clone(&failed)),
            );
        }

        for node in rest {
            let node_outs = outs.remove(&node.id).unwrap_or_default();
            let keep = node_outs.clone();
            let mut node_ins = ins.remove(&node.id).unwrap_or_default();
            let pipeline = opts.pipeline_name.clone();
            let cancel = coop.clone();
            let Node { id, kind } = node;

            let built: Result<NodeFut, FaucetError> = match kind {
                NodeKind::Source(_) => Err(cfg(format!("source '{id}' was not prepared"))),
                NodeKind::Transform(stages) => take_single(node_ins)
                    .ok_or_else(|| cfg(format!("transform '{id}' has no input edge")))
                    .map(|rx| {
                        let labels = Labels::new(pipeline.clone(), id.clone(), opts.run_id.clone());
                        Box::pin(run_transform_node(stages, labels, rx, node_outs, cancel))
                            as NodeFut
                    }),
                NodeKind::Tee { .. } => take_single(node_ins)
                    .ok_or_else(|| cfg(format!("tee '{id}' has no input edge")))
                    .map(|rx| {
                        Box::pin(run_tee_node(id.clone(), pipeline, rx, node_outs, cancel))
                            as NodeFut
                    }),
                NodeKind::Merge => {
                    let rxs: Vec<mpsc::Receiver<StreamPage>> =
                        node_ins.into_iter().map(|ie| ie.rx).collect();
                    let mode = facts
                        .merge_modes
                        .get(&id)
                        .copied()
                        .unwrap_or(MergeMode::Passthrough);
                    Ok(Box::pin(run_merge_node(
                        id.clone(),
                        pipeline,
                        rxs,
                        node_outs,
                        cancel,
                        mode,
                    )) as NodeFut)
                }
                NodeKind::Join(j) => {
                    // Every node feeding the build side: a failure among them
                    // leaves the hash table incomplete.
                    let build_upstream: HashSet<String> = node_ins
                        .iter()
                        .find(|ie| ie.label.as_deref() == Some(j.build_edge.as_str()))
                        .map(|ie| {
                            let mut set =
                                facts.ancestors.get(&ie.from).cloned().unwrap_or_default();
                            set.insert(ie.from.clone());
                            set
                        })
                        .unwrap_or_default();
                    let build_rx = take_by_label(&mut node_ins, &j.build_edge);
                    let probe_rx = take_by_label(&mut node_ins, &j.probe_edge);
                    match (build_rx, probe_rx) {
                        (Some(b), Some(p)) => Ok(Box::pin(run_join_node(
                            id.clone(),
                            pipeline,
                            j,
                            JoinInputs {
                                build_rx: b,
                                probe_rx: p,
                                build_upstream,
                                failed: Arc::clone(&failed),
                            },
                            node_outs,
                            cancel,
                        )) as NodeFut),
                        _ => Err(cfg(format!(
                            "join '{id}' is missing its build/probe input edges"
                        ))),
                    }
                }
                NodeKind::Sink(sink) => match take_single(node_ins) {
                    None => Err(cfg(format!("sink '{id}' has no input edge"))),
                    Some(rx) => {
                        let resume = plan.sinks.get(&id).cloned();
                        let sopts = SinkNodeOpts {
                            pipeline_name: pipeline,
                            run_id: opts.run_id.clone(),
                            state_store: opts.state_store.clone(),
                            dlq: governance
                                .dlq_by_sink
                                .get(&id)
                                .cloned()
                                .or_else(|| opts.dlq.clone()),
                            cancel: cancel.clone(),
                            // Masking is destination-scoped, so each sink node
                            // takes the policy compiled for it (if any); the rest
                            // are pipeline-wide.
                            #[cfg(feature = "masking")]
                            masking: governance.masking_by_sink.get(&id).cloned(),
                            #[cfg(feature = "quality")]
                            quality: governance.quality.clone(),
                            #[cfg(feature = "contract")]
                            contract: governance.contract.clone(),
                            schema_drift: governance.schema_drift,
                            resilience: governance.resilience.clone(),
                            delivery: governance.delivery,
                            replay: source_replay,
                            codec: codec.clone(),
                            resume,
                            position_source: only_source.clone(),
                            source_label: source_label(facts.ancestors.get(&id), &source_kinds),
                            upstream: facts.ancestors.get(&id).cloned().unwrap_or_default(),
                            failed: Arc::clone(&failed),
                        };
                        Ok(Box::pin(run_sink_node(id.clone(), sink, rx, sopts)) as NodeFut)
                    }
                },
            };
            match built {
                Ok(fut) => {
                    by_id.insert(
                        id.clone(),
                        track_failure(id, fut, keep, Arc::clone(&failed)),
                    );
                }
                Err(e) => return (TopologyRun::default(), Some(e)),
            }
        }

        // Drop the leftover maps so no dangling senders keep channels open.
        drop(outs);
        drop(ins);

        // One task per node, so nodes run on the runtime's whole thread pool
        // instead of sharing a single task. A synchronous stage (the DuckDB `sql`
        // transform, a wasm transform) would otherwise occupy the one task and
        // stall every other node including the sinks (#456 M5). A spawned node
        // also isolates panics: they arrive as a `JoinError` we report, rather
        // than unwinding the caller.
        let futs: Vec<NodeFut> = order
            .iter()
            .filter_map(|(id, _)| by_id.remove(id))
            .collect();
        let handles: Vec<tokio::task::JoinHandle<Result<NodeOutcome, FaucetError>>> = futs
            .into_iter()
            .map(|f| {
                tokio::spawn(tracing::Instrument::in_current_span(
                    crate::http::inherit_reference_policy(f),
                ))
            })
            .collect();
        // Dropping a `JoinHandle` detaches the task rather than cancelling it, so
        // every abandon path below aborts explicitly.
        let aborts: Vec<tokio::task::AbortHandle> =
            handles.iter().map(|h| h.abort_handle()).collect();
        // A dropped run future (serve cancel / timeout past its flush grace)
        // must not leave node tasks writing and persisting bookmarks for a
        // run already reported as cancelled.
        let _abort_on_drop = AbortOnDrop(aborts.clone());
        let abort_all = || {
            for a in &aborts {
                a.abort();
            }
        };
        let joined = handles.into_iter().map(|h| async move {
            match h.await {
                Ok(r) => r,
                Err(e) if e.is_panic() => {
                    Err(FaucetError::Source(format!("topology node panicked: {e}")))
                }
                Err(e) => Err(FaucetError::Source(format!("topology node aborted: {e}"))),
            }
        });

        let externally_cancelled = || cancelled(&opts.cancel);
        match opts.on_error {
            TopologyOnError::Propagate => {
                // Do NOT `try_join_all`: it returns on the first error and drops
                // the remaining node futures where they stand, so a buffered sink
                // never flushes — orphaning a multipart upload or writing a
                // footer-less Parquet file. Instead signal the shared cancel
                // token and let the siblings stop at their next page boundary and
                // flush, exactly as the CLI executor's `on_error: stop` does
                // (#146 H16, #456 M1). A node that does not stop within the grace
                // window is still dropped, so a sink wedged mid-write cannot hang
                // the run.
                let first_err: Arc<std::sync::Mutex<Option<FaucetError>>> =
                    Arc::new(std::sync::Mutex::new(None));
                let failures: Arc<std::sync::Mutex<Vec<(String, String, NodeErrorKind)>>> =
                    Arc::new(std::sync::Mutex::new(Vec::new()));
                let wrapped = joined.zip(order.clone()).map(|(f, (node_id, _))| {
                    let coop = coop.clone();
                    let slot = Arc::clone(&first_err);
                    let failed = Arc::clone(&failures);
                    async move {
                        match f.await {
                            Ok(o) => Some(o),
                            Err(e) => {
                                failed.lock().unwrap_or_else(|p| p.into_inner()).push((
                                    node_id,
                                    e.to_string(),
                                    NodeErrorKind::classify(&e),
                                ));
                                tracing::error!(
                                    error = %e,
                                    "topology node failed; cancelling siblings so they flush"
                                );
                                let mut guard = slot.lock().unwrap_or_else(|p| p.into_inner());
                                if guard.is_none() {
                                    *guard = Some(e);
                                }
                                coop.cancel();
                                None
                            }
                        }
                    }
                });
                // The grace window opens only once something has cancelled the
                // token — a healthy run is never bounded by it.
                let all = futures::future::join_all(wrapped);
                let grace = STOP_FLUSH_GRACE;
                let deadline = {
                    let coop = coop.clone();
                    async move {
                        coop.cancelled().await;
                        tokio::time::sleep(grace).await;
                    }
                };
                let outcomes = tokio::select! {
                    biased;
                    v = all => v,
                    () = deadline => {
                        tracing::warn!(
                            grace_secs = grace.as_secs(),
                            "topology: nodes did not stop within the flush grace after a failure; \
                             aborting them"
                        );
                        abort_all();
                        Vec::new()
                    }
                };
                let outcomes: Vec<NodeOutcome> = outcomes.into_iter().flatten().collect();
                let err = first_err.lock().unwrap_or_else(|p| p.into_inner()).take();
                let complete = err.is_none() && !externally_cancelled();
                let finish = finish_sinks(&outcomes, complete).await;
                let (result, per_source) = aggregate(outcomes);
                let failed = failures.lock().unwrap_or_else(|p| p.into_inner()).clone();
                let nodes = reports(&order, &result, &per_source, &failed, &facts.ancestors);
                let run = TopologyRun {
                    result,
                    nodes,
                    per_source,
                };
                (run, err.or(finish.err()))
            }
            TopologyOnError::Continue => {
                let results = futures::future::join_all(joined).await;
                let mut ok = Vec::new();
                let mut errs = Vec::new();
                let mut failed: Vec<(String, String, NodeErrorKind)> = Vec::new();
                for (r, (node_id, _)) in results.into_iter().zip(order.clone()) {
                    match r {
                        Ok(o) => ok.push(o),
                        Err(e) => {
                            tracing::error!(
                                node = %node_id,
                                error = %e,
                                "topology node failed (on_error: continue)"
                            );
                            errs.push(e.to_string());
                            failed.push((node_id, e.to_string(), NodeErrorKind::classify(&e)));
                        }
                    }
                }
                let complete = errs.is_empty() && !externally_cancelled();
                let finish = finish_sinks(&ok, complete).await;
                let (mut result, per_source) = aggregate(ok);
                result.errors = errs;
                let nodes = reports(&order, &result, &per_source, &failed, &facts.ancestors);
                let run = TopologyRun {
                    result,
                    nodes,
                    per_source,
                };
                (run, finish.err())
            }
        }
    }
}

/// Node ids that failed, with their error text and class — the shared record a
/// sink node consults when its input closes, so it can tell a finished stream
/// from one cut short by an upstream failure.
type FailedNodes = Arc<std::sync::Mutex<HashMap<String, (String, NodeErrorKind)>>>;

/// Run a node future and record a failure **before** its output channels close.
///
/// `keep` holds clones of the node's senders: the node's own copies drop when
/// its future returns, but a downstream receiver only sees end-of-stream once
/// these clones drop too — after the failure is recorded. Without that ordering a
/// sink could observe a closed input, find no failure yet, and report a partial
/// input as a complete, successful run (#789 CLI-18).
fn track_failure(
    id: String,
    fut: Pin<Box<dyn Future<Output = Result<NodeOutcome, FaucetError>> + Send>>,
    keep: Vec<mpsc::Sender<StreamPage>>,
    failed: FailedNodes,
) -> Pin<Box<dyn Future<Output = Result<NodeOutcome, FaucetError>> + Send>> {
    Box::pin(async move {
        use futures::FutureExt;
        let result = match std::panic::AssertUnwindSafe(fut).catch_unwind().await {
            Ok(r) => r,
            Err(payload) => {
                let msg = payload
                    .downcast_ref::<&str>()
                    .map(|s| (*s).to_string())
                    .or_else(|| payload.downcast_ref::<String>().cloned())
                    .unwrap_or_else(|| "non-string panic payload".into());
                Err(FaucetError::Source(format!(
                    "topology node '{id}' panicked: {msg}"
                )))
            }
        };
        if let Err(e) = &result {
            failed
                .lock()
                .unwrap_or_else(|p| p.into_inner())
                .insert(id, (e.to_string(), NodeErrorKind::classify(e)));
        }
        drop(keep);
        result
    })
}

/// How a merge node treats the bookmarks riding on its input pages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MergeMode {
    /// The inputs carry positions of different sources: forward them as they
    /// arrive. (A multi-source graph never resumes from them anyway.)
    Passthrough,
    /// Every input carries the same single source's positions — a tee fanned the
    /// source out and this merge joins the copies back. A position is released
    /// only once **every** input has delivered it, so no sink can persist a
    /// bookmark while another branch's copy of that page is still in flight
    /// (#789 CORE-12).
    Gated,
    /// Some inputs share a source and some do not, so their positions cannot be
    /// lined up: forward pages without bookmarks. The sink then never persists a
    /// position it cannot prove every branch delivered, and the next run replays
    /// in full — duplicates on a non-idempotent sink, never a skipped record.
    Strip,
}

/// Facts derived from the graph shape alone.
struct GraphFacts {
    /// Every node upstream of each node (transitively), excluding the node.
    ancestors: HashMap<String, HashSet<String>>,
    /// How each merge node treats its inputs' bookmarks.
    merge_modes: HashMap<String, MergeMode>,
}

impl GraphFacts {
    fn of(nodes: &[Node], edges: &[Edge]) -> Self {
        let mut rev: HashMap<&str, Vec<&Edge>> = HashMap::new();
        for e in edges {
            rev.entry(e.to.as_str()).or_default().push(e);
        }
        let ancestors: HashMap<String, HashSet<String>> = nodes
            .iter()
            .map(|n| (n.id.clone(), ancestors_of(&n.id, &rev)))
            .collect();

        // The sources whose positions arrive on a node's output pages: a source
        // emits its own, a transform/tee/sink passes its input's on, a merge
        // carries the union of its inputs', and a join only its probe side's.
        let kinds: HashMap<&str, &NodeKind> =
            nodes.iter().map(|n| (n.id.as_str(), &n.kind)).collect();
        let mut origins: HashMap<String, HashSet<String>> = HashMap::new();
        for n in nodes {
            bookmark_origins(&n.id, &kinds, &rev, &mut origins);
        }

        let mut merge_modes = HashMap::new();
        for n in nodes {
            if !matches!(n.kind, NodeKind::Merge) {
                continue;
            }
            let inputs: Vec<HashSet<String>> = rev
                .get(n.id.as_str())
                .map(|es| {
                    es.iter()
                        .map(|e| origins.get(&e.from).cloned().unwrap_or_default())
                        .collect()
                })
                .unwrap_or_default();
            merge_modes.insert(n.id.clone(), merge_mode(&inputs));
        }
        Self {
            ancestors,
            merge_modes,
        }
    }
}

/// Every node upstream of `id`, excluding `id`.
fn ancestors_of(id: &str, rev: &HashMap<&str, Vec<&Edge>>) -> HashSet<String> {
    let mut seen: HashSet<String> = HashSet::new();
    let mut stack: Vec<&str> = rev
        .get(id)
        .map(|es| es.iter().map(|e| e.from.as_str()).collect())
        .unwrap_or_default();
    while let Some(n) = stack.pop() {
        if !seen.insert(n.to_string()) {
            continue;
        }
        if let Some(es) = rev.get(n) {
            stack.extend(es.iter().map(|e| e.from.as_str()));
        }
    }
    seen
}

fn bookmark_origins(
    id: &str,
    kinds: &HashMap<&str, &NodeKind>,
    rev: &HashMap<&str, Vec<&Edge>>,
    memo: &mut HashMap<String, HashSet<String>>,
) -> HashSet<String> {
    if let Some(o) = memo.get(id) {
        return o.clone();
    }
    let inputs: Vec<&Edge> = rev.get(id).cloned().unwrap_or_default();
    let origins: HashSet<String> = match kinds.get(id) {
        Some(NodeKind::Source(_)) => HashSet::from([id.to_string()]),
        Some(NodeKind::Join(j)) => inputs
            .iter()
            .filter(|e| e.label.as_deref() == Some(j.probe_edge.as_str()))
            .flat_map(|e| bookmark_origins(&e.from, kinds, rev, memo))
            .collect(),
        _ => inputs
            .iter()
            .flat_map(|e| bookmark_origins(&e.from, kinds, rev, memo))
            .collect(),
    };
    memo.insert(id.to_string(), origins.clone());
    origins
}

/// Pure merge-mode decision over the bookmark origins of each input.
fn merge_mode(inputs: &[HashSet<String>]) -> MergeMode {
    let disjoint = inputs
        .iter()
        .enumerate()
        .all(|(i, a)| inputs[i + 1..].iter().all(|b| a.is_disjoint(b)));
    if disjoint {
        return MergeMode::Passthrough;
    }
    let first = &inputs[0];
    if first.len() == 1 && inputs.iter().all(|o| o == first) {
        MergeMode::Gated
    } else {
        MergeMode::Strip
    }
}

/// Releases a source position only once every live input of a gated merge has
/// delivered it.
///
/// The inputs of a [`MergeMode::Gated`] merge are copies of one source's pages,
/// so each sees the same positions in the same order. Counting how many
/// bookmarked pages each input has delivered is therefore enough: position `k`
/// is safe once every live input has delivered `k` pages. A closed input has
/// delivered everything it ever will, so it no longer holds the others back.
#[derive(Debug)]
struct BookmarkGate {
    delivered: Vec<u64>,
    closed: Vec<bool>,
    released: u64,
    /// Positions seen but not yet released; `pending[0]` is position
    /// `released + 1`.
    pending: std::collections::VecDeque<Value>,
}

impl BookmarkGate {
    fn new(inputs: usize) -> Self {
        Self {
            delivered: vec![0; inputs],
            closed: vec![false; inputs],
            released: 0,
            pending: std::collections::VecDeque::new(),
        }
    }

    /// A page carrying `bookmark` arrived on `input`. Returns the bookmark to
    /// attach to the forwarded page, if this delivery released one.
    fn arrive(&mut self, input: usize, bookmark: Value) -> Option<Value> {
        self.delivered[input] += 1;
        let seen = self.released + self.pending.len() as u64;
        if self.delivered[input] > seen {
            self.pending.push_back(bookmark);
        }
        self.release()
    }

    /// `input` has closed. Returns a position released by its absence, if any.
    fn close(&mut self, input: usize) -> Option<Value> {
        self.closed[input] = true;
        self.release()
    }

    fn release(&mut self) -> Option<Value> {
        let live_min = self
            .delivered
            .iter()
            .zip(&self.closed)
            .filter(|(_, closed)| !**closed)
            .map(|(d, _)| *d)
            .min()
            .unwrap_or_else(|| self.released + self.pending.len() as u64);
        let mut out = None;
        while self.released < live_min {
            match self.pending.pop_front() {
                Some(bm) => {
                    self.released += 1;
                    out = Some(bm);
                }
                None => break,
            }
        }
        out
    }
}

/// Build the per-node report list from the node ids/kinds and their outcomes.
///
/// A sink that a failed node feeds is reported as failed even when it returned
/// normally: its input closing looked like the end of the stream, but the run
/// never delivered its complete input (#789 CLI-18).
fn reports(
    order: &[(String, &'static str)],
    sinks: &TopologyResult,
    per_source: &HashMap<String, usize>,
    errors: &[(String, String, NodeErrorKind)],
    ancestors: &HashMap<String, HashSet<String>>,
) -> Vec<NodeReport> {
    order
        .iter()
        .map(|(id, kind)| {
            let own = errors.iter().find(|(nid, _, _)| nid == id);
            let upstream = (own.is_none() && *kind == "sink")
                .then(|| {
                    errors
                        .iter()
                        .find(|(nid, _, _)| ancestors.get(id).is_some_and(|a| a.contains(nid)))
                })
                .flatten();
            let (error, error_kind) = match (own, upstream) {
                (Some((_, e, k)), _) => (Some(e.clone()), Some(*k)),
                (None, Some((nid, e, k))) => (
                    Some(format!(
                        "upstream node '{nid}' failed, so this sink did not receive its \
                         complete input: {e}"
                    )),
                    Some(*k),
                ),
                (None, None) => (None, None),
            };
            NodeReport {
                node_id: id.clone(),
                kind,
                records: sinks
                    .per_sink
                    .get(id)
                    .or_else(|| per_source.get(id))
                    .copied()
                    .unwrap_or(0),
                bookmark: sinks.bookmarks.get(id).cloned().flatten(),
                error,
                error_kind,
            }
        })
        .collect()
}

/// Finalize the sink nodes once every node has stopped.
///
/// `complete` is true only when **no** node failed and the run was not
/// cancelled — the graph analogue of `Pipeline::run`'s decision. A sink node
/// sees only its own input close, which also happens when an upstream node
/// failed, so the decision is graph-wide:
///
/// - **Complete:** every `write_mode: overwrite` sink swaps its staging in
///   (`commit_overwrite`) and only then persists its bookmark, which `run_stream`
///   held back; then every sink's [`Sink::complete_run`] runs (#753). A commit
///   that fails discards the remaining sinks' staging rather than swapping a
///   subset in.
/// - **Otherwise:** every overwrite sink discards its staging, leaving its
///   destination as it was (#789 CORE-14).
#[allow(deprecated)] // drives the 1.x lifecycle hook until faucet-core 2.0 (RFC 0014)
async fn finish_sinks(outcomes: &[NodeOutcome], complete: bool) -> Result<(), FaucetError> {
    struct Finish<'a> {
        sink: &'a dyn Sink,
        deferred: Option<&'a DeferredState>,
        bookmark: Option<&'a Value>,
    }
    let sinks: Vec<Finish<'_>> = outcomes
        .iter()
        .filter_map(|o| match o {
            NodeOutcome::Sink {
                sink,
                deferred,
                bookmark,
                ..
            } => Some(Finish {
                sink: sink.as_ref(),
                deferred: deferred.as_ref(),
                bookmark: bookmark.as_ref(),
            }),
            _ => None,
        })
        .collect();
    if !complete {
        for f in &sinks {
            if f.sink.is_overwrite() {
                abort_quietly(f.sink).await;
            }
        }
        return Ok(());
    }
    for (i, f) in sinks.iter().enumerate() {
        if !f.sink.is_overwrite() {
            continue;
        }
        if let Err(e) = f.sink.commit_overwrite().await {
            for rest in &sinks[i + 1..] {
                if rest.sink.is_overwrite() {
                    abort_quietly(rest.sink).await;
                }
            }
            return Err(e);
        }
        if let (Some(d), Some(bm)) = (f.deferred, f.bookmark) {
            d.store.put(&d.key, bm).await?;
        }
    }
    for f in &sinks {
        f.sink.complete_run().await?;
    }
    Ok(())
}

#[allow(deprecated)] // drives the 1.x lifecycle hook until faucet-core 2.0 (RFC 0014)
async fn abort_quietly(sink: &dyn Sink) {
    if let Err(e) = sink.abort_overwrite().await {
        tracing::warn!(
            error = %e,
            "failed to discard overwrite staging after an unsuccessful or cancelled \
             topology run; the destination is unchanged"
        );
    }
}

/// Aggregate node outcomes into a [`TopologyResult`] plus the per-source counts
/// (which live on [`TopologyRun`], not the result).
fn aggregate(outcomes: Vec<NodeOutcome>) -> (TopologyResult, HashMap<String, usize>) {
    let mut result = TopologyResult::default();
    let mut per_source = HashMap::new();
    for o in outcomes {
        match o {
            NodeOutcome::Sink {
                node_id,
                records,
                bookmark,
                ..
            } => {
                result.records_written += records;
                result.per_sink.insert(node_id.clone(), records);
                result.bookmarks.insert(node_id, bookmark);
            }
            NodeOutcome::Source { node_id, records } => {
                per_source.insert(node_id, records);
            }
            NodeOutcome::Other => {}
        }
    }
    (result, per_source)
}

fn cfg(msg: impl Into<String>) -> FaucetError {
    FaucetError::Config(format!("topology: {}", msg.into()))
}

fn arity(
    node_id: &str,
    kind: &str,
    in_ok: bool,
    out_ok: bool,
    expected: &str,
) -> Result<(), FaucetError> {
    if in_ok && out_ok {
        Ok(())
    } else {
        Err(cfg(format!(
            "{kind} '{node_id}' has the wrong edge arity (expected {expected})"
        )))
    }
}

fn reaches_any(start: &str, adj: &HashMap<&str, Vec<&str>>, targets: &HashSet<&str>) -> bool {
    let mut stack = vec![start];
    let mut seen = HashSet::new();
    while let Some(n) = stack.pop() {
        if targets.contains(n) {
            return true;
        }
        if !seen.insert(n) {
            continue;
        }
        if let Some(ns) = adj.get(n) {
            stack.extend(ns.iter().copied());
        }
    }
    false
}

/// Where one sink node resumes under exactly-once delivery.
#[derive(Debug, Clone, PartialEq)]
struct SinkResume {
    /// The commit-token sequence the node's next page follows.
    start_seq: u64,
    /// Skip replayed changes at or before this position: the node already
    /// committed them. Set only for a node ahead of the replay start, and only
    /// when the source can order its positions.
    skip_through: Option<Value>,
}

/// The source's resume point plus each sink node's resume state.
#[derive(Debug, Default)]
struct ResumePlan {
    start: Option<Value>,
    sinks: HashMap<String, SinkResume>,
}

/// Aborts every node task when dropped; a no-op for tasks that finished.
struct AbortOnDrop(Vec<tokio::task::AbortHandle>);

impl Drop for AbortOnDrop {
    fn drop(&mut self) {
        for a in &self.0 {
            a.abort();
        }
    }
}

/// Read every sink node's stored bookmark and decide the source's resume point.
///
/// Returns `Some(bookmark)` only when it is provably safe to resume there;
/// `None` means "replay in full", which costs duplicates on a non-idempotent
/// sink but can never skip a record. See [`start_bookmark`] for the rules.
#[cfg(test)]
async fn compute_start_bookmark(
    opts: &TopologyOptions,
    sink_ids: &[String],
    source_count: usize,
    delivery: crate::idempotency::DeliveryMode,
    source: Option<&dyn Source>,
) -> Result<Option<Value>, FaucetError> {
    let sinks: Vec<(String, Option<&dyn Sink>)> =
        sink_ids.iter().map(|id| (id.clone(), None)).collect();
    compute_resume(opts, &sinks, source_count, delivery, source)
        .await
        .map(|p| p.start)
}

/// Decide the source's resume point and, under exactly-once delivery, where each
/// sink node resumes.
///
/// At-least-once follows [`start_bookmark`]. Exactly-once is ordered by each
/// sink's committed position, recovered the way `Pipeline::run` does: the state
/// store's `(bookmark, seq)`, overridden by the bookmark embedded in the sink's
/// own commit token when the token is ahead — the crash window between "sink
/// committed" and "state persisted" (#789 CORE-11). Then:
///
/// - **All sinks at one position:** resume there; nothing is replayed.
/// - **Positions differ, and the source orders them** ([`Source::position_le`]):
///   resume from the earliest; each sink ahead of it skips the replayed pages at
///   or before its own committed position and keeps its own sequence. Page
///   boundaries need not replay identically.
///   A replayed page that straddles a sink's position keeps only the records
///   [`Source::record_covered`] does not report as already delivered (#862 M-027).
/// - **Otherwise** the run is refused: skipping replayed pages by count is sound
///   only when the replay reproduces the original pages, which no source
///   promises (a multi-partition log interleaves differently on every fetch),
///   so it could skip records a sink never wrote (#862 H-07).
///
/// A sink with no committed position forces a full replay, each sink ahead
/// skipping by position; with no positions at all every sink starts from zero.
#[allow(deprecated)] // drives the 1.x lifecycle hook until faucet-core 2.0 (RFC 0014)
async fn compute_resume(
    opts: &TopologyOptions,
    sinks: &[(String, Option<&dyn Sink>)],
    source_count: usize,
    delivery: crate::idempotency::DeliveryMode,
    source: Option<&dyn Source>,
) -> Result<ResumePlan, FaucetError> {
    let Some(store) = opts.state_store.as_ref() else {
        return Ok(ResumePlan::default());
    };
    if sinks.is_empty() {
        return Ok(ResumePlan::default());
    }
    let mut stored: Vec<(String, Option<Value>)> = Vec::with_capacity(sinks.len());
    for (id, _) in sinks {
        let key = crate::state_key::StateKey::invocation(opts.pipeline_name.as_str(), id.as_str())
            .render();
        let value = match store.get(&key).await {
            // Refuse a bookmark the source cannot read; migrate an older one (#736).
            Ok(Some(v)) => Some(match source {
                Some(src) => crate::state_version::resolve_for_source(&key, &v, src)?.data,
                None => crate::state_version::peel_versioned(&v),
            }),
            Ok(None) => None,
            // A transient read error is not "no bookmark": replaying in full
            // on it would be a silent re-sync.
            Err(e) => return Err(e),
        };
        stored.push((id.clone(), value));
    }

    if delivery != crate::idempotency::DeliveryMode::ExactlyOnce {
        if stored.iter().any(|(_, v)| v.is_none()) {
            return Ok(ResumePlan::default());
        }
        let values: Vec<Value> = stored.into_iter().filter_map(|(_, v)| v).collect();
        return Ok(ResumePlan {
            start: start_bookmark(&values, source_count),
            sinks: HashMap::new(),
        });
    }

    let mut positions: Vec<(String, Option<Value>, u64)> = Vec::with_capacity(sinks.len());
    for ((id, sink), (_, value)) in sinks.iter().zip(stored) {
        let (mut bm, mut seq) = value
            .as_ref()
            .map(crate::idempotency::unwrap_state)
            .unwrap_or((None, 0));
        let key = crate::state_key::StateKey::invocation(opts.pipeline_name.as_str(), id.as_str())
            .render();
        if let (Some(sink), Some(src)) = (sink, source)
            && sink.supports_idempotent_writes()
            && src.replay_guarantee() == crate::idempotency::ReplayGuarantee::Deterministic
            && let Some(token) = sink.last_committed_token(&key).await?
            && let Some((token_seq, Some(token_bm))) = crate::idempotency::parse_token_parts(&token)
            && token_seq > seq
        {
            bm = Some(token_bm);
            seq = token_seq;
        }
        positions.push((id.clone(), bm, seq));
    }
    plan_exactly_once(&positions, source_count, source, &opts.pipeline_name)
}

/// Pure exactly-once resume decision over each sink's `(id, position, seq)`.
fn plan_exactly_once(
    positions: &[(String, Option<Value>, u64)],
    source_count: usize,
    source: Option<&dyn Source>,
    pipeline: &str,
) -> Result<ResumePlan, FaucetError> {
    let own = |skip: &dyn Fn(&Option<Value>) -> Option<Value>| -> HashMap<String, SinkResume> {
        positions
            .iter()
            .map(|(id, bm, seq)| {
                (
                    id.clone(),
                    SinkResume {
                        start_seq: *seq,
                        skip_through: skip(bm),
                    },
                )
            })
            .collect()
    };
    if source_count != 1 {
        if source_count > 1 {
            tracing::warn!(
                sources = source_count,
                "topology: multi-source graph cannot attribute a sink bookmark to a source; \
                 replaying every source in full"
            );
        }
        return Ok(ResumePlan {
            start: None,
            sinks: own(&|_| None),
        });
    }

    let known: Vec<Value> = positions
        .iter()
        .filter_map(|(_, bm, _)| bm.clone())
        .collect();
    let all_known = known.len() == positions.len();
    if all_known && known.iter().all(|b| b == &known[0]) {
        return Ok(ResumePlan {
            start: known.first().cloned(),
            sinks: own(&|_| None),
        });
    }

    let ordering = source.filter(|src| {
        known
            .first()
            .is_some_and(|b| src.position_le(b, b).is_some())
    });
    if let Some(src) = ordering {
        let start = if all_known {
            src.position_min(&known)
        } else {
            None
        };
        if start.is_some() || !all_known {
            let skip = |bm: &Option<Value>| bm.clone().filter(|b| Some(b) != start.as_ref());
            return Ok(ResumePlan {
                start: start.clone(),
                sinks: own(&skip),
            });
        }
    }

    if positions
        .iter()
        .all(|(_, bm, seq)| bm.is_none() && *seq == 0)
    {
        return Ok(ResumePlan {
            start: None,
            sinks: own(&|_| None),
        });
    }
    let committed: Vec<String> = positions
        .iter()
        .map(|(id, bm, seq)| match bm {
            Some(bm) => format!("'{id}' at seq {seq} ({bm})"),
            None => format!("'{id}' with no committed position"),
        })
        .collect();
    let keys: Vec<String> = positions
        .iter()
        .map(|(id, _, _)| {
            let key = crate::state_key::StateKey::invocation(pipeline, id.as_str());
            format!("'{key}'")
        })
        .collect();
    Err(FaucetError::State(format!(
        "topology exactly-once: the sink nodes committed different positions ({}), and the \
         source '{}' cannot order its positions (Source::position_le), so no resume point \
         avoids both lost and duplicated records; resuming by page count is unsafe because \
         a replay need not produce the same pages. To recover, either delete every sink \
         node's state ({}) and its commit-token watermark row under the same scope, then \
         rerun to replay from the start (each sink re-writes what it already holds), or \
         reset only the sinks that are ahead to the furthest-behind sink's position and \
         accept duplicates in between; a source that implements Source::position_le resumes \
         automatically. See the topology cookbook, \"Exactly-once delivery\"",
        committed.join(", "),
        source.map_or("unknown", |s| s.connector_name()),
        keys.join(", "),
    )))
}

/// Exactly-once resume point: the bookmark of the lowest-`seq` sink.
///
/// Unlike the at-least-once path this *can* order the sinks, because `seq` is a
/// monotonic counter rather than an opaque position — so a diverged set resumes
/// from the laggard instead of replaying from scratch. The runner starts every
/// sink at that laggard's sequence, so the sinks ahead skip their
/// already-committed pages via their commit tokens.
///
/// The single-source restriction still applies: nothing records which source a
/// sink's bookmark came from.
pub fn eo_start_bookmark(ranked: &[(u64, Option<Value>)], source_count: usize) -> Option<Value> {
    if ranked.is_empty() || source_count != 1 {
        if source_count > 1 && !ranked.is_empty() {
            tracing::warn!(
                sources = source_count,
                "topology: multi-source graph cannot attribute a sink bookmark to a source; \
                 replaying every source in full"
            );
        }
        return None;
    }
    ranked
        .iter()
        .min_by_key(|(seq, _)| *seq)
        .and_then(|(_, bm)| bm.clone())
}

/// Pure resume-point decision: the bookmark every source node is started from,
/// or `None` to replay in full.
///
/// Deliberately conservative — the only safe way to be wrong is to replay:
///
/// 1. **More than one source node → `None`.** A sink's bookmark records the
///    position of whichever source fed its pages, and nothing in the graph
///    records which one that was. Applying one source's position to another
///    resumes it somewhere it has never been. (#456 H1)
/// 2. **Sink bookmarks that are not all equal → `None`.** Bookmarks are compared
///    for *equality*, never ordered: resume positions are routinely structured
///    (CDC LSN maps, Kafka/Kinesis offset maps) and
///    [`json_gt`](crate::replication::json_gt)'s object arm falls back to
///    comparing serialized text, an order unrelated to replication progress. A
///    "minimum" chosen that way can sit *ahead* of the true minimum and silently
///    skip the lagging sink's records. (#456 H1)
/// 3. **All sinks agree → resume there.** No ordering needed, so no guessing.
pub fn start_bookmark(sink_bookmarks: &[Value], source_count: usize) -> Option<Value> {
    if sink_bookmarks.is_empty() || source_count != 1 {
        if source_count > 1 && !sink_bookmarks.is_empty() {
            tracing::warn!(
                sources = source_count,
                "topology: multi-source graph cannot attribute a sink bookmark to a source; \
                 replaying every source in full. Make the sinks idempotent \
                 (`write_mode: upsert`) or split the graph into one pipeline per source."
            );
        }
        return None;
    }
    let first = &sink_bookmarks[0];
    if sink_bookmarks.iter().any(|v| v != first) {
        tracing::warn!(
            "topology: sink bookmarks have diverged and resume positions are not safely \
             ordered; replaying the source in full so no sink is skipped past. Faster sinks \
             will re-see already-written pages — make them idempotent."
        );
        return None;
    }
    Some(first.clone())
}

/// Receive the next page, or `None` once the channel closes or `cancel` fires.
async fn recv_or_cancel(
    rx: &mut mpsc::Receiver<StreamPage>,
    cancel: &CancellationToken,
) -> Option<StreamPage> {
    tokio::select! {
        biased;
        () = cancel.cancelled() => None,
        page = rx.recv() => page,
    }
}

/// Send `page` to every live output, moving into the last and cloning for the
/// rest. Closed (dropped-receiver) outputs are removed. Returns `false` once
/// every output has closed, or when `cancel` fires while a send is waiting on a
/// full channel — a send that waited forever is how a tee feeding both sides of
/// a join wedged the run (#789 CORE-13).
async fn broadcast(
    page: StreamPage,
    outs: &mut Vec<mpsc::Sender<StreamPage>>,
    cancel: &CancellationToken,
) -> bool {
    if outs.is_empty() {
        return false;
    }
    let last = outs.len() - 1;
    let mut page = Some(page);
    let mut closed: Vec<usize> = Vec::new();
    for (i, tx) in outs.iter().enumerate() {
        let item = if i == last { page.take() } else { page.clone() };
        let Some(item) = item else { break };
        tokio::select! {
            biased;
            () = cancel.cancelled() => return false,
            r = tx.send(item) => if r.is_err() { closed.push(i) },
        }
    }
    for &i in closed.iter().rev() {
        outs.remove(i);
    }
    !outs.is_empty()
}

fn cancelled(cancel: &Option<CancellationToken>) -> bool {
    cancel.as_ref().is_some_and(|c| c.is_cancelled())
}

async fn run_source_node(
    labels: Labels,
    source: Arc<dyn Source>,
    start_bookmark: Option<Value>,
    batch_size: usize,
    mut outs: Vec<mpsc::Sender<StreamPage>>,
    cancel: CancellationToken,
) -> Result<NodeOutcome, FaucetError> {
    let node_id = labels.row.to_string();
    // The same instrumentation `Pipeline::run` layers on: per-node source
    // metrics, with the node id as `row`, and a round-trip recorder.
    source.set_roundtrip_recorder(Arc::new(crate::observability::RoundtripRecorder::new(
        crate::observability::RoundtripSide::Source,
        labels.pipeline.to_string(),
        node_id.clone(),
        source.connector_name(),
    )));
    let source = crate::observability::InstrumentedSource::new(source.as_ref(), labels);
    if let Some(bm) = start_bookmark {
        source.apply_start_bookmark(bm).await?;
    }
    let ctx = std::collections::HashMap::new();
    let mut pages = source.stream_pages(&ctx, batch_size);
    let mut records = 0usize;
    loop {
        let item = tokio::select! {
            biased;
            () = cancel.cancelled() => break,
            item = pages.next() => item,
        };
        let Some(item) = item else { break };
        let page = item?;
        records += page.records.len();
        if !broadcast(page, &mut outs, &cancel).await {
            break;
        }
    }
    Ok(NodeOutcome::Source { node_id, records })
}

async fn run_transform_node(
    stages: Vec<CompiledStage>,
    labels: Labels,
    mut rx: mpsc::Receiver<StreamPage>,
    mut outs: Vec<mpsc::Sender<StreamPage>>,
    cancel: CancellationToken,
) -> Result<NodeOutcome, FaucetError> {
    while let Some(page) = recv_or_cancel(&mut rx, &cancel).await {
        let records = instrumented_apply_stages(page.records, &stages, &labels)?;
        let out = StreamPage {
            records,
            bookmark: page.bookmark,
        };
        if !broadcast(out, &mut outs, &cancel).await {
            break;
        }
    }
    Ok(NodeOutcome::Other)
}

fn node_labels(pipeline: &str, node: &str) -> Vec<Label> {
    vec![
        Label::new("pipeline", SharedString::from(pipeline.to_string())),
        Label::new("node", SharedString::from(node.to_string())),
    ]
}

async fn run_tee_node(
    node_id: String,
    pipeline: String,
    mut rx: mpsc::Receiver<StreamPage>,
    mut outs: Vec<mpsc::Sender<StreamPage>>,
    cancel: CancellationToken,
) -> Result<NodeOutcome, FaucetError> {
    let labels = node_labels(&pipeline, &node_id);
    while let Some(page) = recv_or_cancel(&mut rx, &cancel).await {
        counter!("faucet_tee_records_total", labels.clone()).increment(page.records.len() as u64);
        if !broadcast(page, &mut outs, &cancel).await {
            break;
        }
    }
    Ok(NodeOutcome::Other)
}

async fn run_merge_node(
    node_id: String,
    pipeline: String,
    rxs: Vec<mpsc::Receiver<StreamPage>>,
    mut outs: Vec<mpsc::Sender<StreamPage>>,
    cancel: CancellationToken,
    mode: MergeMode,
) -> Result<NodeOutcome, FaucetError> {
    let labels = node_labels(&pipeline, &node_id);
    if mode == MergeMode::Strip {
        tracing::warn!(
            node = %node_id,
            "topology: merge '{node_id}' combines inputs that share a source with inputs that \
             do not, so their positions cannot be lined up; it forwards no bookmarks and the \
             next run replays in full"
        );
    }
    let mut gate = BookmarkGate::new(rxs.len());
    let streams = rxs.into_iter().enumerate().map(|(i, mut rx)| {
        Box::pin(async_stream::stream! {
            while let Some(p) = rx.recv().await {
                yield (i, Some(p));
            }
            yield (i, None);
        }) as Pin<Box<dyn futures::Stream<Item = (usize, Option<StreamPage>)> + Send>>
    });
    let mut sel = futures::stream::select_all(streams);
    loop {
        let next = tokio::select! {
            biased;
            () = cancel.cancelled() => break,
            next = sel.next() => next,
        };
        let Some((input, page)) = next else { break };
        let out = match (mode, page) {
            (MergeMode::Gated, None) => match gate.close(input) {
                Some(bm) => StreamPage {
                    records: Vec::new(),
                    bookmark: Some(bm),
                },
                None => continue,
            },
            (_, None) => continue,
            (MergeMode::Gated, Some(p)) => StreamPage {
                bookmark: p.bookmark.and_then(|bm| gate.arrive(input, bm)),
                records: p.records,
            },
            (MergeMode::Strip, Some(p)) => StreamPage {
                records: p.records,
                bookmark: None,
            },
            (MergeMode::Passthrough, Some(p)) => p,
        };
        counter!("faucet_merge_records_total", labels.clone()).increment(out.records.len() as u64);
        if !broadcast(out, &mut outs, &cancel).await {
            break;
        }
    }
    Ok(NodeOutcome::Other)
}

/// A join node's two inputs, plus what it needs to tell a finished build side
/// from one cut short by a failure.
struct JoinInputs {
    build_rx: mpsc::Receiver<StreamPage>,
    probe_rx: mpsc::Receiver<StreamPage>,
    build_upstream: HashSet<String>,
    failed: FailedNodes,
}

async fn run_join_node(
    node_id: String,
    pipeline: String,
    j: JoinNode,
    inputs: JoinInputs,
    mut outs: Vec<mpsc::Sender<StreamPage>>,
    cancel: CancellationToken,
) -> Result<NodeOutcome, FaucetError> {
    let JoinInputs {
        mut build_rx,
        mut probe_rx,
        build_upstream,
        failed,
    } = inputs;
    let mode = j.config.mode;
    let mut join = HashJoin::new(j.config);

    // Build phase: fully drain the build side before probing.
    let build_start = std::time::Instant::now();
    while let Some(page) = recv_or_cancel(&mut build_rx, &cancel).await {
        join.add_build_page(page.records)?;
    }
    // A closed build channel is also what a failed upstream looks like; never
    // probe against a partial hash table (inner joins would drop rows, left
    // joins emit them unenriched). A failed node is recorded before its
    // senders close, so this check cannot race the close.
    if let Some((node, error)) = failed_upstream(&failed, &build_upstream) {
        return Err(FaucetError::Source(format!(
            "join '{node_id}': build-side node '{node}' failed, so its hash table is \
             incomplete and nothing was probed: {error}"
        )));
    }
    if cancel.is_cancelled() {
        return Ok(NodeOutcome::Other);
    }
    let labels = node_labels(&pipeline, &node_id);
    histogram!("faucet_join_build_duration_seconds", labels.clone())
        .record(build_start.elapsed().as_secs_f64());

    // Probe phase.
    while let Some(page) = recv_or_cancel(&mut probe_rx, &cancel).await {
        let enriched = join.probe_page(page.records)?;
        let out = StreamPage {
            records: enriched,
            bookmark: page.bookmark,
        };
        if !broadcast(out, &mut outs, &cancel).await {
            break;
        }
    }

    emit_join_metrics(&labels, mode, join.stats());
    Ok(NodeOutcome::Other)
}

fn emit_join_metrics(labels: &[Label], mode: JoinMode, stats: &crate::join::JoinStats) {
    counter!("faucet_join_build_records_total", labels.to_vec()).increment(stats.build_records);
    counter!("faucet_join_build_nulls_total", labels.to_vec()).increment(stats.build_nulls);
    counter!("faucet_join_duplicates_total", labels.to_vec()).increment(stats.duplicates);
    counter!("faucet_join_probe_records_total", labels.to_vec()).increment(stats.probe_records);
    counter!("faucet_join_project_misses_total", labels.to_vec()).increment(stats.project_misses);
    let mut match_labels = labels.to_vec();
    match_labels.push(Label::new("kind", SharedString::from(mode.to_string())));
    counter!("faucet_join_matches_total", match_labels.clone()).increment(stats.matches);
    counter!("faucet_join_misses_total", match_labels).increment(stats.misses);
}

/// Where an overwrite sink node's bookmark goes once its staging is swapped in.
struct DeferredState {
    store: Arc<dyn StateStore>,
    key: String,
}

struct SinkNodeOpts {
    pipeline_name: String,
    run_id: String,
    state_store: Option<Arc<dyn StateStore>>,
    dlq: Option<DlqConfig>,
    cancel: CancellationToken,
    /// Masking policy compiled for *this* sink node (destination-scoped).
    #[cfg(feature = "masking")]
    masking: Option<Arc<crate::masking::CompiledMasking>>,
    #[cfg(feature = "quality")]
    quality: Option<Arc<crate::quality::CompiledQuality>>,
    #[cfg(feature = "contract")]
    contract: Option<Arc<crate::contract::CompiledContract>>,
    schema_drift: Option<crate::drift::SchemaDriftPolicy>,
    resilience: Option<crate::resilience::ResiliencePolicy>,
    /// Delivery guarantee for this sink node.
    delivery: crate::idempotency::DeliveryMode,
    /// The replay capability of the graph's source, so `run_stream` can tell an
    /// atomic-watermark run from a keyed-upsert one. `None` when there is not
    /// exactly one source (in which case exactly-once is gated off anyway).
    replay: Option<crate::idempotency::ReplayGuarantee>,
    /// How this node's bookmark is stored (#736).
    codec: crate::state_version::StateCodec,
    /// Where this node resumes under exactly-once delivery.
    resume: Option<SinkResume>,
    /// The graph's only source, which orders positions for `resume.skip_through`.
    position_source: Option<Arc<dyn Source>>,
    /// The `source` label of this node's run metrics: the connector kind of
    /// the source feeding it, or `multiple`.
    source_label: String,
    /// Every node upstream of this sink.
    upstream: HashSet<String>,
    /// Nodes that have failed so far.
    failed: FailedNodes,
}

/// `faucet_pipeline_runs_total` for one sink node's run.
fn count_node_run(mut labels: Vec<Label>, err: Option<&FaucetError>) {
    labels.push(Label::new(
        "status",
        SharedString::const_str(if err.is_some() { "err" } else { "ok" }),
    ));
    if let Some(e) = err {
        labels.push(Label::new(
            "kind",
            SharedString::const_str(crate::observability::decorator::error_kind(e)),
        ));
    }
    counter!("faucet_pipeline_runs_total", labels).increment(1);
}

/// The connector kind of the one source among `upstream`, or `multiple`.
fn source_label(
    upstream: Option<&HashSet<String>>,
    kinds: &HashMap<String, &'static str>,
) -> String {
    let mut found: Vec<&str> = upstream
        .into_iter()
        .flatten()
        .filter_map(|id| kinds.get(id).copied())
        .collect();
    found.sort_unstable();
    found.dedup();
    match found.as_slice() {
        [one] => (*one).to_string(),
        [] => "unknown".to_string(),
        _ => "multiple".to_string(),
    }
}

/// The first failed node among `upstream`, if any.
fn failed_upstream(failed: &FailedNodes, upstream: &HashSet<String>) -> Option<(String, String)> {
    let failed = failed.lock().unwrap_or_else(|p| p.into_inner());
    let mut hits: Vec<(&String, &(String, NodeErrorKind))> = failed
        .iter()
        .filter(|(id, _)| upstream.contains(*id))
        .collect();
    hits.sort_by(|a, b| a.0.cmp(b.0));
    hits.first()
        .map(|(id, (msg, _))| ((*id).clone(), msg.clone()))
}

/// Where a replayed page sits relative to a sink's committed position.
#[derive(Debug, PartialEq)]
enum PageCoverage {
    /// Every change in the page was committed: skip it.
    Committed,
    /// The page may hold committed changes, and later pages may too.
    Straddles,
    /// The page reaches past the position: no later page holds a committed change.
    Past,
}

fn covered_page(src: &dyn Source, page: &StreamPage, through: &Value) -> PageCoverage {
    let Some(bm) = page.bookmark.as_ref() else {
        return PageCoverage::Straddles;
    };
    if src.position_le(bm, through) == Some(true) {
        PageCoverage::Committed
    } else if src.position_le(through, bm) == Some(true) {
        PageCoverage::Past
    } else {
        PageCoverage::Straddles
    }
}

/// Drop the records of a replayed page that `src` reports as already
/// delivered at `through`. A record it cannot classify — a transform removed
/// the source's position fields — is kept for a sink that deduplicates by key,
/// and refused otherwise: writing it could duplicate a committed record.
fn trim_covered(
    records: &mut Vec<Value>,
    src: &dyn Source,
    through: &Value,
    keyed: bool,
    sink_id: &str,
) -> Result<(), FaucetError> {
    let mut unknown = false;
    records.retain(|r| match src.record_covered(r, through) {
        Some(covered) => !covered,
        None => {
            unknown = true;
            true
        }
    });
    if unknown && !keyed {
        return Err(FaucetError::State(format!(
            "topology exactly-once: a replayed page straddles the position sink '{sink_id}' \
             already committed, and source '{}' cannot tell from a record reaching it whether \
             it was delivered — a transform removed the source's position fields (`topic` / \
             `partition` / `offset` for kafka, `lsn` for postgres-cdc / mysql-cdc / mssql-cdc). \
             Keep those fields until the sink, or write with `write_mode: upsert` + `key`",
            src.connector_name()
        )));
    }
    Ok(())
}

#[allow(deprecated)] // drives the 1.x lifecycle hook until faucet-core 2.0 (RFC 0014)
async fn run_sink_node(
    node_id: String,
    sink: Box<dyn Sink>,
    mut rx: mpsc::Receiver<StreamPage>,
    opts: SinkNodeOpts,
) -> Result<NodeOutcome, FaucetError> {
    let failed = Arc::clone(&opts.failed);
    let upstream = opts.upstream.clone();
    let position_source = opts.position_source.clone();
    let mut skip_through = opts.resume.as_ref().and_then(|r| r.skip_through.clone());
    let keyed = sink.dedups_by_key();
    let sink_id = node_id.clone();
    let pages = Box::pin(async_stream::stream! {
        loop {
            match rx.recv().await {
                Some(mut page) => {
                    // Exactly-once: this node already committed every change at or
                    // before `skip_through`, so a replay from an earlier sink's
                    // position must not write them again (#789 CORE-01). Replayed
                    // pages need not break where the original ones did, so a page
                    // that straddles the position keeps only the records the
                    // source says were not yet delivered there (#862 M-027).
                    if let (Some(through), Some(src)) = (skip_through.as_ref(), position_source.as_ref()) {
                        let coverage = covered_page(src.as_ref(), &page, through);
                        if coverage == PageCoverage::Committed {
                            continue;
                        }
                        if let Err(e) = trim_covered(&mut page.records, src.as_ref(), through, keyed, &sink_id) {
                            yield Err(e);
                            break;
                        }
                        if coverage == PageCoverage::Past {
                            skip_through = None;
                        }
                    }
                    yield Ok::<StreamPage, FaucetError>(page);
                }
                None => {
                    if let Some((node, error)) = failed_upstream(&failed, &upstream) {
                        yield Err(FaucetError::Source(format!(
                            "upstream node '{node}' failed, so sink '{sink_id}' did not \
                             receive its complete input: {error}"
                        )));
                    }
                    break;
                }
            }
        }
    });

    let mut run_opts = RunStreamOptions::new()
        .with_name(opts.pipeline_name.clone())
        .with_row(node_id.clone())
        .with_run_id(opts.run_id.clone());
    let overwriting = sink.is_overwrite();
    let mut deferred = None;
    if let Some(store) = opts.state_store {
        let key =
            crate::state_key::StateKey::invocation(opts.pipeline_name.as_str(), node_id.as_str())
                .render();
        let store: Arc<dyn StateStore> = Arc::new(crate::state_version::VersionedStateStore::new(
            store,
            key.clone(),
            opts.codec,
        ));
        // Exactly-once: this node's commit-token sequence resumes where the
        // graph-wide resume plan placed it (#458, #789 CORE-01).
        if opts.delivery == crate::idempotency::DeliveryMode::ExactlyOnce {
            let seq = match opts.resume.as_ref() {
                Some(r) => r.start_seq,
                None => match store.get(&key).await? {
                    Some(prior) => crate::idempotency::unwrap_state(&prior).1,
                    None => 0,
                },
            };
            run_opts = run_opts.with_delivery(opts.delivery).with_start_seq(seq);
            if let Some(replay) = opts.replay {
                run_opts = run_opts.with_replay_guarantee(replay);
            }
        }
        if overwriting {
            deferred = Some(DeferredState {
                store: Arc::clone(&store),
                key: key.clone(),
            });
        }
        run_opts = run_opts.with_state(store, key);
    }
    if let Some(dlq) = opts.dlq {
        run_opts = run_opts.with_dlq(dlq);
    }
    run_opts = run_opts.with_cancel(opts.cancel);
    // Governance passes, in the same order `Pipeline` applies them: masking
    // first (so nothing downstream — sink, DLQ, lineage sample — ever sees
    // unmasked PII), then quality, contract, and drift.
    #[cfg(feature = "masking")]
    if let Some(m) = opts.masking {
        run_opts = run_opts.with_masking(m);
    }
    #[cfg(feature = "quality")]
    if let Some(q) = opts.quality {
        run_opts = run_opts.with_quality(q);
    }
    #[cfg(feature = "contract")]
    if let Some(c) = opts.contract {
        run_opts = run_opts.with_contract(c);
    }
    if let Some(d) = opts.schema_drift {
        run_opts.schema_drift = Some(d);
    }
    if let Some(r) = opts.resilience {
        run_opts.resilience = Some(r);
    }

    // `write_mode: overwrite` stages before the first write; the swap happens
    // only once the whole graph has succeeded (`finish_sinks`), and a failure
    // here discards the staging so the destination is left as it was
    // (#789 CORE-14).
    if overwriting {
        sink.begin_overwrite().await?;
    }
    // The same instrumentation `Pipeline::run` layers on: per-node sink
    // metrics with the node id as `row`, a round-trip recorder, and the run
    // counter.
    let labels = Labels::new(
        opts.pipeline_name.clone(),
        node_id.clone(),
        opts.run_id.clone(),
    );
    sink.set_roundtrip_recorder(Arc::new(crate::observability::RoundtripRecorder::new(
        crate::observability::RoundtripSide::Sink,
        opts.pipeline_name.clone(),
        node_id.clone(),
        sink.connector_name(),
    )));
    let run_labels = vec![
        Label::new("pipeline", SharedString::from(opts.pipeline_name.clone())),
        Label::new("row", SharedString::from(node_id.clone())),
        Label::new("source", SharedString::from(opts.source_label.clone())),
        Label::new("sink", SharedString::const_str(sink.connector_name())),
    ];
    let timer = crate::observability::DurationGuard::new(
        "faucet_pipeline_run_duration_seconds",
        run_labels.clone(),
    );
    let instrumented = crate::observability::InstrumentedSink::new(sink.as_ref(), labels);
    let outcome = run_stream(pages, &instrumented, run_opts).await;
    drop(instrumented);
    drop(timer);
    count_node_run(run_labels, outcome.as_ref().err());
    let result = match outcome {
        Ok(r) => r,
        Err(e) => {
            if overwriting {
                abort_quietly(sink.as_ref()).await;
            }
            return Err(e);
        }
    };
    Ok(NodeOutcome::Sink {
        node_id,
        records: result.records_written,
        bookmark: result.bookmark,
        sink,
        deferred,
    })
}

// ── Builder ──────────────────────────────────────────────────────────────────

/// Fluent builder for a [`Topology`].
#[derive(Default)]
pub struct TopologyBuilder {
    nodes: Vec<Node>,
    edges: Vec<Edge>,
}

impl TopologyBuilder {
    /// Add a node of any kind.
    pub fn node(mut self, id: impl Into<String>, kind: NodeKind) -> Self {
        self.nodes.push(Node {
            id: id.into(),
            kind,
        });
        self
    }

    /// Add a source node.
    pub fn source(self, id: impl Into<String>, source: Box<dyn Source>) -> Self {
        self.node(id, NodeKind::Source(source))
    }

    /// Add a transform node.
    pub fn transform(self, id: impl Into<String>, stages: Vec<CompiledStage>) -> Self {
        self.node(id, NodeKind::Transform(stages))
    }

    /// Add a tee (fan-out) node.
    pub fn tee(self, id: impl Into<String>, capacity: usize, fanout: Option<usize>) -> Self {
        self.node(id, NodeKind::Tee { capacity, fanout })
    }

    /// Add a merge (fan-in) node.
    pub fn merge(self, id: impl Into<String>) -> Self {
        self.node(id, NodeKind::Merge)
    }

    /// Add a join node.
    pub fn join(self, id: impl Into<String>, join: JoinNode) -> Self {
        self.node(id, NodeKind::Join(join))
    }

    /// Add a sink node.
    pub fn sink(self, id: impl Into<String>, sink: Box<dyn Sink>) -> Self {
        self.node(id, NodeKind::Sink(sink))
    }

    /// Add an unlabelled edge.
    pub fn edge(mut self, from: impl Into<String>, to: impl Into<String>) -> Self {
        self.edges.push(Edge {
            from: from.into(),
            to: to.into(),
            label: None,
        });
        self
    }

    /// Add a labelled edge (used by join build/probe wiring).
    pub fn labelled_edge(
        mut self,
        from: impl Into<String>,
        to: impl Into<String>,
        label: impl Into<String>,
    ) -> Self {
        self.edges.push(Edge {
            from: from.into(),
            to: to.into(),
            label: Some(label.into()),
        });
        self
    }

    /// Finalize and validate the topology.
    pub fn build(self) -> Result<Topology, FaucetError> {
        let t = Topology {
            nodes: self.nodes,
            edges: self.edges,
        };
        t.validate()?;
        Ok(t)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::join::{JoinConfig, JoinMode, Projection};
    use crate::state::MemoryStateStore;
    use async_trait::async_trait;
    use serde_json::json;
    use std::sync::Mutex;

    // ── Mock connectors ───────────────────────────────────────────────────────

    pub(super) struct VecSource {
        records: Vec<Value>,
        bookmark: Option<Value>,
    }
    impl VecSource {
        pub(super) fn boxed(records: Vec<Value>) -> Box<dyn Source> {
            Box::new(VecSource {
                records,
                bookmark: None,
            })
        }
        fn boxed_bm(records: Vec<Value>, bm: Value) -> Box<dyn Source> {
            Box::new(VecSource {
                records,
                bookmark: Some(bm),
            })
        }
    }
    #[async_trait]
    impl Source for VecSource {
        async fn fetch_with_context(
            &self,
            _c: &std::collections::HashMap<String, Value>,
        ) -> Result<Vec<Value>, FaucetError> {
            Ok(self.records.clone())
        }
        async fn fetch_with_context_incremental(
            &self,
            _c: &std::collections::HashMap<String, Value>,
        ) -> Result<(Vec<Value>, Option<Value>), FaucetError> {
            Ok((self.records.clone(), self.bookmark.clone()))
        }
    }

    struct FailingSource;
    #[async_trait]
    impl Source for FailingSource {
        async fn fetch_with_context(
            &self,
            _c: &std::collections::HashMap<String, Value>,
        ) -> Result<Vec<Value>, FaucetError> {
            Err(FaucetError::Source("boom".into()))
        }
    }

    /// Records the bookmark applied via `apply_start_bookmark`.
    struct RecordingSource {
        records: Vec<Value>,
        applied: Arc<Mutex<Option<Value>>>,
    }
    #[async_trait]
    impl Source for RecordingSource {
        async fn fetch_with_context(
            &self,
            _c: &std::collections::HashMap<String, Value>,
        ) -> Result<Vec<Value>, FaucetError> {
            Ok(self.records.clone())
        }
        async fn apply_start_bookmark(&self, bm: Value) -> Result<(), FaucetError> {
            *self.applied.lock().unwrap() = Some(bm);
            Ok(())
        }
    }

    #[derive(Clone)]
    pub(super) struct CollectSink {
        store: Arc<Mutex<Vec<Value>>>,
    }
    impl CollectSink {
        pub(super) fn new() -> (Self, Arc<Mutex<Vec<Value>>>) {
            let store = Arc::new(Mutex::new(Vec::new()));
            (
                Self {
                    store: store.clone(),
                },
                store,
            )
        }
    }
    #[async_trait]
    impl Sink for CollectSink {
        async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
            self.store.lock().unwrap().extend_from_slice(records);
            Ok(records.len())
        }
    }

    pub(super) struct FailingSink;
    #[async_trait]
    impl Sink for FailingSink {
        async fn write_batch(&self, _records: &[Value]) -> Result<usize, FaucetError> {
            Err(FaucetError::Sink("sink boom".into()))
        }
    }

    /// A sink that fails the way the resilience circuit breaker does, so a test
    /// can check the *class* survives rather than just the message (#658).
    pub(super) struct BreakerSink;
    #[async_trait]
    impl Sink for BreakerSink {
        async fn write_batch(&self, _records: &[Value]) -> Result<usize, FaucetError> {
            Err(FaucetError::CircuitOpen {
                failures: 3,
                cooldown: std::time::Duration::from_secs(30),
            })
        }
    }

    /// A sink that records whether `flush` was called — the observable proof that
    /// a node was allowed to finish cooperatively rather than being dropped.
    struct FlushTrackingSink {
        flushed: Arc<Mutex<bool>>,
    }
    #[async_trait]
    impl Sink for FlushTrackingSink {
        async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
            Ok(records.len())
        }
        async fn flush(&self) -> Result<(), FaucetError> {
            *self.flushed.lock().unwrap() = true;
            Ok(())
        }
    }

    pub(super) fn recs(n: usize) -> Vec<Value> {
        (0..n).map(|i| json!({ "i": i })).collect()
    }

    // ── Validation ────────────────────────────────────────────────────────────

    #[test]
    fn validate_rejects_a_source_that_consumes_destructively() {
        struct Queue;
        #[async_trait]
        impl Source for Queue {
            async fn fetch_with_context(
                &self,
                _: &std::collections::HashMap<String, Value>,
            ) -> Result<Vec<Value>, FaucetError> {
                Ok(Vec::new())
            }
            fn consumes_destructively(&self) -> bool {
                true
            }
            fn connector_name(&self) -> &'static str {
                "queue"
            }
        }
        let rt = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        assert!(rt.block_on(Queue.fetch_all()).unwrap().is_empty());
        let (sink, _) = CollectSink::new();
        let err = Topology::builder()
            .source("q", Box::new(Queue))
            .sink("out", Box::new(sink))
            .edge("q", "out")
            .build()
            .unwrap_err()
            .to_string();
        assert!(err.contains("source 'q' (queue)"), "{err}");
    }

    #[test]
    fn validate_rejects_empty() {
        let err = Topology {
            nodes: vec![],
            edges: vec![],
        }
        .validate()
        .unwrap_err();
        assert!(err.to_string().contains("no nodes"));
    }

    #[test]
    fn validate_rejects_duplicate_id() {
        let (sink, _) = CollectSink::new();
        let err = Topology::builder()
            .source("a", VecSource::boxed(recs(1)))
            .sink("a", Box::new(sink))
            .edge("a", "a")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("duplicate node id"));
    }

    #[test]
    fn validate_rejects_unknown_endpoint() {
        let err = Topology::builder()
            .source("s", VecSource::boxed(recs(1)))
            .edge("s", "ghost")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("unknown 'to' node 'ghost'"));
    }

    #[test]
    fn validate_rejects_unknown_from_endpoint() {
        let (sink, _) = CollectSink::new();
        let err = Topology::builder()
            .sink("k", Box::new(sink))
            .edge("ghost", "k")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("unknown 'from' node 'ghost'"));
    }

    #[test]
    fn validate_rejects_source_with_incoming_edge() {
        let (sink, _) = CollectSink::new();
        let err = Topology::builder()
            .source("s", VecSource::boxed(recs(1)))
            .sink("k", Box::new(sink))
            .edge("s", "k")
            .edge("k", "s") // sink→source: gives source in=1 and sink out=1
            .build()
            .unwrap_err();
        // Either arity or cycle is caught; both are correct rejections.
        assert!(err.to_string().contains("arity") || err.to_string().contains("cycle"));
    }

    #[test]
    fn validate_rejects_tee_fanout_mismatch() {
        let (s1, _) = CollectSink::new();
        let (s2, _) = CollectSink::new();
        let err = Topology::builder()
            .source("s", VecSource::boxed(recs(1)))
            .tee("t", 4, Some(3))
            .sink("a", Box::new(s1))
            .sink("b", Box::new(s2))
            .edge("s", "t")
            .edge("t", "a")
            .edge("t", "b")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("fanout 3 but has 2"));
    }

    #[test]
    fn validate_rejects_tee_with_one_output() {
        let (s1, _) = CollectSink::new();
        let err = Topology::builder()
            .source("s", VecSource::boxed(recs(1)))
            .tee("t", 4, None)
            .sink("a", Box::new(s1))
            .edge("s", "t")
            .edge("t", "a")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("tee 't'"));
    }

    #[test]
    fn validate_rejects_merge_with_one_input() {
        let (s1, _) = CollectSink::new();
        let err = Topology::builder()
            .source("s", VecSource::boxed(recs(1)))
            .merge("m")
            .sink("a", Box::new(s1))
            .edge("s", "m")
            .edge("m", "a")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("merge 'm'"));
    }

    #[test]
    fn validate_rejects_join_missing_label() {
        let (s1, _) = CollectSink::new();
        let jn = JoinNode {
            config: JoinConfig::default(),
            build_edge: "build".into(),
            probe_edge: "probe".into(),
        };
        let err = Topology::builder()
            .source("b", VecSource::boxed(recs(1)))
            .source("p", VecSource::boxed(recs(1)))
            .join("j", jn)
            .sink("a", Box::new(s1))
            .labelled_edge("b", "j", "build")
            .edge("p", "j") // unlabelled — probe label missing
            .edge("j", "a")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("labelled 'probe'"));
    }

    #[test]
    fn validate_rejects_join_same_labels() {
        let (s1, _) = CollectSink::new();
        let jn = JoinNode {
            config: JoinConfig::default(),
            build_edge: "x".into(),
            probe_edge: "x".into(),
        };
        let err = Topology::builder()
            .source("b", VecSource::boxed(recs(1)))
            .source("p", VecSource::boxed(recs(1)))
            .join("j", jn)
            .sink("a", Box::new(s1))
            .labelled_edge("b", "j", "x")
            .labelled_edge("p", "j", "x")
            .edge("j", "a")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("must differ"));
    }

    #[test]
    fn validate_rejects_cycle() {
        // s → m(merge) → t(tee) → {m, k}. The m→t→m loop is a valid-arity
        // cycle (merge absorbs the back-edge, tee provides the second out).
        let (sink, _) = CollectSink::new();
        let err = Topology::builder()
            .source("s", VecSource::boxed(recs(1)))
            .merge("m")
            .tee("t", 4, None)
            .sink("k", Box::new(sink))
            .edge("s", "m")
            .edge("m", "t")
            .edge("t", "m")
            .edge("t", "k")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("cycle"), "{err}");
    }

    #[test]
    fn validate_rejects_no_source() {
        // Two transforms wired in a ring: valid arity, but no source node.
        let err = Topology::builder()
            .transform("t1", vec![])
            .transform("t2", vec![])
            .edge("t1", "t2")
            .edge("t2", "t1")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("no source"), "{err}");
    }

    #[test]
    fn validate_rejects_no_sink() {
        // Two sources into a self-looping merge: valid arity, but no sink.
        let err = Topology::builder()
            .source("s1", VecSource::boxed(recs(1)))
            .source("s2", VecSource::boxed(recs(1)))
            .merge("m")
            .edge("s1", "m")
            .edge("s2", "m")
            .edge("m", "m")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("no sink"), "{err}");
    }

    // ── Execution ─────────────────────────────────────────────────────────────

    #[tokio::test]
    async fn simple_source_to_sink() {
        let (sink, store) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(5)))
            .sink("k", Box::new(sink))
            .edge("s", "k")
            .build()
            .unwrap();
        let result = topo.run(TopologyOptions::new("p")).await.unwrap();
        assert_eq!(result.records_written, 5);
        assert_eq!(store.lock().unwrap().len(), 5);
        assert_eq!(result.per_sink.get("k"), Some(&5));
    }

    #[tokio::test]
    async fn source_transform_sink() {
        let (sink, store) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(3)))
            .transform("t", vec![]) // passthrough
            .sink("k", Box::new(sink))
            .edge("s", "t")
            .edge("t", "k")
            .build()
            .unwrap();
        let result = topo.run(TopologyOptions::new("p")).await.unwrap();
        assert_eq!(result.records_written, 3);
        assert_eq!(store.lock().unwrap().len(), 3);
    }

    #[tokio::test]
    async fn tee_fans_out_to_three_sinks() {
        let (s1, st1) = CollectSink::new();
        let (s2, st2) = CollectSink::new();
        let (s3, st3) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(10)))
            .tee("t", 4, Some(3))
            .sink("a", Box::new(s1))
            .sink("b", Box::new(s2))
            .sink("c", Box::new(s3))
            .edge("s", "t")
            .edge("t", "a")
            .edge("t", "b")
            .edge("t", "c")
            .build()
            .unwrap();
        let result = topo.run(TopologyOptions::new("p")).await.unwrap();
        assert_eq!(st1.lock().unwrap().len(), 10);
        assert_eq!(st2.lock().unwrap().len(), 10);
        assert_eq!(st3.lock().unwrap().len(), 10);
        assert_eq!(result.records_written, 30);
    }

    #[tokio::test]
    async fn merge_fans_in_two_sources() {
        let (sink, store) = CollectSink::new();
        let topo = Topology::builder()
            .source("s1", VecSource::boxed(recs(4)))
            .source("s2", VecSource::boxed(recs(6)))
            .merge("m")
            .sink("k", Box::new(sink))
            .edge("s1", "m")
            .edge("s2", "m")
            .edge("m", "k")
            .build()
            .unwrap();
        let result = topo.run(TopologyOptions::new("p")).await.unwrap();
        assert_eq!(result.records_written, 10);
        assert_eq!(store.lock().unwrap().len(), 10);
    }

    #[tokio::test]
    async fn join_enriches_end_to_end() {
        let (sink, store) = CollectSink::new();
        let customers = vec![
            json!({"id": 1, "tier": "gold"}),
            json!({"id": 2, "tier": "silver"}),
        ];
        let orders = vec![
            json!({"order": "A", "cust": 1}),
            json!({"order": "B", "cust": 2}),
            json!({"order": "C", "cust": 99}),
        ];
        let jn = JoinNode {
            config: JoinConfig {
                mode: JoinMode::Inner,
                build_key: "id".into(),
                probe_key: "cust".into(),
                projections: vec![Projection {
                    from: "tier".into(),
                    as_: "tier".into(),
                }],
                ..Default::default()
            },
            build_edge: "customers".into(),
            probe_edge: "orders".into(),
        };
        let topo = Topology::builder()
            .source("c", VecSource::boxed(customers))
            .source("o", VecSource::boxed(orders))
            .join("j", jn)
            .sink("k", Box::new(sink))
            .labelled_edge("c", "j", "customers")
            .labelled_edge("o", "j", "orders")
            .edge("j", "k")
            .build()
            .unwrap();
        let result = topo.run(TopologyOptions::new("p")).await.unwrap();
        // inner join: C (cust 99) drops → 2 enriched records.
        assert_eq!(result.records_written, 2);
        let written = store.lock().unwrap();
        assert!(
            written
                .iter()
                .any(|r| r["order"] == json!("A") && r["tier"] == json!("gold"))
        );
    }

    #[tokio::test]
    #[allow(clippy::await_holding_lock)]
    async fn source_and_sink_nodes_are_instrumented() {
        use metrics_util::debugging::DebugValue;
        let _g = crate::observability::decorator::source_tests::LOCK
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let snap = crate::observability::decorator::source_tests::snapshotter();
        let probe = crate::forwarding::HookSink::default();
        let topo = Topology::builder()
            .source("src-node", VecSource::boxed(recs(3)))
            .sink("sink-node", Box::new(probe.clone()))
            .edge("src-node", "sink-node")
            .build()
            .unwrap();
        topo.run(TopologyOptions::new("topo-metrics"))
            .await
            .unwrap();
        assert!(probe.reached().contains(&"set_roundtrip_recorder"));
        type Counter = (String, Vec<(String, String)>, u64);
        let counters: Vec<Counter> = snap
            .snapshot()
            .into_vec()
            .into_iter()
            .filter_map(|(k, _, _, v)| match v {
                DebugValue::Counter(c) => Some((
                    k.key().name().to_string(),
                    k.key()
                        .labels()
                        .map(|l| (l.key().to_string(), l.value().to_string()))
                        .collect::<Vec<_>>(),
                    c,
                )),
                _ => None,
            })
            .filter(|(_, l, _)| l.contains(&("pipeline".into(), "topo-metrics".into())))
            .collect();
        let has = |name: &str, label: (&str, &str), n: u64| {
            counters.iter().any(|(m, l, c)| {
                m == name && l.contains(&(label.0.into(), label.1.into())) && *c == n
            })
        };
        assert!(
            has("faucet_source_records_total", ("row", "src-node"), 3),
            "{counters:?}"
        );
        assert!(
            has("faucet_sink_records_total", ("row", "sink-node"), 3),
            "{counters:?}"
        );
        assert!(
            has("faucet_pipeline_runs_total", ("source", "VecSource"), 1),
            "{counters:?}"
        );
        assert!(
            has("faucet_pipeline_runs_total", ("status", "ok"), 1),
            "{counters:?}"
        );
    }

    #[test]
    fn a_node_fed_by_several_sources_is_labelled_multiple() {
        let kinds: HashMap<String, &'static str> = [
            ("a".to_string(), "rest"),
            ("b".to_string(), "csv"),
            ("c".to_string(), "rest"),
        ]
        .into();
        let up = |ids: &[&str]| ids.iter().map(|s| s.to_string()).collect::<HashSet<_>>();
        assert_eq!(source_label(Some(&up(&["a", "t"])), &kinds), "rest");
        assert_eq!(source_label(Some(&up(&["a", "c"])), &kinds), "rest");
        assert_eq!(source_label(Some(&up(&["a", "b"])), &kinds), "multiple");
        assert_eq!(source_label(None, &kinds), "unknown");
    }

    #[tokio::test]
    async fn a_state_read_error_fails_the_run_instead_of_replaying() {
        struct Unreadable;
        #[async_trait]
        impl StateStore for Unreadable {
            async fn get(&self, _k: &str) -> Result<Option<Value>, FaucetError> {
                Err(FaucetError::State("store unreachable".into()))
            }
            async fn put(&self, _k: &str, _v: &Value) -> Result<(), FaucetError> {
                Ok(())
            }
            async fn delete(&self, _k: &str) -> Result<(), FaucetError> {
                Ok(())
            }
        }
        let (sink, store) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(2)))
            .sink("k", Box::new(sink))
            .edge("s", "k")
            .build()
            .unwrap();
        let mut opts = TopologyOptions::new("p");
        opts.state_store = Some(Arc::new(Unreadable));
        let err = topo.run(opts).await.unwrap_err();
        assert!(err.to_string().contains("store unreachable"), "{err}");
        assert!(store.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn a_failed_build_side_is_never_probed() {
        /// One page, then a failure.
        struct HalfSource;
        #[async_trait]
        impl Source for HalfSource {
            async fn fetch_with_context(
                &self,
                _c: &std::collections::HashMap<String, Value>,
            ) -> Result<Vec<Value>, FaucetError> {
                Ok(Vec::new())
            }
            fn stream_pages<'a>(
                &'a self,
                _c: &'a std::collections::HashMap<String, Value>,
                _b: usize,
            ) -> Pin<Box<dyn crate::Stream<Item = Result<StreamPage, FaucetError>> + Send + 'a>>
            {
                Box::pin(futures::stream::iter(vec![
                    Ok(StreamPage {
                        records: vec![json!({"id": 1, "tier": "gold"})],
                        bookmark: None,
                    }),
                    Err(FaucetError::Source("build side broke".into())),
                ]))
            }
        }
        for on_error in [TopologyOnError::Continue, TopologyOnError::Propagate] {
            let (sink, store) = CollectSink::new();
            let jn = JoinNode {
                config: JoinConfig {
                    mode: JoinMode::Left,
                    build_key: "id".into(),
                    probe_key: "cust".into(),
                    projections: vec![Projection {
                        from: "tier".into(),
                        as_: "tier".into(),
                    }],
                    ..Default::default()
                },
                build_edge: "customers".into(),
                probe_edge: "orders".into(),
            };
            let topo = Topology::builder()
                .source("c", Box::new(HalfSource))
                .source(
                    "o",
                    VecSource::boxed(vec![
                        json!({"order": "A", "cust": 1}),
                        json!({"order": "B", "cust": 2}),
                    ]),
                )
                .join("j", jn)
                .sink("k", Box::new(sink))
                .labelled_edge("c", "j", "customers")
                .labelled_edge("o", "j", "orders")
                .edge("j", "k")
                .build()
                .unwrap();
            let mut opts = TopologyOptions::new("p");
            opts.on_error = on_error;
            let (run, err) = topo
                .run_attributed(opts, TopologyGovernance::default())
                .await;
            let errors = format!("{err:?} {:?}", run.result.errors);
            assert!(errors.contains("build side broke"), "{errors}");
            assert!(
                store.lock().unwrap().is_empty(),
                "{on_error:?}: nothing probed"
            );
        }
    }

    #[tokio::test]
    async fn propagate_aborts_on_sink_failure() {
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(3)))
            .sink("k", Box::new(FailingSink))
            .edge("s", "k")
            .build()
            .unwrap();
        let err = topo.run(TopologyOptions::new("p")).await.unwrap_err();
        assert!(matches!(err, FaucetError::Sink(_)));
    }

    #[tokio::test]
    async fn propagate_aborts_on_source_failure() {
        let (sink, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", Box::new(FailingSource))
            .sink("k", Box::new(sink))
            .edge("s", "k")
            .build()
            .unwrap();
        let err = topo.run(TopologyOptions::new("p")).await.unwrap_err();
        assert!(matches!(err, FaucetError::Source(_)));
    }

    struct CompletingSink(Arc<Mutex<u32>>);
    #[async_trait]
    impl Sink for CompletingSink {
        async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
            Ok(records.len())
        }
        async fn complete_run(&self) -> Result<(), FaucetError> {
            *self.0.lock().unwrap() += 1;
            Ok(())
        }
    }

    #[tokio::test]
    async fn complete_run_fires_only_for_a_fully_successful_graph() {
        let done = Arc::new(Mutex::new(0));
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(2)))
            .sink("k", Box::new(CompletingSink(done.clone())))
            .edge("s", "k")
            .build()
            .unwrap();
        topo.run(TopologyOptions::new("p")).await.unwrap();
        assert_eq!(*done.lock().unwrap(), 1);

        let failed = Arc::new(Mutex::new(0));
        let topo = Topology::builder()
            .source("s", Box::new(FailingSource))
            .sink("k", Box::new(CompletingSink(failed.clone())))
            .edge("s", "k")
            .build()
            .unwrap();
        assert!(topo.run(TopologyOptions::new("p")).await.is_err());
        assert_eq!(*failed.lock().unwrap(), 0);

        let partial = Arc::new(Mutex::new(0));
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(4)))
            .tee("t", 4, Some(2))
            .sink("bad", Box::new(FailingSink))
            .sink("good", Box::new(CompletingSink(partial.clone())))
            .edge("s", "t")
            .edge("t", "bad")
            .edge("t", "good")
            .build()
            .unwrap();
        let opts = TopologyOptions::new("p").with_on_error(TopologyOnError::Continue);
        topo.run(opts).await.unwrap();
        assert_eq!(*partial.lock().unwrap(), 0);

        let cancelled = Arc::new(Mutex::new(0));
        let token = CancellationToken::new();
        token.cancel();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(2)))
            .sink("k", Box::new(CompletingSink(cancelled.clone())))
            .edge("s", "k")
            .build()
            .unwrap();
        let _ = topo.run(TopologyOptions::new("p").with_cancel(token)).await;
        assert_eq!(*cancelled.lock().unwrap(), 0);
    }

    #[tokio::test]
    async fn continue_lets_healthy_branch_finish() {
        // One branch fails, the other still receives every record.
        let (good, store) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(8)))
            .tee("t", 8, Some(2))
            .sink("bad", Box::new(FailingSink))
            .sink("good", Box::new(good))
            .edge("s", "t")
            .edge("t", "bad")
            .edge("t", "good")
            .build()
            .unwrap();
        let opts = TopologyOptions::new("p").with_on_error(TopologyOnError::Continue);
        let result = topo.run(opts).await.unwrap();
        assert_eq!(store.lock().unwrap().len(), 8);
        assert!(!result.errors.is_empty(), "failing sink should be recorded");
    }

    #[tokio::test]
    async fn state_agreeing_bookmarks_resume_the_source() {
        let store = Arc::new(MemoryStateStore::new());
        // Both sinks committed the same page → that position is a safe resume.
        store.put("p::a", &json!(100)).await.unwrap();
        store.put("p::b", &json!(100)).await.unwrap();
        let applied = Arc::new(Mutex::new(None));
        let src = RecordingSource {
            records: recs(1),
            applied: applied.clone(),
        };
        let (s1, _) = CollectSink::new();
        let (s2, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", Box::new(src))
            .tee("t", 4, Some(2))
            .sink("a", Box::new(s1))
            .sink("b", Box::new(s2))
            .edge("s", "t")
            .edge("t", "a")
            .edge("t", "b")
            .build()
            .unwrap();
        let opts = TopologyOptions::new("p").with_state_store(store.clone());
        topo.run(opts).await.unwrap();
        assert_eq!(*applied.lock().unwrap(), Some(json!(100)));
    }

    #[tokio::test]
    async fn state_diverged_bookmarks_replay_in_full() {
        // #456 H1: bookmarks are compared for equality, never ordered — an
        // ordered "minimum" over structured positions can sit ahead of the true
        // minimum and skip the lagging sink's records. Diverged → full replay.
        let store = Arc::new(MemoryStateStore::new());
        store.put("p::a", &json!(250)).await.unwrap();
        store.put("p::b", &json!(100)).await.unwrap();
        let applied = Arc::new(Mutex::new(None));
        let src = RecordingSource {
            records: recs(1),
            applied: applied.clone(),
        };
        let (s1, _) = CollectSink::new();
        let (s2, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", Box::new(src))
            .tee("t", 4, Some(2))
            .sink("a", Box::new(s1))
            .sink("b", Box::new(s2))
            .edge("s", "t")
            .edge("t", "a")
            .edge("t", "b")
            .build()
            .unwrap();
        let opts = TopologyOptions::new("p").with_state_store(store.clone());
        topo.run(opts).await.unwrap();
        assert_eq!(
            *applied.lock().unwrap(),
            None,
            "diverged bookmarks must replay, never guess an order"
        );
    }

    #[tokio::test]
    async fn state_multi_source_never_cross_applies_a_bookmark() {
        // #456 H1: nothing records which source a sink's bookmark came from, so
        // applying one to every source would resume a source somewhere it has
        // never been. Multi-source graphs replay in full.
        let store = Arc::new(MemoryStateStore::new());
        store.put("p::k", &json!(500)).await.unwrap();
        let a_applied = Arc::new(Mutex::new(None));
        let b_applied = Arc::new(Mutex::new(None));
        let a = RecordingSource {
            records: recs(1),
            applied: a_applied.clone(),
        };
        let b = RecordingSource {
            records: recs(1),
            applied: b_applied.clone(),
        };
        let (sink, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("a", Box::new(a))
            .source("b", Box::new(b))
            .merge("m")
            .sink("k", Box::new(sink))
            .edge("a", "m")
            .edge("b", "m")
            .edge("m", "k")
            .build()
            .unwrap();
        let opts = TopologyOptions::new("p").with_state_store(store.clone());
        topo.run(opts).await.unwrap();
        assert_eq!(*a_applied.lock().unwrap(), None);
        assert_eq!(*b_applied.lock().unwrap(), None);
    }

    #[tokio::test]
    async fn state_no_bookmark_when_a_sink_is_missing() {
        let store = Arc::new(MemoryStateStore::new());
        store.put("p::a", &json!(100)).await.unwrap();
        // sink b has no stored bookmark → full replay (no apply).
        let applied = Arc::new(Mutex::new(None));
        let src = RecordingSource {
            records: recs(1),
            applied: applied.clone(),
        };
        let (s1, _) = CollectSink::new();
        let (s2, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", Box::new(src))
            .tee("t", 4, Some(2))
            .sink("a", Box::new(s1))
            .sink("b", Box::new(s2))
            .edge("s", "t")
            .edge("t", "a")
            .edge("t", "b")
            .build()
            .unwrap();
        let opts = TopologyOptions::new("p").with_state_store(store.clone());
        topo.run(opts).await.unwrap();
        assert_eq!(*applied.lock().unwrap(), None);
    }

    #[tokio::test]
    async fn sink_persists_bookmark() {
        let store = Arc::new(MemoryStateStore::new());
        let (sink, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", VecSource::boxed_bm(recs(2), json!("v9")))
            .sink("k", Box::new(sink))
            .edge("s", "k")
            .build()
            .unwrap();
        let opts = TopologyOptions::new("p").with_state_store(store.clone());
        let result = topo.run(opts).await.unwrap();
        assert_eq!(result.bookmarks.get("k"), Some(&Some(json!("v9"))));
        assert_eq!(
            store
                .get("p::k")
                .await
                .unwrap()
                .map(|v| crate::state_version::peel_versioned(&v)),
            Some(json!("v9"))
        );
    }

    /// #456 M1: a node failure under `Propagate` must let its siblings stop at a
    /// page boundary and **flush**, not drop them where they stand (which
    /// orphans a multipart upload / writes a footer-less file).
    #[tokio::test]
    async fn propagate_lets_siblings_flush_before_returning_the_error() {
        let flushed = Arc::new(Mutex::new(false));
        let tracker = FlushTrackingSink {
            flushed: flushed.clone(),
        };
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(64)))
            .tee("t", 4, Some(2))
            .sink("bad", Box::new(FailingSink))
            .sink("good", Box::new(tracker))
            .edge("s", "t")
            .edge("t", "bad")
            .edge("t", "good")
            .build()
            .unwrap();
        let opts = TopologyOptions::new("p").with_on_error(TopologyOnError::Propagate);
        let err = topo.run(opts).await.unwrap_err();
        assert!(matches!(err, FaucetError::Sink(_)), "{err:?}");
        assert!(
            *flushed.lock().unwrap(),
            "the healthy sink node must be flushed, not dropped mid-write"
        );
    }

    /// #456 C3: the governance passes must apply to a topology's sink nodes, or a
    /// config declaring masking writes PII in the clear.
    #[cfg(feature = "masking")]
    #[tokio::test]
    async fn masking_applies_to_a_sink_node() {
        use crate::masking::{CompiledMasking, MaskingSpec};

        let spec: MaskingSpec = serde_json::from_value(json!({
            "rules": [{
                "name": "hide-email",
                "match": { "fields": ["email"] },
                "action": { "type": "redact", "mask": "***" }
            }]
        }))
        .unwrap();
        let compiled = Arc::new(CompiledMasking::compile(&spec).unwrap());

        let (sink, store) = CollectSink::new();
        let topo = Topology::builder()
            .source(
                "s",
                VecSource::boxed(vec![json!({"id": 1, "email": "a@b.c"})]),
            )
            .sink("k", Box::new(sink))
            .edge("s", "k")
            .build()
            .unwrap();

        let mut governance = TopologyGovernance::new();
        governance.masking_by_sink.insert("k".to_string(), compiled);
        topo.run_with(TopologyOptions::new("p"), governance)
            .await
            .unwrap();

        let written = store.lock().unwrap();
        assert_eq!(written.len(), 1);
        assert_eq!(written[0]["email"], json!("***"), "PII must be masked");
        assert_eq!(written[0]["id"], json!(1));
    }

    #[tokio::test]
    async fn cancellation_stops_the_run() {
        let cancel = CancellationToken::new();
        cancel.cancel(); // pre-cancelled
        let (sink, store) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(1000)))
            .sink("k", Box::new(sink))
            .edge("s", "k")
            .build()
            .unwrap();
        let opts = TopologyOptions::new("p").with_cancel(cancel);
        let result = topo.run(opts).await.unwrap();
        // Cancelled before/early: far fewer than 1000 records written.
        assert!(store.lock().unwrap().len() < 1000);
        let _ = result;
    }

    #[test]
    fn start_bookmark_only_resumes_when_provably_safe() {
        // Every sink agrees, single source → resume there.
        assert_eq!(
            start_bookmark(&[json!(100), json!(100)], 1),
            Some(json!(100))
        );
        // Structured positions that agree are fine too — no ordering needed.
        let lsn = json!({"slot": "s", "lsn": "0/16B3748"});
        assert_eq!(
            start_bookmark(&[lsn.clone(), lsn.clone()], 1),
            Some(lsn.clone())
        );

        // Diverged scalars → replay. The old code returned `min` = 100 here;
        // for the structured case below that "minimum" was text-ordered and
        // could sit ahead of the true minimum (#456 H1).
        assert_eq!(start_bookmark(&[json!(250), json!(100)], 1), None);
        // The exact shape that made a text-ordered minimum unsafe: "0/9…" sorts
        // above "0/10…" lexicographically while being *behind* it numerically.
        assert_eq!(
            start_bookmark(
                &[json!({"lsn": "0/9FFFFFF"}), json!({"lsn": "0/10000000"}),],
                1
            ),
            None
        );

        // More than one source → never cross-apply.
        assert_eq!(start_bookmark(&[json!(100), json!(100)], 2), None);
        // No sinks / no bookmarks → nothing to resume from.
        assert_eq!(start_bookmark(&[], 1), None);
        assert_eq!(start_bookmark(&[], 3), None);
    }

    #[test]
    fn kind_str_matches() {
        assert_eq!(NodeKind::Merge.kind_str(), "merge");
        assert_eq!(
            NodeKind::Tee {
                capacity: 1,
                fanout: None
            }
            .kind_str(),
            "tee"
        );
    }

    #[test]
    fn builder_exposes_nodes_and_edges() {
        let (sink, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(1)))
            .sink("k", Box::new(sink))
            .edge("s", "k")
            .build()
            .unwrap();
        assert_eq!(topo.nodes().len(), 2);
        assert_eq!(topo.edges().len(), 1);
    }

    #[cfg(feature = "transform-keys-case")]
    #[tokio::test]
    async fn transform_node_applies_stage() {
        use crate::stage::{TransformStage, compile_stage};
        use crate::transform::{KeyCaseMode, RecordTransform};
        let stage = compile_stage(&TransformStage::Map(RecordTransform::KeysCase {
            mode: KeyCaseMode::Snake,
            on_collision: Default::default(),
        }))
        .unwrap();
        let (sink, store) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(vec![json!({"FooBar": 1})]))
            .transform("t", vec![stage])
            .sink("k", Box::new(sink))
            .edge("s", "t")
            .edge("t", "k")
            .build()
            .unwrap();
        topo.run(TopologyOptions::new("p")).await.unwrap();
        let w = store.lock().unwrap();
        assert!(w[0].get("foo_bar").is_some());
    }
}

#[cfg(test)]
mod delivery_and_report_tests {
    use super::tests::{BreakerSink, CollectSink, FailingSink, VecSource, recs};
    use super::*;
    use crate::Stream;
    use crate::idempotency::{DeliveryMode, format_token_with_bookmark, wrap_state};
    use crate::state::{MemoryStateStore, StateStore};
    use async_trait::async_trait;
    use serde_json::json;
    use std::sync::Mutex;

    /// A sink that records a commit token per scope, like the SQL sinks do.
    struct TokenSink {
        rows: Arc<Mutex<Vec<Value>>>,
        tokens: Arc<Mutex<std::collections::HashMap<String, String>>>,
    }
    #[async_trait]
    impl Sink for TokenSink {
        async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
            self.rows.lock().unwrap().extend_from_slice(records);
            Ok(records.len())
        }
        fn supports_idempotent_writes(&self) -> bool {
            true
        }
        async fn write_batch_idempotent(
            &self,
            records: &[Value],
            scope: &str,
            token: &str,
        ) -> Result<usize, FaucetError> {
            self.rows.lock().unwrap().extend_from_slice(records);
            self.tokens
                .lock()
                .unwrap()
                .insert(scope.to_string(), token.to_string());
            Ok(records.len())
        }
        async fn last_committed_token(&self, scope: &str) -> Result<Option<String>, FaucetError> {
            Ok(self.tokens.lock().unwrap().get(scope).cloned())
        }
    }

    /// #458: a sink node under `delivery: exactly_once` must commit through the
    /// idempotent write path, under **its own** scope (its state key), so each
    /// sink's watermark is independent of its siblings'.
    #[tokio::test]
    async fn exactly_once_commits_a_token_per_sink_node_scope() {
        let rows = Arc::new(Mutex::new(Vec::new()));
        let tokens = Arc::new(Mutex::new(std::collections::HashMap::new()));
        let sink = TokenSink {
            rows: rows.clone(),
            tokens: tokens.clone(),
        };
        let store = Arc::new(MemoryStateStore::new());
        let topo = Topology::builder()
            .source("s", Box::new(EoSource(recs(3))))
            .sink("k", Box::new(sink))
            .edge("s", "k")
            .build()
            .unwrap();

        let mut gov = TopologyGovernance::new();
        gov.delivery = DeliveryMode::ExactlyOnce;
        let opts = TopologyOptions::new("p").with_state_store(store.clone());
        topo.run_with(opts, gov).await.unwrap();

        assert_eq!(rows.lock().unwrap().len(), 3);
        let committed = tokens.lock().unwrap();
        assert!(
            committed.contains_key("p::k"),
            "token must be scoped to the sink node's own state key, got {:?}",
            committed.keys().collect::<Vec<_>>()
        );
    }

    /// A source that reports deterministic replay and emits a bookmark per page,
    /// which is what the atomic-watermark mechanism requires.
    struct EoSource(Vec<Value>);
    #[async_trait]
    impl Source for EoSource {
        async fn fetch_with_context(
            &self,
            _ctx: &std::collections::HashMap<String, Value>,
        ) -> Result<Vec<Value>, FaucetError> {
            Ok(self.0.clone())
        }
        fn stream_pages<'a>(
            &'a self,
            _ctx: &'a std::collections::HashMap<String, Value>,
            _batch: usize,
        ) -> Pin<Box<dyn Stream<Item = Result<StreamPage, FaucetError>> + Send + 'a>> {
            let rows = self.0.clone();
            Box::pin(async_stream::try_stream! {
                yield StreamPage { records: rows, bookmark: Some(json!({"pos": 1})) };
            })
        }
        fn replay_guarantee(&self) -> crate::idempotency::ReplayGuarantee {
            crate::idempotency::ReplayGuarantee::Deterministic
        }
        fn supports_exactly_once(&self) -> bool {
            true
        }
    }

    /// #458: exactly-once *can* order sinks, because `seq` is a monotonic counter.
    /// Resume from the furthest-behind sink; the ones ahead skip via their tokens.
    #[test]
    fn eo_resume_picks_the_lowest_sequence() {
        let a = (7u64, Some(json!({"pos": 7})));
        let b = (4u64, Some(json!({"pos": 4})));
        let c = (9u64, Some(json!({"pos": 9})));
        assert_eq!(
            eo_start_bookmark(&[a.clone(), b.clone(), c.clone()], 1),
            Some(json!({"pos": 4})),
            "resume from the laggard, not the leader"
        );
        // Still never cross-applies in a multi-source graph.
        assert_eq!(eo_start_bookmark(&[a, b, c], 2), None);
        assert_eq!(eo_start_bookmark(&[], 1), None);
    }

    /// The EO envelope must be unwrapped on read — a raw `get` would hand the
    /// source `{"__faucet_eo": …}` instead of its bookmark.
    #[tokio::test]
    async fn eo_resume_unwraps_the_state_envelope() {
        let store = Arc::new(MemoryStateStore::new());
        store
            .put("p::k", &wrap_state(Some(&json!({"pos": 5})), 5))
            .await
            .unwrap();
        let opts = TopologyOptions::new("p").with_state_store(store.clone());
        let bm = compute_start_bookmark(
            &opts,
            &["k".to_string()],
            1,
            DeliveryMode::ExactlyOnce,
            None,
        )
        .await
        .unwrap();
        assert_eq!(bm, Some(json!({"pos": 5})), "envelope must be unwrapped");
        // A bare token round-trips through parse_token_parts the same way.
        let t = format_token_with_bookmark(5, Some(&json!({"pos": 5})));
        assert!(t.contains('#'), "token embeds the bookmark: {t}");
    }

    /// #658: the class of a node failure travels typed, not as prose.
    #[test]
    fn node_error_kind_classifies_only_the_breaker() {
        // The table is one line, but it is the whole point of the field: the
        // class comes from the typed error, so no consumer has to read prose.
        assert_eq!(
            NodeErrorKind::classify(&FaucetError::CircuitOpen {
                failures: 3,
                cooldown: std::time::Duration::from_secs(30),
            }),
            NodeErrorKind::CircuitOpen
        );
        // A message that merely *reads* like a trip is not one.
        assert_eq!(
            NodeErrorKind::classify(&FaucetError::Sink(
                "Circuit open after 3 consecutive failures".into()
            )),
            NodeErrorKind::Other
        );
    }

    #[tokio::test]
    async fn a_breaker_trip_is_reported_on_the_node_that_raised_it_only() {
        // The edge case #658 names: when one node trips and its siblings are
        // cancelled so they can flush, only the node that actually raised
        // `CircuitOpen` may carry that kind — otherwise the scheduler would
        // apply a breaker cooldown for an unrelated cancellation.
        let (healthy, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(4)))
            .tee("t", 4, Some(2))
            .sink("tripped", Box::new(BreakerSink))
            .sink("healthy", Box::new(healthy))
            .edge("s", "t")
            .edge("t", "tripped")
            .edge("t", "healthy")
            .build()
            .unwrap();

        let run = topo
            .run_reported(
                TopologyOptions::new("p").with_on_error(TopologyOnError::Continue),
                TopologyGovernance::new(),
            )
            .await
            .unwrap();

        let tripped = run.nodes.iter().find(|n| n.node_id == "tripped").unwrap();
        assert_eq!(
            tripped.error_kind,
            Some(NodeErrorKind::CircuitOpen),
            "the node that raised the trip must carry the class that earns the cooldown"
        );

        let classified: Vec<&str> = run
            .nodes
            .iter()
            .filter(|n| n.error_kind == Some(NodeErrorKind::CircuitOpen))
            .map(|n| n.node_id.as_str())
            .collect();
        assert_eq!(
            classified,
            vec!["tripped"],
            "exactly one node may be classified as the breaker trip"
        );
        // A node that did not fail carries no kind at all — `None` is
        // "did not fail", never "failed, unclassified".
        let healthy = run.nodes.iter().find(|n| n.node_id == "healthy").unwrap();
        assert_eq!(healthy.error_kind, None);
    }

    /// #459: the CLI needs to know *which* sink node failed to notify per node.
    #[tokio::test]
    async fn run_reported_attributes_failures_to_their_node() {
        let (good, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(4)))
            .tee("t", 4, Some(2))
            .sink("bad", Box::new(FailingSink))
            .sink("good", Box::new(good))
            .edge("s", "t")
            .edge("t", "bad")
            .edge("t", "good")
            .build()
            .unwrap();
        let run = topo
            .run_reported(
                TopologyOptions::new("p").with_on_error(TopologyOnError::Continue),
                TopologyGovernance::new(),
            )
            .await
            .unwrap();

        let bad = run.nodes.iter().find(|n| n.node_id == "bad").unwrap();
        assert!(bad.error.is_some(), "the failing sink is attributed");
        assert_eq!(
            bad.error_kind,
            Some(NodeErrorKind::Other),
            "an ordinary sink failure is classified, just not as a breaker trip"
        );
        let good = run.nodes.iter().find(|n| n.node_id == "good").unwrap();
        assert!(good.error.is_none(), "the healthy sink is not");
        assert_eq!(good.records, 4);
        // Every node appears, with its kind.
        assert_eq!(run.nodes.len(), 4);
        assert!(run.nodes.iter().any(|n| n.kind == "source"));
        assert!(run.nodes.iter().any(|n| n.kind == "tee"));
    }
}

#[cfg(test)]
#[allow(clippy::disallowed_methods)] // tests drive time and raw clients directly
mod graph_safety_tests {
    use super::tests::{CollectSink, FailingSink, VecSource, recs};
    use super::*;
    use crate::Stream;
    use crate::idempotency::{DeliveryMode, format_token_with_bookmark, wrap_state};
    use crate::state::MemoryStateStore;
    use async_trait::async_trait;
    use serde_json::json;
    use std::sync::Mutex;

    /// A source over `pos` 1..=`total`, `per_page` records per page, each page
    /// bookmarked `{"pos": <last record>}`. Resuming from `{"pos": p}` continues
    /// at `p + 1`. `ordered` makes it order positions like a CDC source.
    struct LogSource {
        total: u64,
        per_page: u64,
        ordered: bool,
        start: Mutex<u64>,
        applied: Arc<Mutex<Option<Value>>>,
    }
    impl LogSource {
        fn new(total: u64, per_page: u64, ordered: bool) -> (Self, Arc<Mutex<Option<Value>>>) {
            let applied = Arc::new(Mutex::new(None));
            (
                Self {
                    total,
                    per_page,
                    ordered,
                    start: Mutex::new(0),
                    applied: applied.clone(),
                },
                applied,
            )
        }
    }
    #[async_trait]
    impl Source for LogSource {
        async fn fetch_with_context(
            &self,
            _c: &HashMap<String, Value>,
        ) -> Result<Vec<Value>, FaucetError> {
            Ok(Vec::new())
        }
        fn stream_pages<'a>(
            &'a self,
            _ctx: &'a HashMap<String, Value>,
            _batch: usize,
        ) -> Pin<Box<dyn Stream<Item = Result<StreamPage, FaucetError>> + Send + 'a>> {
            let mut next = *self.start.lock().unwrap() + 1;
            let (total, per_page) = (self.total, self.per_page);
            Box::pin(async_stream::try_stream! {
                while next <= total {
                    let last = (next + per_page - 1).min(total);
                    let records: Vec<Value> = (next..=last).map(|n| json!({ "n": n })).collect();
                    yield StreamPage { records, bookmark: Some(json!({ "pos": last })) };
                    next = last + 1;
                }
            })
        }
        async fn apply_start_bookmark(&self, bm: Value) -> Result<(), FaucetError> {
            *self.start.lock().unwrap() = bm["pos"].as_u64().unwrap_or(0);
            *self.applied.lock().unwrap() = Some(bm);
            Ok(())
        }
        fn replay_guarantee(&self) -> crate::idempotency::ReplayGuarantee {
            crate::idempotency::ReplayGuarantee::Deterministic
        }
        fn supports_exactly_once(&self) -> bool {
            true
        }
        fn position_le(&self, a: &Value, b: &Value) -> Option<bool> {
            if !self.ordered {
                return None;
            }
            Some(a["pos"].as_u64()? <= b["pos"].as_u64()?)
        }
        fn record_covered(&self, record: &Value, position: &Value) -> Option<bool> {
            if !self.ordered {
                return None;
            }
            Some(record["n"].as_u64()? <= position["pos"].as_u64()?)
        }
    }

    /// An idempotent sink keeping its rows and one commit token per scope.
    #[derive(Clone)]
    struct TokenSink {
        rows: Arc<Mutex<Vec<Value>>>,
        tokens: Arc<Mutex<HashMap<String, String>>>,
    }
    impl TokenSink {
        fn new() -> Self {
            Self {
                rows: Arc::new(Mutex::new(Vec::new())),
                tokens: Arc::new(Mutex::new(HashMap::new())),
            }
        }
        fn committed(self, scope: &str, seq: u64, pos: u64) -> Self {
            self.tokens.lock().unwrap().insert(
                scope.into(),
                format_token_with_bookmark(seq, Some(&json!({ "pos": pos }))),
            );
            self
        }
        fn ns(&self) -> Vec<u64> {
            self.rows
                .lock()
                .unwrap()
                .iter()
                .filter_map(|r| r["n"].as_u64())
                .collect()
        }
    }
    #[async_trait]
    impl Sink for TokenSink {
        async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
            self.rows.lock().unwrap().extend_from_slice(records);
            Ok(records.len())
        }
        fn supports_idempotent_writes(&self) -> bool {
            true
        }
        async fn write_batch_idempotent(
            &self,
            records: &[Value],
            scope: &str,
            token: &str,
        ) -> Result<usize, FaucetError> {
            self.rows.lock().unwrap().extend_from_slice(records);
            self.tokens
                .lock()
                .unwrap()
                .insert(scope.to_string(), token.to_string());
            Ok(records.len())
        }
        async fn last_committed_token(&self, scope: &str) -> Result<Option<String>, FaucetError> {
            Ok(self.tokens.lock().unwrap().get(scope).cloned())
        }
    }

    async fn seed(store: &MemoryStateStore, key: &str, pos: u64, seq: u64) {
        store
            .put(key, &wrap_state(Some(&json!({ "pos": pos })), seq))
            .await
            .unwrap();
    }

    async fn stored_seq(store: &MemoryStateStore, key: &str) -> u64 {
        let v = store.get(key).await.unwrap().unwrap();
        crate::idempotency::unwrap_state(&crate::state_version::peel_versioned(&v)).1
    }

    fn eo() -> TopologyGovernance {
        let mut g = TopologyGovernance::new();
        g.delivery = DeliveryMode::ExactlyOnce;
        g
    }

    fn two_sink_graph(source: LogSource, ahead: TokenSink, behind: TokenSink) -> Topology {
        Topology::builder()
            .source("s", Box::new(source))
            .tee("t", 4, Some(2))
            .sink("ahead", Box::new(ahead))
            .sink("behind", Box::new(behind))
            .edge("s", "t")
            .edge("t", "ahead")
            .edge("t", "behind")
            .build()
            .unwrap()
    }

    /// #862 H-07: with diverged sinks and a source that cannot order positions,
    /// skipping replayed pages by count is unsafe (a replay need not produce
    /// the same pages), so the run refuses instead of losing or duplicating.
    #[tokio::test]
    async fn eo_diverged_sinks_refuse_when_the_source_cannot_order_positions() {
        let store = Arc::new(MemoryStateStore::new());
        seed(&store, "p::ahead", 9, 9).await;
        seed(&store, "p::behind", 5, 5).await;
        let ahead = TokenSink::new().committed("p::ahead", 9, 9);
        let behind = TokenSink::new().committed("p::behind", 5, 5);
        let (source, applied) = LogSource::new(10, 1, false);
        let topo = two_sink_graph(source, ahead.clone(), behind.clone());

        let err = topo
            .run_with(
                TopologyOptions::new("p").with_state_store(store.clone()),
                eo(),
            )
            .await
            .unwrap_err();

        let msg = err.to_string();
        assert!(msg.contains("cannot order its positions"), "{msg}");
        assert!(msg.contains("'ahead' at seq 9"), "{msg}");
        assert_eq!(*applied.lock().unwrap(), None, "nothing was replayed");
        assert!(ahead.ns().is_empty() && behind.ns().is_empty());
        assert_eq!(stored_seq(&store, "p::ahead").await, 9);
    }

    /// #862 M-027: a replayed page that straddles the position a sink ahead
    /// committed keeps only the records past it.
    #[tokio::test]
    async fn eo_a_straddling_replayed_page_drops_the_committed_records() {
        let store = Arc::new(MemoryStateStore::new());
        seed(&store, "p::ahead", 6, 6).await;
        seed(&store, "p::behind", 5, 5).await;
        let ahead = TokenSink::new().committed("p::ahead", 6, 6);
        let behind = TokenSink::new().committed("p::behind", 5, 5);
        let (source, _) = LogSource::new(10, 2, true);
        let topo = two_sink_graph(source, ahead.clone(), behind.clone());

        topo.run_with(
            TopologyOptions::new("p").with_state_store(store.clone()),
            eo(),
        )
        .await
        .unwrap();

        assert_eq!(ahead.ns(), vec![7, 8, 9, 10], "record 6 was committed");
        assert_eq!(behind.ns(), vec![6, 7, 8, 9, 10]);
    }

    /// review 868 other 1: a straddling page whose records lost the source's
    /// position fields to a transform fails rather than writing duplicates.
    #[tokio::test]
    async fn eo_a_straddling_page_without_position_fields_is_refused() {
        let store = Arc::new(MemoryStateStore::new());
        seed(&store, "p::ahead", 6, 6).await;
        seed(&store, "p::behind", 5, 5).await;
        let ahead = TokenSink::new().committed("p::ahead", 6, 6);
        let behind = TokenSink::new().committed("p::behind", 5, 5);
        let (source, _) = LogSource::new(10, 2, true);
        let strip: crate::stage::PageFnBox = Arc::new(|records: Vec<Value>| {
            Ok(records
                .into_iter()
                .map(|r| json!({ "m": r["n"].clone() }))
                .collect())
        });
        let topo = Topology::builder()
            .source("s", Box::new(source))
            .transform("x", vec![CompiledStage::PageFn(strip)])
            .tee("t", 4, Some(2))
            .sink("ahead", Box::new(ahead.clone()))
            .sink("behind", Box::new(behind))
            .edge("s", "x")
            .edge("x", "t")
            .edge("t", "ahead")
            .edge("t", "behind")
            .build()
            .unwrap();
        let err = topo
            .run_with(
                TopologyOptions::new("p").with_state_store(store.clone()),
                eo(),
            )
            .await
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("position fields") && err.contains("'ahead'"),
            "{err}"
        );
        assert!(
            ahead.rows.lock().unwrap().is_empty(),
            "nothing was written twice"
        );
    }

    #[test]
    fn trim_covered_keeps_unclassified_records_for_a_keyed_sink() {
        let (src, _) = LogSource::new(1, 1, true);
        let mut records = vec![json!({ "n": 1 }), json!({ "n": 3 }), json!({ "m": 2 })];
        trim_covered(&mut records, &src, &json!({ "pos": 2 }), true, "k").unwrap();
        assert_eq!(records, vec![json!({ "n": 3 }), json!({ "m": 2 })]);
    }

    /// #862 M-010: a page-level stage in a transform node runs off the worker,
    /// so other tasks on a one-worker runtime keep running meanwhile.
    #[tokio::test(flavor = "multi_thread", worker_threads = 1)]
    async fn a_slow_page_stage_in_a_transform_node_does_not_pin_the_worker() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let slow: crate::stage::PageFnBox = Arc::new(|records: Vec<Value>| {
            std::thread::sleep(std::time::Duration::from_millis(400));
            Ok(records)
        });
        let (source, _) = LogSource::new(1, 1, false);
        let sink = TokenSink::new();
        let topo = Topology::builder()
            .source("s", Box::new(source))
            .transform("x", vec![CompiledStage::PageFn(slow)])
            .sink("k", Box::new(sink.clone()))
            .edge("s", "x")
            .edge("x", "k")
            .build()
            .unwrap();
        let ticks = Arc::new(AtomicUsize::new(0));
        let t = ticks.clone();
        let ticker = tokio::spawn(async move {
            loop {
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                t.fetch_add(1, Ordering::SeqCst);
            }
        });
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
        let before = ticks.load(Ordering::SeqCst);
        topo.run(TopologyOptions::new("p")).await.unwrap();
        let during = ticks.load(Ordering::SeqCst) - before;
        ticker.abort();
        assert_eq!(sink.ns(), vec![1]);
        assert!(during >= 20, "the ticker starved: {during} ticks");
    }

    /// Positions ordered per component (one offset per partition): a page
    /// past the position in one component only still straddles it.
    #[test]
    fn covered_page_follows_a_partial_order() {
        struct Pair;
        #[async_trait]
        impl Source for Pair {
            async fn fetch_with_context(
                &self,
                _ctx: &HashMap<String, Value>,
            ) -> Result<Vec<Value>, FaucetError> {
                Ok(Vec::new())
            }
            fn position_le(&self, a: &Value, b: &Value) -> Option<bool> {
                Some(a["x"].as_u64()? <= b["x"].as_u64()? && a["y"].as_u64()? <= b["y"].as_u64()?)
            }
        }
        let through = json!({ "x": 5, "y": 5 });
        let page = |bm: Option<Value>| StreamPage {
            records: Vec::new(),
            bookmark: bm,
        };
        let cov = |bm| covered_page(&Pair, &page(bm), &through);
        assert_eq!(
            cov(Some(json!({ "x": 4, "y": 5 }))),
            PageCoverage::Committed
        );
        assert_eq!(
            cov(Some(json!({ "x": 9, "y": 3 }))),
            PageCoverage::Straddles
        );
        assert_eq!(cov(Some(json!({ "x": 9, "y": 5 }))), PageCoverage::Past);
        assert_eq!(cov(None), PageCoverage::Straddles);
    }

    /// CORE-01 with a source that orders its positions: replayed page boundaries
    /// may differ from the original ones, and the sink ahead still skips exactly
    /// what it committed, by position rather than by page count.
    #[tokio::test]
    async fn eo_diverged_sinks_skip_by_position_when_the_source_orders_them() {
        let store = Arc::new(MemoryStateStore::new());
        seed(&store, "p::ahead", 9, 9).await;
        seed(&store, "p::behind", 5, 5).await;
        let ahead = TokenSink::new().committed("p::ahead", 9, 9);
        let behind = TokenSink::new().committed("p::behind", 5, 5);
        let (source, applied) = LogSource::new(10, 2, true);
        let topo = two_sink_graph(source, ahead.clone(), behind.clone());

        topo.run_with(
            TopologyOptions::new("p").with_state_store(store.clone()),
            eo(),
        )
        .await
        .unwrap();

        assert_eq!(*applied.lock().unwrap(), Some(json!({ "pos": 5 })));
        assert_eq!(ahead.ns(), vec![10]);
        assert_eq!(behind.ns(), vec![6, 7, 8, 9, 10]);
        assert_eq!(stored_seq(&store, "p::ahead").await, 10);
    }

    /// CORE-11: the sink committed a page the state store never recorded. The
    /// source is re-anchored at the position embedded in the sink's token, so
    /// nothing is re-written and nothing is skipped however the replay is paged.
    #[tokio::test]
    async fn eo_resume_reanchors_from_the_sinks_committed_token() {
        let store = Arc::new(MemoryStateStore::new());
        seed(&store, "p::k", 4, 4).await;
        let sink = TokenSink::new().committed("p::k", 5, 7);
        let (source, applied) = LogSource::new(9, 1, false);
        let topo = Topology::builder()
            .source("s", Box::new(source))
            .sink("k", Box::new(sink.clone()))
            .edge("s", "k")
            .build()
            .unwrap();

        topo.run_with(
            TopologyOptions::new("p").with_state_store(store.clone()),
            eo(),
        )
        .await
        .unwrap();

        assert_eq!(*applied.lock().unwrap(), Some(json!({ "pos": 7 })));
        assert_eq!(sink.ns(), vec![8, 9]);
        assert_eq!(stored_seq(&store, "p::k").await, 7);
    }

    #[test]
    fn eo_plan_without_a_committed_position_replays_from_zero() {
        let (src, _) = LogSource::new(1, 1, false);
        let err = plan_exactly_once(
            &[
                ("a".into(), Some(json!({ "pos": 3 })), 3),
                ("b".into(), None, 0),
            ],
            1,
            Some(&src),
            "p",
        )
        .unwrap_err();
        assert!(
            err.to_string().contains("'b' with no committed position"),
            "an unordered source cannot skip by count (#862 H-07): {err}"
        );
        assert!(
            err.to_string().contains("'p::a', 'p::b'")
                && err.to_string().contains("delete every sink node's state"),
            "the refusal names the recovery: {err}"
        );
        let plan = plan_exactly_once(
            &[("a".into(), None, 0), ("b".into(), None, 0)],
            1,
            Some(&src),
            "p",
        )
        .unwrap();
        assert_eq!(plan.start, None);
        assert!(plan.sinks.values().all(|r| r.start_seq == 0));

        let (ordered, _) = LogSource::new(1, 1, true);
        let plan = plan_exactly_once(
            &[
                ("a".into(), Some(json!({ "pos": 3 })), 3),
                ("b".into(), None, 0),
            ],
            1,
            Some(&ordered),
            "p",
        )
        .unwrap();
        assert_eq!(plan.start, None);
        assert_eq!(plan.sinks["a"].skip_through, Some(json!({ "pos": 3 })));
        assert_eq!(plan.sinks["a"].start_seq, 3);
        assert_eq!(plan.sinks["b"].skip_through, None);
    }

    #[test]
    fn eo_plan_for_several_sources_keeps_each_sinks_sequence() {
        let plan = plan_exactly_once(
            &[
                ("a".into(), Some(json!({ "pos": 3 })), 3),
                ("b".into(), Some(json!({ "pos": 4 })), 4),
            ],
            2,
            None,
            "p",
        )
        .unwrap();
        assert_eq!(plan.start, None);
        assert_eq!(plan.sinks["a"].start_seq, 3);
        assert_eq!(plan.sinks["b"].start_seq, 4);
    }

    #[test]
    fn eo_plan_agreeing_sinks_resume_without_skipping() {
        let plan = plan_exactly_once(
            &[
                ("a".into(), Some(json!({ "pos": 3 })), 3),
                ("b".into(), Some(json!({ "pos": 3 })), 6),
            ],
            1,
            None,
            "p",
        )
        .unwrap();
        assert_eq!(plan.start, Some(json!({ "pos": 3 })));
        assert_eq!(plan.sinks["b"].start_seq, 6);
        assert!(plan.sinks.values().all(|r| r.skip_through.is_none()));
    }

    // ── CORE-13 ───────────────────────────────────────────────────────────────

    #[test]
    fn validate_rejects_a_join_fed_by_one_tee_on_both_sides() {
        let jn = JoinNode {
            config: JoinConfig {
                mode: JoinMode::Inner,
                build_key: "i".into(),
                probe_key: "i".into(),
                ..Default::default()
            },
            build_edge: "b".into(),
            probe_edge: "p".into(),
        };
        let (sink, _) = CollectSink::new();
        let err = Topology::builder()
            .source("s", VecSource::boxed(recs(1)))
            .tee("t", 4, Some(2))
            .join("j", jn)
            .sink("k", Box::new(sink))
            .edge("s", "t")
            .labelled_edge("t", "j", "b")
            .labelled_edge("t", "j", "p")
            .edge("j", "k")
            .build()
            .unwrap_err()
            .to_string();
        assert!(err.contains("join 'j'"), "{err}");
        assert!(err.contains("'s'") || err.contains("'t'"), "{err}");
    }

    #[tokio::test]
    async fn dropping_the_run_future_aborts_its_node_tasks() {
        struct Wedged {
            alive: Arc<()>,
            entered: Arc<tokio::sync::Notify>,
        }
        #[async_trait::async_trait]
        impl Sink for Wedged {
            async fn write_batch(&self, _: &[Value]) -> Result<usize, FaucetError> {
                let _hold = Arc::clone(&self.alive);
                self.entered.notify_one();
                std::future::pending().await
            }
        }
        let alive = Arc::new(());
        let entered = Arc::new(tokio::sync::Notify::new());
        let topology = Topology::builder()
            .source("s", VecSource::boxed(recs(2)))
            .sink(
                "k",
                Box::new(Wedged {
                    alive: Arc::clone(&alive),
                    entered: Arc::clone(&entered),
                }),
            )
            .edge("s", "k")
            .build()
            .unwrap();
        let run = tokio::spawn(topology.run(TopologyOptions::default()));
        entered.notified().await;
        run.abort();
        let _ = run.await;
        tokio::time::timeout(Duration::from_secs(5), async {
            while Arc::strong_count(&alive) > 1 {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("the wedged sink node must be aborted with the run");
    }

    #[tokio::test]
    async fn broadcast_gives_up_on_a_full_channel_when_cancelled() {
        let (tx, mut rx) = mpsc::channel::<StreamPage>(1);
        tx.send(StreamPage {
            records: Vec::new(),
            bookmark: None,
        })
        .await
        .unwrap();
        let cancel = CancellationToken::new();
        let trip = cancel.clone();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(20)).await;
            trip.cancel();
        });
        let mut outs = vec![tx.clone(), tx];
        let sent = tokio::time::timeout(
            Duration::from_secs(5),
            broadcast(
                StreamPage {
                    records: recs(1),
                    bookmark: None,
                },
                &mut outs,
                &cancel,
            ),
        )
        .await
        .expect("a cancelled broadcast must not wait on a full channel");
        assert!(!sent);
        assert!(rx.recv().await.is_some());
    }

    #[tokio::test]
    async fn broadcast_drops_closed_outputs() {
        let (live_tx, mut live_rx) = mpsc::channel::<StreamPage>(4);
        let (dead_tx, dead_rx) = mpsc::channel::<StreamPage>(4);
        drop(dead_rx);
        let mut outs = vec![dead_tx, live_tx];
        let cancel = CancellationToken::new();
        let page = StreamPage {
            records: recs(2),
            bookmark: None,
        };
        assert!(broadcast(page, &mut outs, &cancel).await);
        assert_eq!(outs.len(), 1);
        assert_eq!(live_rx.recv().await.unwrap().records.len(), 2);
        let mut none: Vec<mpsc::Sender<StreamPage>> = Vec::new();
        let page = StreamPage {
            records: Vec::new(),
            bookmark: None,
        };
        assert!(!broadcast(page, &mut none, &cancel).await);
    }

    #[tokio::test]
    async fn a_cancelled_receive_returns_none() {
        let (_tx, mut rx) = mpsc::channel::<StreamPage>(1);
        let cancel = CancellationToken::new();
        cancel.cancel();
        assert!(recv_or_cancel(&mut rx, &cancel).await.is_none());
    }

    // ── CORE-12 ───────────────────────────────────────────────────────────────

    #[test]
    fn merge_mode_follows_the_inputs_origins() {
        let set = |ids: &[&str]| ids.iter().map(|s| s.to_string()).collect::<HashSet<_>>();
        assert_eq!(
            merge_mode(&[set(&["a"]), set(&["b"])]),
            MergeMode::Passthrough
        );
        assert_eq!(merge_mode(&[set(&["a"]), set(&["a"])]), MergeMode::Gated);
        assert_eq!(
            merge_mode(&[set(&["a", "b"]), set(&["a"])]),
            MergeMode::Strip
        );
    }

    #[test]
    fn bookmark_gate_releases_a_position_only_once_every_input_delivered_it() {
        let mut gate = BookmarkGate::new(2);
        assert_eq!(gate.arrive(0, json!(1)), None);
        assert_eq!(gate.arrive(0, json!(2)), None);
        assert_eq!(gate.arrive(1, json!(1)), Some(json!(1)));
        assert_eq!(gate.arrive(1, json!(2)), Some(json!(2)));
        assert_eq!(gate.arrive(1, json!(3)), None);
        // The lagging input closes: everything the other one delivered is safe.
        assert_eq!(gate.close(0), Some(json!(3)));
        assert_eq!(gate.close(1), None);
    }

    #[test]
    fn graph_facts_gate_a_merge_that_rejoins_one_source() {
        let (k, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(1)))
            .tee("t", 4, Some(2))
            .transform("x", Vec::new())
            .transform("y", Vec::new())
            .merge("m")
            .sink("k", Box::new(k))
            .edge("s", "t")
            .edge("t", "x")
            .edge("t", "y")
            .edge("x", "m")
            .edge("y", "m")
            .edge("m", "k")
            .build()
            .unwrap();
        let facts = GraphFacts::of(topo.nodes(), topo.edges());
        assert_eq!(facts.merge_modes["m"], MergeMode::Gated);
        assert!(facts.ancestors["k"].contains("s"));
        assert!(facts.ancestors["k"].contains("x"));
    }

    /// A state store that logs every put into the same log a sink writes to, so
    /// a test can check the order of "row written" and "position persisted".
    struct LoggingStore {
        inner: MemoryStateStore,
        log: Arc<Mutex<Vec<String>>>,
    }
    #[async_trait]
    impl StateStore for LoggingStore {
        async fn get(&self, key: &str) -> Result<Option<Value>, FaucetError> {
            self.inner.get(key).await
        }
        async fn put(&self, key: &str, value: &Value) -> Result<(), FaucetError> {
            let data = crate::state_version::peel_versioned(value);
            self.log
                .lock()
                .unwrap()
                .push(format!("put {}", data["pos"].as_u64().unwrap_or(0)));
            self.inner.put(key, value).await
        }
        async fn delete(&self, key: &str) -> Result<(), FaucetError> {
            self.inner.delete(key).await
        }
    }

    struct LoggingSink {
        log: Arc<Mutex<Vec<String>>>,
    }
    #[async_trait]
    impl Sink for LoggingSink {
        async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
            let mut log = self.log.lock().unwrap();
            for r in records {
                log.push(format!("row {}", r["n"].as_u64().unwrap_or(0)));
            }
            Ok(records.len())
        }
    }

    /// CORE-12: in a tee → … → merge diamond, a position is persisted only after
    /// both branches' copies of its page were written.
    #[tokio::test]
    async fn a_diamond_persists_a_position_only_after_both_copies_landed() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let store = Arc::new(LoggingStore {
            inner: MemoryStateStore::new(),
            log: log.clone(),
        });
        let (source, _) = LogSource::new(6, 1, false);
        let topo = Topology::builder()
            .source("s", Box::new(source))
            .tee("t", 1, Some(2))
            .transform("x", Vec::new())
            .transform("y", Vec::new())
            .merge("m")
            .sink("k", Box::new(LoggingSink { log: log.clone() }))
            .edge("s", "t")
            .edge("t", "x")
            .edge("t", "y")
            .edge("x", "m")
            .edge("y", "m")
            .edge("m", "k")
            .build()
            .unwrap();
        topo.run(TopologyOptions::new("p").with_state_store(store))
            .await
            .unwrap();

        let log = log.lock().unwrap().clone();
        for (i, entry) in log.iter().enumerate() {
            let Some(pos) = entry.strip_prefix("put ") else {
                continue;
            };
            let copies = log[..i]
                .iter()
                .filter(|e| **e == format!("row {pos}"))
                .count();
            assert_eq!(
                copies, 2,
                "position {pos} persisted before both copies: {log:?}"
            );
        }
        assert_eq!(log.iter().filter(|e| e.starts_with("row")).count(), 12);
        assert!(log.iter().any(|e| e == "put 6"), "{log:?}");
    }

    // ── CORE-14 ───────────────────────────────────────────────────────────────

    struct OverwriteSink {
        log: Arc<Mutex<Vec<String>>>,
        fail_commit: bool,
    }
    #[async_trait]
    impl Sink for OverwriteSink {
        async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
            self.log.lock().unwrap().push("write".into());
            Ok(records.len())
        }
        fn is_overwrite(&self) -> bool {
            true
        }
        async fn begin_overwrite(&self) -> Result<(), FaucetError> {
            self.log.lock().unwrap().push("begin".into());
            Ok(())
        }
        async fn commit_overwrite(&self) -> Result<(), FaucetError> {
            if self.fail_commit {
                return Err(FaucetError::Sink("swap failed".into()));
            }
            self.log.lock().unwrap().push("commit".into());
            Ok(())
        }
        async fn abort_overwrite(&self) -> Result<(), FaucetError> {
            self.log.lock().unwrap().push("abort".into());
            Ok(())
        }
        async fn complete_run(&self) -> Result<(), FaucetError> {
            self.log.lock().unwrap().push("complete".into());
            Ok(())
        }
    }

    #[tokio::test]
    async fn an_overwrite_sink_node_commits_then_persists_its_position() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let store = Arc::new(LoggingStore {
            inner: MemoryStateStore::new(),
            log: log.clone(),
        });
        let (source, _) = LogSource::new(3, 1, false);
        let topo = Topology::builder()
            .source("s", Box::new(source))
            .sink(
                "k",
                Box::new(OverwriteSink {
                    log: log.clone(),
                    fail_commit: false,
                }),
            )
            .edge("s", "k")
            .build()
            .unwrap();
        topo.run(TopologyOptions::new("p").with_state_store(store))
            .await
            .unwrap();
        let log = log.lock().unwrap().clone();
        assert_eq!(
            log,
            vec![
                "begin", "write", "write", "write", "commit", "put 3", "complete"
            ],
            "staged, swapped, then the position — never before the swap"
        );
    }

    #[tokio::test]
    async fn an_overwrite_sink_node_discards_staging_when_another_node_fails() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(3)))
            .tee("t", 4, Some(2))
            .sink(
                "k",
                Box::new(OverwriteSink {
                    log: log.clone(),
                    fail_commit: false,
                }),
            )
            .sink("bad", Box::new(FailingSink))
            .edge("s", "t")
            .edge("t", "k")
            .edge("t", "bad")
            .build()
            .unwrap();
        let run = topo
            .run_reported(
                TopologyOptions::new("p").with_on_error(TopologyOnError::Continue),
                TopologyGovernance::new(),
            )
            .await
            .unwrap();
        assert!(!run.result.errors.is_empty());
        let log = log.lock().unwrap().clone();
        assert!(log.contains(&"abort".to_string()), "{log:?}");
        assert!(!log.contains(&"commit".to_string()), "{log:?}");
    }

    #[tokio::test]
    async fn an_overwrite_sink_node_discards_staging_on_cancel() {
        let log = Arc::new(Mutex::new(Vec::new()));
        let cancel = CancellationToken::new();
        cancel.cancel();
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(3)))
            .sink(
                "k",
                Box::new(OverwriteSink {
                    log: log.clone(),
                    fail_commit: false,
                }),
            )
            .edge("s", "k")
            .build()
            .unwrap();
        topo.run(TopologyOptions::new("p").with_cancel(cancel))
            .await
            .unwrap();
        let log = log.lock().unwrap().clone();
        assert_eq!(log.first().map(String::as_str), Some("begin"));
        assert!(log.contains(&"abort".to_string()), "{log:?}");
        assert!(!log.contains(&"commit".to_string()), "{log:?}");
    }

    #[tokio::test]
    async fn a_failed_swap_fails_the_run_and_discards_the_other_staging() {
        let first = Arc::new(Mutex::new(Vec::new()));
        let second = Arc::new(Mutex::new(Vec::new()));
        let topo = Topology::builder()
            .source("s", VecSource::boxed(recs(2)))
            .tee("t", 4, Some(2))
            .sink(
                "a",
                Box::new(OverwriteSink {
                    log: first.clone(),
                    fail_commit: true,
                }),
            )
            .sink(
                "b",
                Box::new(OverwriteSink {
                    log: second.clone(),
                    fail_commit: false,
                }),
            )
            .edge("s", "t")
            .edge("t", "a")
            .edge("t", "b")
            .build()
            .unwrap();
        let err = topo
            .run(TopologyOptions::new("p"))
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("swap failed"), "{err}");
        let second = second.lock().unwrap().clone();
        assert!(second.contains(&"abort".to_string()), "{second:?}");
        assert!(!second.contains(&"commit".to_string()), "{second:?}");
    }

    // ── CLI-18 (core side) ────────────────────────────────────────────────────

    struct BrokenSource;
    #[async_trait]
    impl Source for BrokenSource {
        async fn fetch_with_context(
            &self,
            _c: &HashMap<String, Value>,
        ) -> Result<Vec<Value>, FaucetError> {
            Err(FaucetError::Source("source down".into()))
        }
    }

    #[tokio::test]
    async fn a_sink_fed_by_a_failed_source_is_reported_failed() {
        let (sink, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("src", Box::new(BrokenSource))
            .transform("x", Vec::new())
            .sink("k", Box::new(sink))
            .edge("src", "x")
            .edge("x", "k")
            .build()
            .unwrap();
        let run = topo
            .run_reported(
                TopologyOptions::new("p").with_on_error(TopologyOnError::Continue),
                TopologyGovernance::new(),
            )
            .await
            .unwrap();
        let k = run.nodes.iter().find(|n| n.node_id == "k").unwrap();
        let err = k.error.as_deref().unwrap_or_default();
        assert!(err.contains("upstream node 'src' failed"), "{err}");
        assert_eq!(k.error_kind, Some(NodeErrorKind::Other));
    }

    /// #862 L-030: a panicking node is recorded as failed before its outputs
    /// close, so a downstream sink does not report its cut-short input as a
    /// complete run.
    #[tokio::test]
    async fn a_sink_fed_by_a_panicking_transform_is_reported_failed() {
        let boom: crate::stage::PageFnBox = Arc::new(|_records: Vec<Value>| panic!("boom"));
        let (source, _) = LogSource::new(1, 1, false);
        let (sink, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("s", Box::new(source))
            .transform("x", vec![CompiledStage::PageFn(boom)])
            .sink("k", Box::new(sink))
            .edge("s", "x")
            .edge("x", "k")
            .build()
            .unwrap();
        let run = topo
            .run_reported(
                TopologyOptions::new("p").with_on_error(TopologyOnError::Continue),
                TopologyGovernance::new(),
            )
            .await
            .unwrap();
        let k = run.nodes.iter().find(|n| n.node_id == "k").unwrap();
        let err = k.error.as_deref().unwrap_or_default();
        assert!(err.contains("upstream node 'x' failed"), "{err}");
        assert!(
            run.result
                .errors
                .iter()
                .any(|e| e.contains("topology node 'x' panicked: boom")),
            "{:?}",
            run.result.errors
        );
    }

    #[tokio::test]
    async fn run_attributed_keeps_the_per_node_report_on_failure() {
        let (sink, _) = CollectSink::new();
        let topo = Topology::builder()
            .source("src", Box::new(BrokenSource))
            .sink("k", Box::new(sink))
            .edge("src", "k")
            .build()
            .unwrap();
        let (run, err) = topo
            .run_attributed(TopologyOptions::new("p"), TopologyGovernance::new())
            .await;
        assert!(err.is_some(), "Propagate surfaces the failure");
        let k = run.nodes.iter().find(|n| n.node_id == "k").unwrap();
        assert!(k.error.is_some(), "the sink is reported, not dropped");
        let src = run.nodes.iter().find(|n| n.node_id == "src").unwrap();
        assert!(
            src.error
                .as_deref()
                .unwrap_or_default()
                .contains("source down")
        );
    }

    #[tokio::test]
    async fn run_attributed_reports_an_invalid_graph() {
        let (run, err) = Topology {
            nodes: Vec::new(),
            edges: Vec::new(),
        }
        .run_attributed(TopologyOptions::new("p"), TopologyGovernance::new())
        .await;
        assert!(err.is_some());
        assert!(run.nodes.is_empty());
    }
}