otel-arrow-dfe-engine 0.61.0

Async pipeline engine
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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

//! Async Pipeline Engine

use crate::{
    admission::AdmissionBinder,
    attributes::{ChannelImplementation, ChannelKind, ChannelMode, ChannelType},
    channel_metrics::{
        ChannelMetricsRegistry, ChannelReceiverMetricSets, ChannelReceiverMetrics,
        ChannelReceiverStateMetrics, ChannelSenderFailureMetrics, ChannelSenderMetricSets,
        ChannelSenderMetrics, LocalChannelQueueDepth, PdataChannelReceiverMetricSets,
        PdataChannelSenderMetricSets, SharedChannelQueueDepth,
    },
    config::{ExporterConfig, ExtensionConfig, ProcessorConfig, ReceiverConfig},
    control::{AckMsg, CallData, NackMsg},
    effect_handler::SourceTagging,
    entity_context::{NodeTelemetryGuard, NodeTelemetryHandle, with_node_telemetry_handle},
    error::{Error, TypedError},
    exporter::ExporterWrapper,
    extension::ExtensionBundle,
    local::message::{LocalReceiver, LocalSender},
    message::{Receiver, Sender},
    node::{Node, NodeDefs, NodeId, NodeName, NodeType},
    processor::{ProcessorWrapper, validate_local_wakeup_requirements},
    receiver::ReceiverWrapper,
    runtime_pipeline::{PipeNode, RuntimePipeline},
    shared::message::{SharedReceiver, SharedSender},
};
use async_trait::async_trait;
pub use channel_metrics::RequestOutcome;
use context::ExtensionContext;
use context::NodeNameIndex;
use context::PipelineContext;
pub use linkme::distributed_slice;
use otel_arrow_dfe_config::MetricLevel;
use otel_arrow_dfe_config::SignalType;
use otel_arrow_dfe_config::{
    PipelineGroupId, PipelineId, PortName,
    engine::INTERNAL_TELEMETRY_RECEIVER_URN,
    node::NodeUserConfig,
    pipeline::{DispatchPolicy, PipelineConfig},
    policy::{
        ChannelCapacityPolicy, RateLimiterDeclarationScope, RateLimiterPolicy, TelemetryPolicy,
    },
};
use otel_arrow_dfe_telemetry::InternalTelemetrySettings;
use otel_arrow_dfe_telemetry::{otel_debug, otel_debug_span, otel_info, otel_warn};
use std::borrow::Cow;
use std::fmt::Debug;
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::{
    collections::{BTreeMap, HashMap, HashSet},
    sync::OnceLock,
};

pub mod admission;
pub mod capability;
#[doc(hidden)]
pub mod clock;
pub mod context_declaration;
pub mod error;
pub mod exporter;
pub mod extension;
mod extension_lifecycle;
mod extension_monitor;
mod forced_shutdown;
pub mod inventory;
pub use otel_arrow_dfe_engine_macros::component_inventory;
pub mod message;
pub mod processor;
pub mod receiver;
pub mod retained_work;
pub mod runtime_services;

mod attributes;
mod channel_metrics;
mod channel_mode;
mod completion_emission_metrics;
pub mod config;
pub mod context;
pub mod control;
mod control_plane_metrics;
pub mod effect_handler;
pub mod engine_metrics;
pub mod entity_context;
pub mod flow_metrics;
pub(crate) mod indexed_min_heap;
pub mod listener_group;
pub mod local;
pub mod memory_limiter;
pub mod node;
mod node_local_scheduler;
pub mod output_router;
pub mod pipeline_ctrl;
mod pipeline_metrics;
pub mod process_duration;
mod route_admission;
pub mod runtime_pipeline;
pub mod shared;
pub mod state_dir;
pub mod terminal_state;
pub mod testing;
pub mod topic;
pub mod topology;
pub mod wiring_contract;
pub use node_local_scheduler::{WakeupError, WakeupSetOutcome};
pub use processor::{LocalWakeupRequirements, ProcessorRuntimeRequirements};
pub use route_admission::RouteAdmission;

fn resolve_admission_binding(
    node_config: &NodeUserConfig,
    policies: &BTreeMap<String, RateLimiterPolicy>,
    declaration_scope: Option<RateLimiterDeclarationScope>,
) -> Result<AdmissionBinder, String> {
    match node_config.rate_limiters.as_deref() {
        Some([]) => Ok(AdmissionBinder::none()),
        Some([limiter_name]) => {
            let policy = policies.get(limiter_name).copied().ok_or_else(|| {
                format!("rate limiter binding '{limiter_name}' does not name an effective limiter")
            })?;
            Ok(AdmissionBinder::configured_at_scope(
                limiter_name.clone(),
                declaration_scope,
                policy,
            ))
        }
        Some(limiter_names) => Err(format!(
            "V1 supports at most one rate limiter binding per node; found {}",
            limiter_names.len()
        )),
        None => Ok(AdmissionBinder::none()),
    }
}

/// Trait for factory types that expose a name.
///
/// This trait is used to define a common interface for different types of factories
/// that create instances of receivers, processors, or exporters.
pub trait NamedFactory {
    /// Returns the name of the node factory.
    fn name(&self) -> &'static str;
}

/// A factory for creating receivers.
pub struct ReceiverFactory<PData> {
    /// The name of the receiver.
    pub name: &'static str,
    /// A function that creates a new receiver instance.
    ///
    /// `capabilities` is a per-node, one-shot view of the extension capabilities
    /// bound to this receiver in the pipeline configuration. Factories that
    /// don't depend on any extension can ignore the parameter.
    pub create: fn(
        pipeline_ctx: PipelineContext,
        node: NodeId,
        node_config: Arc<NodeUserConfig>,
        receiver_config: &ReceiverConfig,
        capabilities: &capability::registry::Capabilities,
    ) -> Result<ReceiverWrapper<PData>, otel_arrow_dfe_config::error::Error>,
    /// Optional context declarations derived from the node configuration.
    pub context_declarations: Option<context_declaration::ContextDeclarationProvider>,
    /// Optional wiring constraints enforced during pipeline build.
    pub wiring_contract: wiring_contract::WiringContract,
    /// Validates the node-specific config statically, without creating the component.
    ///
    /// Use [`otel_arrow_dfe_config::validation::validate_typed_config`] for components with a
    /// typed `Config` struct, or [`otel_arrow_dfe_config::validation::no_config`] for components
    /// that accept no user configuration.
    pub validate_config:
        fn(config: &serde_json::Value) -> Result<(), otel_arrow_dfe_config::error::Error>,
}

// Note: We don't use `#[derive(Clone)]` here to avoid forcing the `PData` type to implement `Clone`.
impl<PData> Clone for ReceiverFactory<PData> {
    fn clone(&self) -> Self {
        ReceiverFactory {
            name: self.name,
            create: self.create,
            context_declarations: self.context_declarations,
            wiring_contract: self.wiring_contract,
            validate_config: self.validate_config,
        }
    }
}

impl<PData> NamedFactory for ReceiverFactory<PData> {
    fn name(&self) -> &'static str {
        self.name
    }
}

/// A factory for creating processors.
pub struct ProcessorFactory<PData> {
    /// The name of the processor.
    pub name: &'static str,
    /// A function that creates a new processor instance.
    ///
    /// `capabilities` is a per-node, one-shot view of the extension capabilities
    /// bound to this processor in the pipeline configuration. Factories that
    /// don't depend on any extension can ignore the parameter.
    pub create: fn(
        pipeline: PipelineContext,
        node: NodeId,
        node_config: Arc<NodeUserConfig>,
        processor_config: &ProcessorConfig,
        capabilities: &capability::registry::Capabilities,
    ) -> Result<ProcessorWrapper<PData>, otel_arrow_dfe_config::error::Error>,
    /// Optional context declarations derived from the node configuration.
    pub context_declarations: Option<context_declaration::ContextDeclarationProvider>,
    /// Optional wiring constraints enforced during pipeline build.
    pub wiring_contract: wiring_contract::WiringContract,
    /// Validates the node-specific config statically, without creating the component.
    ///
    /// Use [`otel_arrow_dfe_config::validation::validate_typed_config`] for components with a
    /// typed `Config` struct, or [`otel_arrow_dfe_config::validation::no_config`] for components
    /// that accept no user configuration.
    pub validate_config:
        fn(config: &serde_json::Value) -> Result<(), otel_arrow_dfe_config::error::Error>,
}

// Note: We don't use `#[derive(Clone)]` here to avoid forcing the `PData` type to implement `Clone`.
impl<PData> Clone for ProcessorFactory<PData> {
    fn clone(&self) -> Self {
        ProcessorFactory {
            name: self.name,
            create: self.create,
            context_declarations: self.context_declarations,
            wiring_contract: self.wiring_contract,
            validate_config: self.validate_config,
        }
    }
}

impl<PData> NamedFactory for ProcessorFactory<PData> {
    fn name(&self) -> &'static str {
        self.name
    }
}

/// A factory for creating exporter.
pub struct ExporterFactory<PData> {
    /// The name of the receiver.
    pub name: &'static str,
    /// A function that creates a new exporter instance.
    ///
    /// `capabilities` is a per-node, one-shot view of the extension capabilities
    /// bound to this exporter in the pipeline configuration. Factories that
    /// don't depend on any extension can ignore the parameter.
    pub create: fn(
        pipeline: PipelineContext,
        node: NodeId,
        node_config: Arc<NodeUserConfig>,
        exporter_config: &ExporterConfig,
        capabilities: &capability::registry::Capabilities,
    ) -> Result<ExporterWrapper<PData>, otel_arrow_dfe_config::error::Error>,
    /// Optional context declarations derived from the node configuration.
    pub context_declarations: Option<context_declaration::ContextDeclarationProvider>,
    /// Optional wiring constraints enforced during pipeline build.
    pub wiring_contract: wiring_contract::WiringContract,
    /// Validates the node-specific config statically, without creating the component.
    ///
    /// Use [`otel_arrow_dfe_config::validation::validate_typed_config`] for components with a
    /// typed `Config` struct, or [`otel_arrow_dfe_config::validation::no_config`] for components
    /// that accept no user configuration.
    pub validate_config:
        fn(config: &serde_json::Value) -> Result<(), otel_arrow_dfe_config::error::Error>,
}

// Note: We don't use `#[derive(Clone)]` here to avoid forcing the `PData` type to implement `Clone`.
impl<PData> Clone for ExporterFactory<PData> {
    fn clone(&self) -> Self {
        ExporterFactory {
            name: self.name,
            create: self.create,
            context_declarations: self.context_declarations,
            wiring_contract: self.wiring_contract,
            validate_config: self.validate_config,
        }
    }
}

impl<PData> NamedFactory for ExporterFactory<PData> {
    fn name(&self) -> &'static str {
        self.name
    }
}

/// A factory for creating extensions.
///
/// Extension factories are NOT generic over PData -- extensions never process
/// pipeline data. This makes them fully decoupled from the data-plane type.
#[derive(Clone)]
pub struct ExtensionFactory {
    /// The name of the extension.
    pub name: &'static str,
    /// A short, human-readable description of the extension.
    pub description: &'static str,
    /// URL to the extension's documentation.
    pub documentation_url: &'static str,
    /// The capabilities this extension provides.
    ///
    /// `Some(caps)` for active or passive extensions (caps lists are
    /// non-empty by macro construction). `None` marks a Background
    /// extension -- engine-driven event loop with no capabilities
    /// exposed to nodes; `register_into` skips capability registration.
    pub capabilities: Option<capability::ExtensionCapabilities>,
    /// A function that creates a new extension instance.
    pub create: fn(
        ext_ctx: &ExtensionContext,
        name: otel_arrow_dfe_config::ExtensionId,
        ext_config: Arc<otel_arrow_dfe_config::extension::ExtensionUserConfig>,
        extension_config: &ExtensionConfig,
    ) -> Result<ExtensionBundle, otel_arrow_dfe_config::error::Error>,
    /// Validates the node-specific config statically, without creating the component.
    pub validate_config:
        fn(config: &serde_json::Value) -> Result<(), otel_arrow_dfe_config::error::Error>,
}

impl NamedFactory for ExtensionFactory {
    fn name(&self) -> &'static str {
        self.name
    }
}

/// Returns a map of factory names to factory instances.
pub fn get_factory_map<T>(
    factory_map: &'static OnceLock<HashMap<&'static str, T>>,
    factory_slice: &'static [T],
) -> &'static HashMap<&'static str, T>
where
    T: NamedFactory + Clone,
{
    factory_map.get_or_init(|| {
        factory_slice
            .iter()
            .map(|f| (f.name(), f.clone()))
            .collect::<HashMap<&'static str, T>>()
    })
}

bitflags::bitflags! {
/// A 16-bit flags struct intended to store various intents describing
/// callers in a pipeline, e.g., detail about whether Ack and/or
/// Nack should be delivered.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Interests: u16 {
    /// Acks interest
    const ACKS   = 1 << 0;

    /// Nacks interest
    const NACKS  = 1 << 1;

    /// Acks or Nacks interest subset
    const ACKS_OR_NACKS = Self::ACKS.bits() | Self::NACKS.bits();

    /// Return data
    const RETURN_DATA = 1 << 2;

    /// Collect node completion duration through terminal Ack/Nack unwinding.
    const NODE_COMPLETION_DURATION = 1 << 3;

    /// Instrument the node input metric family.
    const NODE_INPUT_METRICS = 1 << 4;

    /// Instrument the node output metric family.
    const NODE_OUTPUT_METRICS = 1 << 5;

    /// Source-tagging requested. A frame with no other interests may be inserted.
    const SOURCE_TAGGING = 1 << 6;

    /// Collect item counts for telemetry associated with this node. This feeds
    /// engine-owned node input/output metrics and node-implemented metrics that
    /// report item counts. Opt-in because counting OTLP items is expensive.
    const NODE_ITEM_COUNTS = 1 << 8;

    /// Collect size measurements for telemetry associated with this node. This
    /// feeds engine-owned logical PData size and node-implemented boundary
    /// payload size metrics, each using the semantics of its metric contract.
    const NODE_SIZE = 1 << 9;

    /// Collect node-implemented local duration measurements. Engine-owned node
    /// and flow timing is controlled separately by the pipeline metric
    /// interests and `NODE_COMPLETION_DURATION`.
    const NODE_LOCAL_DURATION = 1 << 7;

    /// Node metrics include either the input or output metric family.
    const NODE_METRICS = Self::NODE_INPUT_METRICS.bits() | Self::NODE_OUTPUT_METRICS.bits();
}
}

impl Interests {
    /// Derive Interests from MetricLevel.
    ///
    /// None:     empty()
    /// Basic:    empty() with only channel metrics, no use of Context
    /// Normal:   NODE_INPUT_METRICS | NODE_OUTPUT_METRICS
    /// Detailed: NODE_INPUT_METRICS | NODE_OUTPUT_METRICS
    ///           | NODE_COMPLETION_DURATION | NODE_ITEM_COUNTS
    ///           | NODE_SIZE | NODE_LOCAL_DURATION
    #[must_use]
    pub fn from_metric_level(level: MetricLevel) -> Self {
        match level {
            MetricLevel::None | MetricLevel::Basic => Self::empty(),
            MetricLevel::Normal => Self::NODE_METRICS,
            MetricLevel::Detailed => {
                Self::NODE_METRICS
                    | Self::NODE_COMPLETION_DURATION
                    | Self::NODE_ITEM_COUNTS
                    | Self::NODE_SIZE
                    | Self::NODE_LOCAL_DURATION
            }
        }
    }

    /// Derives effective interests for one node from the pipeline metric level
    /// and the node's optional telemetry policy.
    #[must_use]
    pub fn for_node(level: MetricLevel, node_config: &NodeUserConfig) -> Self {
        let mut interests = Self::from_metric_level(level);
        if let Some(telemetry) = node_config
            .policies
            .as_ref()
            .and_then(|policies| policies.telemetry.as_ref())
        {
            if telemetry.messages {
                interests |= Self::NODE_METRICS;
            }
            if telemetry.completion_duration {
                interests |= Self::NODE_COMPLETION_DURATION;
            }
            if telemetry.item_counts {
                interests |= Self::NODE_ITEM_COUNTS;
            }
            if telemetry.size {
                interests |= Self::NODE_SIZE;
            }
            if telemetry.duration {
                interests |= Self::NODE_LOCAL_DURATION;
            }
        }
        interests
    }
}

/// Trait for context-stack unwinding during ack/nack delivery.
pub trait Unwindable {
    /// Returns true if the context stack has any frames.
    ///
    /// TODO: there are cases where having frames does not necessarily
    /// mean there are interests. This can be refined.
    fn has_frames(&self) -> bool;

    /// Remove and return the top frame.
    fn pop_frame(&mut self) -> Option<control::Frame>;

    /// Signal type carried by the payload. Returns `None` when unknown or not
    /// applicable. Implementations must keep this metadata available after
    /// [`Unwindable::drop_payload`] so it remains readable during unwinding.
    fn signal(&self) -> Option<SignalType>;

    /// Drop the retained payload unless RETURN_DATA is set.
    fn drop_payload(&mut self);
}

impl Unwindable for () {
    fn has_frames(&self) -> bool {
        false
    }
    fn pop_frame(&mut self) -> Option<control::Frame> {
        None
    }
    fn signal(&self) -> Option<SignalType> {
        None
    }
    fn drop_payload(&mut self) {}
}

impl Unwindable for String {
    fn has_frames(&self) -> bool {
        false
    }
    fn pop_frame(&mut self) -> Option<control::Frame> {
        None
    }
    fn signal(&self) -> Option<SignalType> {
        None
    }
    fn drop_payload(&mut self) {}
}

/// Trait for setting entry information in the Context, for PData consumers.
pub trait ReceivedAtNode {
    /// Called automatically when a PData message is received from the input channel.
    fn received_at_node(&mut self, node_id: usize, node_interests: Interests);
}

// No-op implementations for types used as PData in tests.
impl ReceivedAtNode for () {
    fn received_at_node(&mut self, _node_id: usize, _node_interests: Interests) {}
}
impl ReceivedAtNode for String {
    fn received_at_node(&mut self, _node_id: usize, _node_interests: Interests) {}
}
// `FlowMetricHook` is a bound on the `PData` generic of `ProcessorWrapper::start*`,
// `RuntimePipeline`, and the controller. Test code uses `()` and `String` as stand-in PData
// types (e.g. `Controller<()>`); these blanket no-op impls let those tests compile without
// requiring every test PData type to define hook behavior. Real PData types (e.g. `OtapPdata`)
// override these methods to drive flow_metric signal counting and compute-duration accumulation.
impl processor::FlowMetricHook for () {}
impl processor::FlowMetricHook for String {}

/// Trait for setting exit information in the Context, for PData consumers.
pub trait StampOutputPort {
    /// Called automatically when a PData message is sent on an output channel.
    fn stamp_output_port_index(&mut self, node_id: usize, index: u16);
}

impl StampOutputPort for () {
    fn stamp_output_port_index(&mut self, _node_id: usize, _index: u16) {}
}

impl StampOutputPort for String {
    fn stamp_output_port_index(&mut self, _node_id: usize, _index: u16) {}
}

/// Trait for forward-path flow_metric compute accumulation on PData.
///
/// At most one flow_metric range can be active on a given message at a
/// time (non-overlapping ranges).
pub trait FlowMetricAccumulation {
    /// Initialise a fresh flow_metric accumulator (set to 0).
    /// Called at the start node.
    fn start_flow_metric(&mut self);

    /// Add `ns` nanoseconds to the active flow_metric accumulator, if any.
    fn add_flow_compute(&mut self, ns: u64);

    /// Remove and return the accumulated total.
    /// Returns `None` if no accumulator was active.
    fn take_flow_compute(&mut self) -> Option<u64>;
}

/// Effect handler extensions for producers specific to data type.
#[async_trait(?Send)]
pub trait ProducerEffectHandlerExtension<PData> {
    /// Subscribe to a set of interests.
    fn subscribe_to(&self, int: Interests, ctx: CallData, data: &mut PData);
}

/// Effect handler extensions for consumers specific to data type.
#[async_trait(?Send)]
pub trait ConsumerEffectHandlerExtension<PData> {
    /// Triggers the next step of work (if any) in Ack processing.
    async fn notify_ack(&self, ack: AckMsg<PData>) -> Result<(), Error>;

    /// Triggers the next step of work (if any) in Nack processing.
    async fn notify_nack(&self, nack: NackMsg<PData>) -> Result<(), Error>;
}

/// Implementation-detail module re-exporting the internal
/// [`AckNackRouting`] trait.
///
/// **Do not use directly.** Prefer
/// [`ConsumerEffectHandlerExtension::notify_ack`] /
/// [`ConsumerEffectHandlerExtension::notify_nack`] which stamp timing
/// information required for correct duration metrics.
#[doc(hidden)]
pub mod _private {
    use super::*;

    /// Internal routing trait for ack/nack messages.
    ///
    /// Callers should use [`ConsumerEffectHandlerExtension::notify_ack`] and
    /// [`ConsumerEffectHandlerExtension::notify_nack`] instead of calling these
    /// methods directly. Those wrappers stamp timing information required for
    /// correct duration metrics before forwarding to `route_ack`/`route_nack`.
    #[async_trait(?Send)]
    pub trait AckNackRouting<PData> {
        /// Routes an ack message to the runtime control manager.
        async fn route_ack(&self, ack: AckMsg<PData>) -> Result<(), Error>;

        /// Routes a nack message to the runtime control manager.
        async fn route_nack(&self, nack: NackMsg<PData>) -> Result<(), Error>;
    }
}

/// Effect handler extension for adding message source
#[async_trait(?Send)]
pub trait MessageSourceLocalEffectHandlerExtension<PData> {
    /// Send data after tagging with the source node.
    async fn send_message_with_source_node(&self, data: PData) -> Result<(), TypedError<PData>>;
    /// Try to send data after tagging with the source node.
    fn try_send_message_with_source_node(&self, data: PData) -> Result<(), TypedError<PData>>;
    /// Try to admit data to the default output without awaiting.
    ///
    /// This preserves non-channel errors (for example, a missing default port)
    /// while classifying `Full` and `Closed` as explicit route rejections.
    fn try_admit_message_with_source_node(
        &self,
        data: PData,
    ) -> Result<RouteAdmission<PData>, TypedError<PData>> {
        route_admission::classify_route_admission(self.try_send_message_with_source_node(data))
    }
    /// Send data to a specific port after tagging with the source node.
    async fn send_message_with_source_node_to<P>(
        &self,
        port: P,
        data: PData,
    ) -> Result<(), TypedError<PData>>
    where
        P: Into<PortName> + Send + 'static;
    /// Try to send data to a specific port after tagging with the source node.
    fn try_send_message_with_source_node_to<P>(
        &self,
        port: P,
        data: PData,
    ) -> Result<(), TypedError<PData>>
    where
        P: Into<PortName> + Send + 'static;
    /// Try to admit data to a specific selected output without awaiting.
    ///
    /// This preserves non-channel errors (for example, an unknown port) while
    /// classifying `Full` and `Closed` as explicit route rejections.
    fn try_admit_message_with_source_node_to<P>(
        &self,
        port: P,
        data: PData,
    ) -> Result<RouteAdmission<PData>, TypedError<PData>>
    where
        P: Into<PortName> + Send + 'static,
    {
        route_admission::classify_route_admission(
            self.try_send_message_with_source_node_to(port, data),
        )
    }
}

/// Send-friendly variant for use in `Send` contexts (e.g., `tokio::spawn`).
#[async_trait]
pub trait MessageSourceSharedEffectHandlerExtension<PData: Send + 'static> {
    /// Send data after tagging with the source node.
    async fn send_message_with_source_node(&self, data: PData) -> Result<(), TypedError<PData>>;
    /// Try to send data after tagging with the source node.
    fn try_send_message_with_source_node(&self, data: PData) -> Result<(), TypedError<PData>>;
    /// Try to admit data to the default output without awaiting.
    ///
    /// This preserves non-channel errors (for example, a missing default port)
    /// while classifying `Full` and `Closed` as explicit route rejections.
    fn try_admit_message_with_source_node(
        &self,
        data: PData,
    ) -> Result<RouteAdmission<PData>, TypedError<PData>> {
        route_admission::classify_route_admission(self.try_send_message_with_source_node(data))
    }
    /// Send data to a specific port after tagging with the source node.
    async fn send_message_with_source_node_to<P>(
        &self,
        port: P,
        data: PData,
    ) -> Result<(), TypedError<PData>>
    where
        P: Into<PortName> + Send + 'static;
    /// Try to send data to a specific port after tagging with the source node.
    fn try_send_message_with_source_node_to<P>(
        &self,
        port: P,
        data: PData,
    ) -> Result<(), TypedError<PData>>
    where
        P: Into<PortName> + Send + 'static;
    /// Try to admit data to a specific selected output without awaiting.
    ///
    /// This preserves non-channel errors (for example, an unknown port) while
    /// classifying `Full` and `Closed` as explicit route rejections.
    fn try_admit_message_with_source_node_to<P>(
        &self,
        port: P,
        data: PData,
    ) -> Result<RouteAdmission<PData>, TypedError<PData>>
    where
        P: Into<PortName> + Send + 'static,
    {
        route_admission::classify_route_admission(
            self.try_send_message_with_source_node_to(port, data),
        )
    }
}

/// Builds a pipeline factory for initialization.
///
/// This function is used as a placeholder when declaring a pipeline factory with the
/// `#[factory_registry]` attribute macro. The macro will replace this placeholder with
/// proper lazy initialization using `LazyLock`.
///
/// # Example
/// ```rust,ignore
/// #[factory_registry(MyData)]
/// static FACTORY_REGISTRY: PipelineFactory<MyData> = build_factory();
/// ```
#[must_use]
pub const fn build_factory<PData: 'static + Clone>() -> PipelineFactory<PData> {
    // This function should never actually be called since the macro replaces it entirely.
    // If it is called, that indicates a bug in the macro system.
    panic!(
        "build_registry() should never be called - it's replaced by the #[factory_registry] macro"
    )
}

/// A pipeline factory.
///
/// This factory contains a registry of all the micro-factories for receivers, processors, and
/// exporters, as well as the logic for creating pipelines based on a given configuration.
pub struct PipelineFactory<PData: 'static + Clone> {
    receiver_factory_map: OnceLock<HashMap<&'static str, ReceiverFactory<PData>>>,
    processor_factory_map: OnceLock<HashMap<&'static str, ProcessorFactory<PData>>>,
    exporter_factory_map: OnceLock<HashMap<&'static str, ExporterFactory<PData>>>,
    extension_factory_map: OnceLock<HashMap<&'static str, ExtensionFactory>>,
    receiver_factories: &'static [ReceiverFactory<PData>],
    processor_factories: &'static [ProcessorFactory<PData>],
    exporter_factories: &'static [ExporterFactory<PData>],
    extension_factories: &'static [ExtensionFactory],
}

impl<PData: 'static + Clone + Debug> PipelineFactory<PData> {
    /// Creates a new factory registry with the given factory slices.
    #[must_use]
    pub const fn new(
        receiver_factories: &'static [ReceiverFactory<PData>],
        processor_factories: &'static [ProcessorFactory<PData>],
        exporter_factories: &'static [ExporterFactory<PData>],
        extension_factories: &'static [ExtensionFactory],
    ) -> Self {
        Self {
            receiver_factory_map: OnceLock::new(),
            processor_factory_map: OnceLock::new(),
            exporter_factory_map: OnceLock::new(),
            extension_factory_map: OnceLock::new(),
            receiver_factories,
            processor_factories,
            exporter_factories,
            extension_factories,
        }
    }

    /// Gets the receiver factory map, initializing it if necessary.
    pub fn get_receiver_factory_map(&self) -> &HashMap<&'static str, ReceiverFactory<PData>> {
        self.receiver_factory_map.get_or_init(|| {
            self.receiver_factories
                .iter()
                .map(|f| (f.name(), f.clone()))
                .collect::<HashMap<&'static str, ReceiverFactory<PData>>>()
        })
    }

    /// Gets the processor factory map, initializing it if necessary.
    pub fn get_processor_factory_map(&self) -> &HashMap<&'static str, ProcessorFactory<PData>> {
        self.processor_factory_map.get_or_init(|| {
            self.processor_factories
                .iter()
                .map(|f| (f.name(), f.clone()))
                .collect::<HashMap<&'static str, ProcessorFactory<PData>>>()
        })
    }

    /// Gets the exporter factory map, initializing it if necessary.
    pub fn get_exporter_factory_map(&self) -> &HashMap<&'static str, ExporterFactory<PData>> {
        self.exporter_factory_map.get_or_init(|| {
            self.exporter_factories
                .iter()
                .map(|f| (f.name(), f.clone()))
                .collect::<HashMap<&'static str, ExporterFactory<PData>>>()
        })
    }

    /// Gets the extension factory map, initializing it if necessary.
    pub fn get_extension_factory_map(&self) -> &HashMap<&'static str, ExtensionFactory> {
        self.extension_factory_map.get_or_init(|| {
            self.extension_factories
                .iter()
                .map(|f| (f.name(), f.clone()))
                .collect::<HashMap<&'static str, ExtensionFactory>>()
        })
    }

    /// Builds a runtime pipeline from the given pipeline configuration.
    ///
    /// Main phases:
    /// 1) Create runtime nodes and register telemetry.
    /// 2) Plan hyper edge wiring: resolve destinations, pick channel type (shared/local,
    ///    MPSC/MPMC), create channel endpoints, and register channel metrics.
    /// 3) Apply wiring: attach senders to source ports and receivers to destination nodes,
    ///    then publish collected channel metrics on the pipeline.
    ///
    /// [config] -> [nodes] -> [hyper-edges] -> [wiring plan] -> [pipeline]
    ///
    /// The `internal_telemetry` settings are injected into any receiver with the
    /// `INTERNAL_TELEMETRY_RECEIVER_URN` plugin URN, enabling it to consume logs
    /// from the Internal Telemetry System.
    pub fn build(
        self: &PipelineFactory<PData>,
        mut pipeline_ctx: PipelineContext,
        mut config: PipelineConfig,
        channel_capacity_policy: ChannelCapacityPolicy,
        telemetry_policy: TelemetryPolicy,
        rate_limiter_policies: BTreeMap<String, RateLimiterPolicy>,
        rate_limiter_scope: Option<RateLimiterDeclarationScope>,
        internal_telemetry: Option<InternalTelemetrySettings>,
    ) -> Result<RuntimePipeline<PData>, Error>
    where
        PData: Unwindable,
    {
        let mut receivers = Vec::new();
        let mut processors = Vec::new();
        let mut exporters = Vec::new();
        let mut build_state = BuildState::new();

        let pipeline_group_id = pipeline_ctx.pipeline_group_id();
        let pipeline_id = pipeline_ctx.pipeline_id();
        let core_id = pipeline_ctx.core_id();

        let span = otel_debug_span!(
            "pipeline.build",
            pipeline_group_id = pipeline_group_id.as_ref(),
            pipeline_id = pipeline_id.as_ref(),
            core_id = core_id
        );
        let _enter = span.enter();

        // Remove unconnected nodes before building the pipeline.
        // Nodes that have no incoming or outgoing connections are filtered out
        // with a warning instead of causing a startup failure.
        let unconnected = config.remove_unconnected_nodes();
        for (node_id, node_kind) in &unconnected {
            let kind: Cow<'static, str> = (*node_kind).into();
            otel_info!(
                "pipeline.build.unconnected_node.removed",
                message = "Removed unconnected node from pipeline.",
                pipeline_group_id = pipeline_group_id.as_ref(),
                pipeline_id = pipeline_id.as_ref(),
                core_id = core_id,
                node_id = node_id.as_ref(),
                node_kind = kind.as_ref(),
            );
        }
        if !unconnected.is_empty() {
            otel_warn!(
                "pipeline.build.unconnected_nodes",
                message = "Some pipeline nodes were removed because they had no active incoming or outgoing edges. These nodes will not participate in data processing. Check pipeline configuration if this is unintentional.",
                pipeline_group_id = pipeline_group_id.as_ref(),
                pipeline_id = pipeline_id.as_ref(),
                core_id = core_id,
                removed_count = unconnected.len(),
            );
        }

        // If every node was removed, the pipeline config is broken -- fail early.
        if config.nodes().is_empty() {
            return Err(Error::EmptyPipeline);
        }

        self.validate_connection_wiring_contracts(&config)?;

        let basic_runtime_metrics_enabled = telemetry_policy.runtime_metrics >= MetricLevel::Basic;

        // First pass: allocate all node IDs from the build_state.
        let mut receiver_count = 0usize;
        let mut processor_count = 0usize;
        let mut exporter_count = 0usize;
        let mut node_ids: HashMap<NodeName, NodeId> = HashMap::new();

        for (name, node_config) in config.node_iter() {
            let (node_type, pipe_node) = match node_config.kind() {
                otel_arrow_dfe_config::node::NodeKind::Receiver => {
                    let pn = PipeNode::new(receiver_count);
                    receiver_count += 1;
                    (NodeType::Receiver, pn)
                }
                otel_arrow_dfe_config::node::NodeKind::Processor => {
                    let pn = PipeNode::new(processor_count);
                    processor_count += 1;
                    (NodeType::Processor, pn)
                }
                otel_arrow_dfe_config::node::NodeKind::Exporter => {
                    let pn = PipeNode::new(exporter_count);
                    exporter_count += 1;
                    (NodeType::Exporter, pn)
                }
            };
            let node_id = build_state.next_node_id(name.clone(), node_type, pipe_node)?;
            let _ = node_ids.insert(name.clone(), node_id);
        }

        let node_names: NodeNameIndex = Arc::new(
            node_ids
                .iter()
                .map(|(name, id)| (name.clone(), id.clone()))
                .collect(),
        );
        pipeline_ctx.set_node_names(node_names);

        // -- Extension instantiation + capability registry build -------------
        //
        // Run before node-wrapper creation so resolve_bindings can validate
        // each node's `node_config.capabilities` against the populated
        // registry, and so factories that call `require_local::<C>()` /
        // `require_shared::<C>()` see a fully-populated `Capabilities`.
        // Capabilities are resolved EAGERLY at build time -- node create()
        // bodies run inside this same `build` call, so extension `start()`
        // side effects (which happen later, in `run_forever`) cannot be
        // observed by capability construction.
        let known_extensions: HashSet<otel_arrow_dfe_config::ExtensionId> =
            config.extensions().keys().cloned().collect();
        let mut capability_registry = capability::registry::CapabilityRegistry::new();
        // Each entry tracks (extension id, bundle, is_background). The
        // `is_background` flag is captured here while we still have the
        // factory in hand -- Background extensions register zero
        // capabilities (`factory.capabilities == None`), and the
        // post-build pruning step uses this flag to keep them
        // unconditionally (they are engine-driven and do not need a
        // node binding to be useful).
        let mut extension_bundles: Vec<(
            otel_arrow_dfe_config::ExtensionId,
            ExtensionBundle,
            bool,
            extension::wrapper::ExtensionEntityKeys,
        )> = Vec::new();
        for (ext_id, ext_user_config) in config.extension_iter() {
            let raw_urn = ext_user_config.r#type.as_str();
            let factory = self
                .get_extension_factory_map()
                .get(raw_urn)
                .ok_or_else(|| Error::UnknownExtension {
                    plugin_urn: raw_urn.to_string(),
                })?;
            let runtime_config = ExtensionConfig::with_control_channel_capacity(
                ext_id.clone(),
                channel_capacity_policy.control.node,
            );
            let ext_ctx = pipeline_ctx.extension_context();
            let bundle = (factory.create)(
                &ext_ctx,
                ext_id.clone(),
                ext_user_config.clone(),
                &runtime_config,
            )
            .map_err(|e| Error::ConfigError(Box::new(e)))?;
            let mut bundle = bundle;
            let entity_keys = bundle.wire_telemetry(
                ext_id.clone(),
                &ext_ctx,
                &mut build_state.channel_metrics,
                basic_runtime_metrics_enabled,
            );
            bundle
                .register_into(factory.capabilities.as_ref(), &mut capability_registry)
                .map_err(|e| Error::CapabilityRegistrationFailed {
                    extension: ext_id.clone(),
                    message: format!("{e}"),
                })?;
            let is_background = factory.capabilities.is_none();
            extension_bundles.push((ext_id.clone(), bundle, is_background, entity_keys));
        }

        // Resolve each node's bindings against the populated registry. A
        // single shared `ConsumedTracker` records consumption across all
        // nodes so the engine can prune unused extension variants after
        // the build phase.
        let mut consumed_tracker = capability::registry::ConsumedTracker::new();
        let mut per_node_capabilities: HashMap<NodeName, capability::registry::Capabilities> =
            HashMap::new();
        for (name, node_config) in config.node_iter() {
            let caps = capability::registry::resolve_bindings(
                &node_config.capabilities,
                &capability_registry,
                &known_extensions,
                &mut consumed_tracker,
            )
            .map_err(|e| Error::CapabilityResolutionFailed {
                node: name.clone(),
                message: format!("{e}"),
            })?;
            let _ = per_node_capabilities.insert(name.clone(), caps);
        }

        // Second pass: create runtime nodes.  Node IDs were pre-assigned above,
        // so we look them up from `node_ids` instead of calling `next_node_id`.
        // ToDo(LQ): Collect all errors instead of failing fast to provide better feedback.
        let empty_capabilities = capability::registry::Capabilities::empty();
        let mut admission_bound_nodes = Vec::new();
        let mut admission_explicitly_opted_out_nodes = Vec::new();
        for (name, node_config) in config.node_iter() {
            let node_kind = node_config.kind();
            let node_id = node_ids.get(name).expect("allocated in first pass").clone();
            let mut base_ctx = pipeline_ctx.with_node_context(
                name.clone(),
                node_config.r#type.clone(),
                node_kind,
                node_config.identity_attributes(),
            );
            base_ctx.set_node_interests(Interests::for_node(
                telemetry_policy.runtime_metrics,
                node_config,
            ));
            base_ctx.set_node_duration_distribution(node_config.duration_distribution());
            let invalid_binding = |error: String| {
                Error::ConfigError(Box::new(
                    otel_arrow_dfe_config::error::Error::InvalidUserConfig {
                        error: format!(
                            "Component `{}` in pipeline_group={} pipeline={} node={}: {error}",
                            node_config.r#type.as_ref(),
                            pipeline_ctx.pipeline_group_id().as_ref(),
                            pipeline_ctx.pipeline_id().as_ref(),
                            name.as_ref(),
                        ),
                    },
                ))
            };
            let admission = resolve_admission_binding(
                node_config,
                &rate_limiter_policies,
                rate_limiter_scope.clone(),
            )
            .map_err(invalid_binding)?;
            base_ctx.set_admission(admission);
            // Per-node Capabilities resolved in the build-time pass above.
            // Falls back to empty for nodes that declared no bindings (the
            // resolver populates the map for every node, including those
            // with no `capabilities` block, so this fallback is defensive).
            let node_capabilities = per_node_capabilities
                .get(name)
                .unwrap_or(&empty_capabilities);

            match node_kind {
                otel_arrow_dfe_config::node::NodeKind::Receiver => {
                    // Inject internal telemetry settings into context if this is the ITR node.
                    // The ITR factory will extract these settings during construction.
                    if node_config.r#type.as_ref() == INTERNAL_TELEMETRY_RECEIVER_URN
                        && let Some(ref settings) = internal_telemetry
                    {
                        base_ctx.set_internal_telemetry(settings.clone());
                    }

                    let wrapper = self.build_node_wrapper(
                        &mut build_state,
                        &base_ctx,
                        NodeType::Receiver,
                        node_id.clone(),
                        basic_runtime_metrics_enabled,
                        || {
                            self.create_receiver(
                                &base_ctx,
                                node_id.clone(),
                                node_config.clone(),
                                channel_capacity_policy.control.node,
                                channel_capacity_policy.pdata,
                                node_capabilities,
                            )
                        },
                    )?;
                    receivers.push(wrapper);
                }
                otel_arrow_dfe_config::node::NodeKind::Processor => {
                    let wrapper = self.build_node_wrapper(
                        &mut build_state,
                        &base_ctx,
                        NodeType::Processor,
                        node_id.clone(),
                        basic_runtime_metrics_enabled,
                        || {
                            self.create_processor(
                                &base_ctx,
                                node_id.clone(),
                                node_config.clone(),
                                channel_capacity_policy.control.node,
                                channel_capacity_policy.pdata,
                                node_capabilities,
                            )
                        },
                    )?;
                    processors.push(wrapper);
                }
                otel_arrow_dfe_config::node::NodeKind::Exporter => {
                    let wrapper = self.build_node_wrapper(
                        &mut build_state,
                        &base_ctx,
                        NodeType::Exporter,
                        node_id.clone(),
                        basic_runtime_metrics_enabled,
                        || {
                            self.create_exporter(
                                &base_ctx,
                                node_id.clone(),
                                node_config.clone(),
                                channel_capacity_policy.control.node,
                                channel_capacity_policy.pdata,
                                node_capabilities,
                            )
                        },
                    )?;
                    exporters.push(wrapper);
                }
            }

            if base_ctx.admission().was_bound() {
                admission_bound_nodes.push(name.as_ref().to_owned());
            } else if matches!(node_config.rate_limiters.as_deref(), Some([])) {
                admission_explicitly_opted_out_nodes.push(name.as_ref().to_owned());
            }
        }

        if !admission_bound_nodes.is_empty() || !admission_explicitly_opted_out_nodes.is_empty() {
            otel_info!(
                "admission.binding.summary",
                bound_nodes = admission_bound_nodes.join(","),
                explicitly_opted_out_nodes = admission_explicitly_opted_out_nodes.join(","),
                message = "Resolved pipeline admission bindings"
            );
        }

        // -- Decide which extension variants to keep --------------------
        //
        // Three categories of extension-level decision are handled here.
        // Per-variant decisions (drop a single local or shared variant
        // because nothing consumes it while the other variant *is*
        // consumed) are made silently -- no warning, since the extension
        // as a whole is serving its purpose.
        //
        //   1. **Background extension** (`factory.capabilities == None`):
        //      always kept. Background extensions are engine-driven and
        //      register zero capabilities, so they cannot appear in any
        //      node's binding map and cannot show up in the consumed
        //      tracker. Pruning them based on consumption would silently
        //      drop their event loop, which is exactly the work they
        //      exist to do. They're spawned in `run_forever` like Active.
        //
        //   2. **Defined but unbound** (no node references this extension
        //      from `node_config.capabilities`): warn + drop the entire
        //      bundle. The author wrote an extension into the pipeline
        //      config but no node references it -- keeping it would
        //      waste the resources of an active lifecycle (or hold
        //      passive state) for nothing. The warning helps debug
        //      "why isn't my extension running?" by surfacing the
        //      missing binding.
        //
        //   3. **Bound but neither variant consumed**: warn + drop the
        //      entire bundle. At least one node declared a binding to
        //      this extension but no node's `create()` actually called
        //      `require_*` / `optional_*` for *any* of its variants.
        //      The warning surfaces node factories that declared a
        //      binding but forgot to consume it.
        //
        //   3a. **Bound and at least one variant consumed**: keep each
        //       consumed variant; silently drop the variant(s) that
        //       weren't consumed. Dropping an unused variant when the
        //       other is in use is a normal optimization (no node ever
        //       wanted that path), not an error condition.
        //
        // A bundle's two variants (local + shared) are evaluated
        // independently in 3/3a -- a SharedAsLocal-fallback bundle
        // (shared-only) only ever populates the consumed_shared set,
        // so the local check naturally fails for it (and the bundle's
        // missing local variant is dropped accordingly).
        let bound_extensions: HashSet<otel_arrow_dfe_config::ExtensionId> = config
            .node_iter()
            .flat_map(|(_, node_config)| node_config.capabilities.values().cloned())
            .collect();
        // Per-variant consumption: an extension's local (resp. shared)
        // variant is considered "in use" iff at least one of the
        // capabilities it exposes for that variant was bound by some
        // node. Tracking presence-of-consumed (rather than
        // presence-of-unconsumed) is required because an extension may
        // expose multiple capabilities of the same variant -- under the
        // unconsumed view, a single unbound capability would mask the
        // bound ones and the whole variant would be incorrectly dropped.
        let consumed_local: HashSet<otel_arrow_dfe_config::ExtensionId> =
            consumed_tracker.consumed_local();
        let consumed_shared: HashSet<otel_arrow_dfe_config::ExtensionId> =
            consumed_tracker.consumed_shared();
        let extension_wrappers: Vec<(
            extension::ExtensionWrapper,
            otel_arrow_dfe_telemetry::registry::EntityKey,
        )> = extension_bundles
            .into_iter()
            .flat_map(|(ext_id, mut bundle, is_background, entity_keys)| {
                let mut kept: Vec<(
                    extension::ExtensionWrapper,
                    otel_arrow_dfe_telemetry::registry::EntityKey,
                )> = Vec::new();

                // Category 1: Background -- always kept, no warning.
                if is_background {
                    if let Some(local) = bundle.take_local() {
                        kept.push((
                            local,
                            entity_keys
                                .local
                                .expect("wire_telemetry mints a key for every present variant"),
                        ));
                    }
                    if let Some(shared) = bundle.take_shared() {
                        kept.push((
                            shared,
                            entity_keys
                                .shared
                                .expect("wire_telemetry mints a key for every present variant"),
                        ));
                    }
                    return kept;
                }

                // Category 2: defined but no node binds to it. Warn and
                // drop the whole bundle (both variants if present).
                if !bound_extensions.contains(&ext_id) {
                    otel_warn!(
                        "extension.unbound",
                        message = "extension defined in pipeline config but no node binds to any of its capabilities; dropping",
                        pipeline_group_id = pipeline_group_id.as_ref(),
                        pipeline_id = pipeline_id.as_ref(),
                        core_id = core_id,
                        extension = ext_id.as_ref(),
                    );
                    return kept;
                }

                // Category 3 / 3a: per-variant consumption.
                // A variant is "consumed" iff it exists in the bundle
                // AND at least one of the extension's capabilities for
                // that variant was bound by a node (i.e., ext_id is
                // present in the corresponding consumed set).
                let local_present = bundle.local().is_some();
                let shared_present = bundle.shared().is_some();
                let local_consumed = local_present && consumed_local.contains(&ext_id);
                let shared_consumed = shared_present && consumed_shared.contains(&ext_id);

                // Category 3: bound but no variant consumed -> warn + drop.
                if !local_consumed && !shared_consumed {
                    otel_warn!(
                        "extension.unconsumed",
                        message = "node bindings reference this extension but no node called require_*/optional_* for any of its variants; dropping",
                        pipeline_group_id = pipeline_group_id.as_ref(),
                        pipeline_id = pipeline_id.as_ref(),
                        core_id = core_id,
                        extension = ext_id.as_ref(),
                    );
                    return kept;
                }

                // Category 3a: at least one variant consumed. Keep the
                // consumed variant(s); silently drop the unused one -- no
                // warning, since the extension as a whole is in use.
                if let Some(local) = bundle.take_local()
                    && local_consumed
                {
                    kept.push((
                        local,
                        entity_keys
                            .local
                            .expect("wire_telemetry mints a key for every present variant"),
                    ));
                }
                if let Some(shared) = bundle.take_shared()
                    && shared_consumed
                {
                    kept.push((
                        shared,
                        entity_keys
                            .shared
                            .expect("wire_telemetry mints a key for every present variant"),
                    ));
                }
                kept
            })
            .collect();

        let edges = collect_hyper_edges_runtime_from_connections(&config, &build_state)?;

        // First pass: plan hyper-edge wiring to avoid multiple mutable borrows
        let buffer_size = NonZeroUsize::new(channel_capacity_policy.pdata)
            .expect("channel_capacity.pdata must be non-zero");
        let nodes = std::mem::take(&mut build_state.nodes);
        let mut pipeline = RuntimePipeline::new(
            config,
            receivers,
            processors,
            exporters,
            extension_wrappers,
            nodes,
            telemetry_policy,
        );
        let wirings = edges
            .into_iter()
            .map(|hyper_edge| {
                let resolved = hyper_edge.resolve(&build_state)?;
                resolved.into_wiring(
                    &pipeline,
                    &mut build_state,
                    buffer_size,
                    basic_runtime_metrics_enabled,
                    &pipeline_group_id,
                    &pipeline_id,
                    core_id,
                )
            })
            .collect::<Result<Vec<_>, Error>>()?;

        // Second pass: apply hyper-edge wiring
        for wiring in wirings {
            wiring.apply(&mut pipeline, &pipeline_group_id, &pipeline_id, core_id)?;
        }
        pipeline.set_channel_metrics(build_state.channel_metrics.into_handles());
        pipeline.set_admission_metrics(build_state.admission_metrics.into_handles());

        Ok(pipeline)
    }

    fn validate_connection_wiring_contracts(&self, config: &PipelineConfig) -> Result<(), Error> {
        let mut contracts_by_node: HashMap<NodeName, wiring_contract::WiringContract> =
            HashMap::new();

        for (node_name, node_config) in config.node_iter() {
            let contract = match node_config.kind() {
                otel_arrow_dfe_config::node::NodeKind::Receiver => {
                    let normalized = otel_arrow_dfe_config::node_urn::validate_plugin_urn(
                        node_config.r#type.as_ref(),
                        otel_arrow_dfe_config::node::NodeKind::Receiver,
                    )
                    .map_err(|e| Error::ConfigError(Box::new(e)))?;
                    self.get_receiver_factory_map()
                        .get(normalized.as_str())
                        .ok_or(Error::UnknownReceiver {
                            plugin_urn: normalized,
                        })?
                        .wiring_contract
                }
                otel_arrow_dfe_config::node::NodeKind::Processor => {
                    let normalized = otel_arrow_dfe_config::node_urn::validate_plugin_urn(
                        node_config.r#type.as_ref(),
                        otel_arrow_dfe_config::node::NodeKind::Processor,
                    )
                    .map_err(|e| Error::ConfigError(Box::new(e)))?;
                    self.get_processor_factory_map()
                        .get(normalized.as_str())
                        .ok_or(Error::UnknownProcessor {
                            plugin_urn: normalized,
                        })?
                        .wiring_contract
                }
                otel_arrow_dfe_config::node::NodeKind::Exporter => {
                    let normalized = otel_arrow_dfe_config::node_urn::validate_plugin_urn(
                        node_config.r#type.as_ref(),
                        otel_arrow_dfe_config::node::NodeKind::Exporter,
                    )
                    .map_err(|e| Error::ConfigError(Box::new(e)))?;
                    self.get_exporter_factory_map()
                        .get(normalized.as_str())
                        .ok_or(Error::UnknownExporter {
                            plugin_urn: normalized,
                        })?
                        .wiring_contract
                }
            };

            _ = contracts_by_node.insert(node_name.as_ref().to_string().into(), contract);
        }

        let mut destinations_by_source_output: HashMap<(NodeName, PortName), HashSet<NodeName>> =
            HashMap::new();
        for connection in config.connection_iter() {
            let mut destinations: Vec<NodeName> = connection
                .to_nodes()
                .into_iter()
                .map(|node_id| node_id.as_ref().to_string().into())
                .collect();
            if destinations.is_empty() {
                continue;
            }
            destinations.sort_unstable_by(|left, right| left.as_ref().cmp(right.as_ref()));
            destinations.dedup_by(|left, right| left.as_ref() == right.as_ref());

            for source in connection.from_sources() {
                let source_name: NodeName = source.node_id().as_ref().to_string().into();
                let source_port = source.resolved_output_port();
                let entry = destinations_by_source_output
                    .entry((source_name, source_port))
                    .or_default();
                entry.extend(destinations.iter().cloned());
            }
        }

        for ((source, output), destination_set) in destinations_by_source_output {
            let Some(contract) = contracts_by_node.get(&source) else {
                return Err(Error::UnknownNode { node: source });
            };
            let mut destinations: Vec<NodeName> = destination_set.into_iter().collect();
            destinations.sort_unstable_by(|left, right| left.as_ref().cmp(right.as_ref()));
            contract.validate_output_destinations(&source, &output, &destinations)?;
        }

        Ok(())
    }

    fn build_node_wrapper<W, F>(
        &self,
        build_state: &mut BuildState<PData>,
        base_ctx: &PipelineContext,
        node_type: NodeType,
        node_id: NodeId,
        basic_runtime_metrics_enabled: bool,
        create_wrapper: F,
    ) -> Result<W, Error>
    where
        W: TelemetryWrapped,
        F: FnOnce() -> Result<W, Error>,
    {
        let node_entity_key = base_ctx.register_node_entity();
        let node_telemetry_handle =
            NodeTelemetryHandle::new(base_ctx.metrics_registry(), node_entity_key);
        // Create the guard before any fallible work so failed builds still clean up.
        let mut node_guard = Some(NodeTelemetryGuard::new(node_telemetry_handle.clone()));
        build_state.register_node(
            node_type,
            node_id,
            base_ctx.clone(),
            node_telemetry_handle.clone(),
        )?;
        let wrapper =
            with_node_telemetry_handle(node_telemetry_handle.clone(), || -> Result<W, Error> {
                let wrapper = create_wrapper()?;
                let wrapper = wrapper.with_control_channel_metrics(
                    base_ctx,
                    &mut build_state.channel_metrics,
                    basic_runtime_metrics_enabled,
                );
                build_state
                    .admission_metrics
                    .register_if_enabled(basic_runtime_metrics_enabled, || {
                        base_ctx.admission().metrics_handle(base_ctx)
                    });
                Ok(wrapper)
            })?;
        Ok(wrapper
            .with_node_telemetry_guard(node_guard.take().expect("node telemetry guard missing")))
    }

    /// Determines the best channel type from the following parameters:
    /// - The number of sources connected to the channel.
    /// - The number of destinations connected to the channel.
    ///
    /// Current behavior:
    /// - multi-destination edges use competing consumers over a shared channel
    ///   (`one_of` semantics).
    /// - broadcast semantics are not yet implemented.
    ///
    /// This function returns a tuple containing one sender per source and one receiver per
    /// destination.
    fn select_channel_type(
        src_nodes: &[&dyn Node<PData>],
        dest_nodes: &[&dyn Node<PData>],
        buffer_size: NonZeroUsize,
        channel_id: Cow<'static, str>,
        source_ports: &[PortName],
        source_contexts: &[PipelineContext],
        source_telemetries: &[NodeTelemetryHandle],
        dest_contexts: &[PipelineContext],
        dest_telemetries: &[NodeTelemetryHandle],
        channel_metrics: &mut ChannelMetricsRegistry,
        channel_metrics_enabled: bool,
    ) -> Result<(Vec<Sender<PData>>, Vec<Receiver<PData>>), Error>
    where
        PData: Unwindable,
    {
        let any_source_is_shared = src_nodes.iter().any(|source| source.is_shared());
        let any_dest_is_shared = dest_nodes.iter().any(|dest| dest.is_shared());
        let use_shared_channels = any_source_is_shared || any_dest_is_shared;
        let num_sources = src_nodes.len();
        let num_destinations = dest_nodes.len();
        debug_assert_eq!(num_sources, source_ports.len());
        debug_assert_eq!(num_sources, source_contexts.len());
        debug_assert_eq!(num_sources, source_telemetries.len());
        debug_assert_eq!(num_destinations, dest_contexts.len());
        debug_assert_eq!(num_destinations, dest_telemetries.len());

        let channel_kind = ChannelKind::Pdata;
        let capacity = buffer_size.get() as u64;

        let register_sender_metrics = |ctx: &PipelineContext,
                                       telemetry: &NodeTelemetryHandle,
                                       entity_key| {
            let metrics = PdataChannelSenderMetricSets {
                messages: ctx
                    .register_measurement_metric_set_for_entity::<ChannelSenderMetrics>(entity_key),
                failures: ctx
                    .register_measurement_metric_set_for_entity::<ChannelSenderFailureMetrics>(
                        entity_key,
                    ),
            };
            for key in metrics.metric_set_keys() {
                telemetry.track_metric_set(key);
            }
            ChannelSenderMetricSets::Pdata(metrics)
        };
        let register_receiver_metrics = |ctx: &PipelineContext,
                                         telemetry: &NodeTelemetryHandle,
                                         entity_key| {
            let metrics = PdataChannelReceiverMetricSets {
                messages: ctx.register_measurement_metric_set_for_entity::<ChannelReceiverMetrics>(
                    entity_key,
                ),
                state: ctx
                    .register_metric_set_for_entity::<ChannelReceiverStateMetrics>(entity_key),
            };
            for key in metrics.metric_set_keys() {
                telemetry.track_metric_set(key);
            }
            ChannelReceiverMetricSets::Pdata(metrics)
        };

        if channel_metrics_enabled {
            match (use_shared_channels, num_destinations > 1) {
                (true, true) => {
                    let channel_mode = ChannelMode::Shared;
                    let channel_type = ChannelType::Mpmc;
                    let channel_impl = ChannelImplementation::Flume;
                    let (pdata_sender, pdata_receiver) = flume::bounded(buffer_size.get());
                    let queue_depth = SharedChannelQueueDepth::default();
                    let mut pdata_senders = Vec::with_capacity(num_sources);
                    for ((ctx, telemetry), port) in source_contexts
                        .iter()
                        .zip(source_telemetries.iter())
                        .zip(source_ports.iter())
                    {
                        let sender_entity_key = ctx.register_node_channel_entity(
                            channel_id.clone(),
                            port.clone(),
                            channel_kind,
                            channel_mode,
                            channel_type,
                            channel_impl,
                        );
                        telemetry.add_output_channel_key(port.clone(), sender_entity_key);
                        let sender_metrics =
                            register_sender_metrics(ctx, telemetry, sender_entity_key);
                        let sender = SharedSender::mpmc_with_metrics(
                            pdata_sender.clone(),
                            channel_metrics,
                            sender_metrics,
                            queue_depth.clone(),
                            Some(<PData as Unwindable>::signal),
                        );
                        pdata_senders.push(Sender::Shared(sender));
                    }
                    let pdata_receivers = dest_contexts
                        .iter()
                        .zip(dest_telemetries.iter())
                        .map(|(ctx, telemetry)| {
                            let receiver_entity_key = ctx.register_node_channel_entity(
                                channel_id.clone(),
                                "input".into(),
                                channel_kind,
                                channel_mode,
                                channel_type,
                                channel_impl,
                            );
                            telemetry.set_input_channel_key(receiver_entity_key);
                            let receiver_metrics =
                                register_receiver_metrics(ctx, telemetry, receiver_entity_key);
                            let receiver = SharedReceiver::mpmc_with_metrics(
                                pdata_receiver.clone(),
                                channel_metrics,
                                receiver_metrics,
                                capacity,
                                queue_depth.clone(),
                                Some(<PData as Unwindable>::signal),
                            );
                            Receiver::Shared(receiver)
                        })
                        .collect::<Vec<_>>();
                    Ok((pdata_senders, pdata_receivers))
                }
                (true, false) => {
                    let channel_mode = ChannelMode::Shared;
                    let channel_type = ChannelType::Mpsc;
                    let channel_impl = ChannelImplementation::Tokio;
                    let (pdata_sender, pdata_receiver) =
                        tokio::sync::mpsc::channel::<PData>(buffer_size.get());
                    let queue_depth = SharedChannelQueueDepth::default();
                    let mut pdata_senders = Vec::with_capacity(num_sources);
                    for ((ctx, telemetry), port) in source_contexts
                        .iter()
                        .zip(source_telemetries.iter())
                        .zip(source_ports.iter())
                    {
                        let sender_entity_key = ctx.register_node_channel_entity(
                            channel_id.clone(),
                            port.clone(),
                            channel_kind,
                            channel_mode,
                            channel_type,
                            channel_impl,
                        );
                        telemetry.add_output_channel_key(port.clone(), sender_entity_key);
                        let sender_metrics =
                            register_sender_metrics(ctx, telemetry, sender_entity_key);
                        let sender = SharedSender::mpsc_with_metrics(
                            pdata_sender.clone(),
                            channel_metrics,
                            sender_metrics,
                            queue_depth.clone(),
                            Some(<PData as Unwindable>::signal),
                        );
                        pdata_senders.push(Sender::Shared(sender));
                    }
                    let ctx = dest_contexts.first().expect("dest_contexts is empty");
                    let telemetry = dest_telemetries.first().expect("dest_telemetries is empty");
                    let receiver_entity_key = ctx.register_node_channel_entity(
                        channel_id.clone(),
                        "input".into(),
                        channel_kind,
                        channel_mode,
                        channel_type,
                        channel_impl,
                    );
                    telemetry.set_input_channel_key(receiver_entity_key);
                    let receiver_metrics =
                        register_receiver_metrics(ctx, telemetry, receiver_entity_key);
                    let pdata_receiver = SharedReceiver::mpsc_with_metrics(
                        pdata_receiver,
                        channel_metrics,
                        receiver_metrics,
                        capacity,
                        queue_depth,
                        Some(<PData as Unwindable>::signal),
                    );
                    Ok((pdata_senders, vec![Receiver::Shared(pdata_receiver)]))
                }
                (false, true) => {
                    let channel_mode = ChannelMode::Local;
                    let channel_type = ChannelType::Mpmc;
                    let channel_impl = ChannelImplementation::Internal;
                    // ToDo(LQ): Use a local SPMC channel when available.
                    let (pdata_sender, pdata_receiver) =
                        otel_arrow_dfe_channel::mpmc::Channel::new(buffer_size);
                    let queue_depth = LocalChannelQueueDepth::default();
                    let mut pdata_senders = Vec::with_capacity(num_sources);
                    for ((ctx, telemetry), port) in source_contexts
                        .iter()
                        .zip(source_telemetries.iter())
                        .zip(source_ports.iter())
                    {
                        let sender_entity_key = ctx.register_node_channel_entity(
                            channel_id.clone(),
                            port.clone(),
                            channel_kind,
                            channel_mode,
                            channel_type,
                            channel_impl,
                        );
                        telemetry.add_output_channel_key(port.clone(), sender_entity_key);
                        let sender_metrics =
                            register_sender_metrics(ctx, telemetry, sender_entity_key);
                        let sender = LocalSender::mpmc_with_metrics(
                            pdata_sender.clone(),
                            channel_metrics,
                            sender_metrics,
                            queue_depth.clone(),
                            Some(<PData as Unwindable>::signal),
                        );
                        pdata_senders.push(Sender::Local(sender));
                    }
                    let pdata_receivers = dest_contexts
                        .iter()
                        .zip(dest_telemetries.iter())
                        .map(|(ctx, telemetry)| {
                            let receiver_entity_key = ctx.register_node_channel_entity(
                                channel_id.clone(),
                                "input".into(),
                                channel_kind,
                                channel_mode,
                                channel_type,
                                channel_impl,
                            );
                            telemetry.set_input_channel_key(receiver_entity_key);
                            let receiver_metrics =
                                register_receiver_metrics(ctx, telemetry, receiver_entity_key);
                            let receiver = LocalReceiver::mpmc_with_metrics(
                                pdata_receiver.clone(),
                                channel_metrics,
                                receiver_metrics,
                                capacity,
                                queue_depth.clone(),
                                Some(<PData as Unwindable>::signal),
                            );
                            Receiver::Local(receiver)
                        })
                        .collect::<Vec<_>>();
                    Ok((pdata_senders, pdata_receivers))
                }
                (false, false) => {
                    let channel_mode = ChannelMode::Local;
                    let channel_type = ChannelType::Mpsc;
                    let channel_impl = ChannelImplementation::Internal;
                    // ToDo(LQ): Use a local SPSC channel when available.
                    let (pdata_sender, pdata_receiver) =
                        otel_arrow_dfe_channel::mpsc::Channel::new(buffer_size.get());
                    let queue_depth = LocalChannelQueueDepth::default();
                    let mut pdata_senders = Vec::with_capacity(num_sources);
                    for ((ctx, telemetry), port) in source_contexts
                        .iter()
                        .zip(source_telemetries.iter())
                        .zip(source_ports.iter())
                    {
                        let sender_entity_key = ctx.register_node_channel_entity(
                            channel_id.clone(),
                            port.clone(),
                            channel_kind,
                            channel_mode,
                            channel_type,
                            channel_impl,
                        );
                        telemetry.add_output_channel_key(port.clone(), sender_entity_key);
                        let sender_metrics =
                            register_sender_metrics(ctx, telemetry, sender_entity_key);
                        let sender = LocalSender::mpsc_with_metrics(
                            pdata_sender.clone(),
                            channel_metrics,
                            sender_metrics,
                            queue_depth.clone(),
                            Some(<PData as Unwindable>::signal),
                        );
                        pdata_senders.push(Sender::Local(sender));
                    }
                    let ctx = dest_contexts.first().expect("dest_contexts is empty");
                    let telemetry = dest_telemetries.first().expect("dest_telemetries is empty");
                    let receiver_entity_key = ctx.register_node_channel_entity(
                        channel_id.clone(),
                        "input".into(),
                        channel_kind,
                        channel_mode,
                        channel_type,
                        channel_impl,
                    );
                    telemetry.set_input_channel_key(receiver_entity_key);
                    let receiver_metrics =
                        register_receiver_metrics(ctx, telemetry, receiver_entity_key);
                    let pdata_receiver = LocalReceiver::mpsc_with_metrics(
                        pdata_receiver,
                        channel_metrics,
                        receiver_metrics,
                        capacity,
                        queue_depth,
                        Some(<PData as Unwindable>::signal),
                    );
                    Ok((pdata_senders, vec![Receiver::Local(pdata_receiver)]))
                }
            }
        } else {
            match (use_shared_channels, num_destinations > 1) {
                (true, true) => {
                    let channel_mode = ChannelMode::Shared;
                    let channel_type = ChannelType::Mpmc;
                    let channel_impl = ChannelImplementation::Flume;
                    let (pdata_sender, pdata_receiver) = flume::bounded(buffer_size.get());
                    let mut pdata_senders = Vec::with_capacity(num_sources);
                    for ((ctx, telemetry), port) in source_contexts
                        .iter()
                        .zip(source_telemetries.iter())
                        .zip(source_ports.iter())
                    {
                        let sender_entity_key = ctx.register_node_channel_entity(
                            channel_id.clone(),
                            port.clone(),
                            channel_kind,
                            channel_mode,
                            channel_type,
                            channel_impl,
                        );
                        telemetry.add_output_channel_key(port.clone(), sender_entity_key);
                        let sender = SharedSender::mpmc(pdata_sender.clone());
                        pdata_senders.push(Sender::Shared(sender));
                    }
                    let pdata_receivers = dest_contexts
                        .iter()
                        .zip(dest_telemetries.iter())
                        .map(|(ctx, telemetry)| {
                            let receiver_entity_key = ctx.register_node_channel_entity(
                                channel_id.clone(),
                                "input".into(),
                                channel_kind,
                                channel_mode,
                                channel_type,
                                channel_impl,
                            );
                            telemetry.set_input_channel_key(receiver_entity_key);
                            Receiver::Shared(SharedReceiver::mpmc(pdata_receiver.clone()))
                        })
                        .collect::<Vec<_>>();
                    Ok((pdata_senders, pdata_receivers))
                }
                (true, false) => {
                    let channel_mode = ChannelMode::Shared;
                    let channel_type = ChannelType::Mpsc;
                    let channel_impl = ChannelImplementation::Tokio;
                    let (pdata_sender, pdata_receiver) =
                        tokio::sync::mpsc::channel::<PData>(buffer_size.get());
                    let mut pdata_senders = Vec::with_capacity(num_sources);
                    for ((ctx, telemetry), port) in source_contexts
                        .iter()
                        .zip(source_telemetries.iter())
                        .zip(source_ports.iter())
                    {
                        let sender_entity_key = ctx.register_node_channel_entity(
                            channel_id.clone(),
                            port.clone(),
                            channel_kind,
                            channel_mode,
                            channel_type,
                            channel_impl,
                        );
                        telemetry.add_output_channel_key(port.clone(), sender_entity_key);
                        let sender = SharedSender::mpsc(pdata_sender.clone());
                        pdata_senders.push(Sender::Shared(sender));
                    }
                    let ctx = dest_contexts.first().expect("dest_contexts is empty");
                    let telemetry = dest_telemetries.first().expect("dest_telemetries is empty");
                    let receiver_entity_key = ctx.register_node_channel_entity(
                        channel_id.clone(),
                        "input".into(),
                        channel_kind,
                        channel_mode,
                        channel_type,
                        channel_impl,
                    );
                    telemetry.set_input_channel_key(receiver_entity_key);
                    Ok((
                        pdata_senders,
                        vec![Receiver::Shared(SharedReceiver::mpsc(pdata_receiver))],
                    ))
                }
                (false, true) => {
                    let channel_mode = ChannelMode::Local;
                    let channel_type = ChannelType::Mpmc;
                    let channel_impl = ChannelImplementation::Internal;
                    // ToDo(LQ): Use a local SPMC channel when available.
                    let (pdata_sender, pdata_receiver) =
                        otel_arrow_dfe_channel::mpmc::Channel::new(buffer_size);
                    let mut pdata_senders = Vec::with_capacity(num_sources);
                    for ((ctx, telemetry), port) in source_contexts
                        .iter()
                        .zip(source_telemetries.iter())
                        .zip(source_ports.iter())
                    {
                        let sender_entity_key = ctx.register_node_channel_entity(
                            channel_id.clone(),
                            port.clone(),
                            channel_kind,
                            channel_mode,
                            channel_type,
                            channel_impl,
                        );
                        telemetry.add_output_channel_key(port.clone(), sender_entity_key);
                        let sender = LocalSender::mpmc(pdata_sender.clone());
                        pdata_senders.push(Sender::Local(sender));
                    }
                    let pdata_receivers = dest_contexts
                        .iter()
                        .zip(dest_telemetries.iter())
                        .map(|(ctx, telemetry)| {
                            let receiver_entity_key = ctx.register_node_channel_entity(
                                channel_id.clone(),
                                "input".into(),
                                channel_kind,
                                channel_mode,
                                channel_type,
                                channel_impl,
                            );
                            telemetry.set_input_channel_key(receiver_entity_key);
                            Receiver::Local(LocalReceiver::mpmc(pdata_receiver.clone()))
                        })
                        .collect::<Vec<_>>();
                    Ok((pdata_senders, pdata_receivers))
                }
                (false, false) => {
                    let channel_mode = ChannelMode::Local;
                    let channel_type = ChannelType::Mpsc;
                    let channel_impl = ChannelImplementation::Internal;
                    // ToDo(LQ): Use a local SPSC channel when available.
                    let (pdata_sender, pdata_receiver) =
                        otel_arrow_dfe_channel::mpsc::Channel::new(buffer_size.get());
                    let mut pdata_senders = Vec::with_capacity(num_sources);
                    for ((ctx, telemetry), port) in source_contexts
                        .iter()
                        .zip(source_telemetries.iter())
                        .zip(source_ports.iter())
                    {
                        let sender_entity_key = ctx.register_node_channel_entity(
                            channel_id.clone(),
                            port.clone(),
                            channel_kind,
                            channel_mode,
                            channel_type,
                            channel_impl,
                        );
                        telemetry.add_output_channel_key(port.clone(), sender_entity_key);
                        let sender = LocalSender::mpsc(pdata_sender.clone());
                        pdata_senders.push(Sender::Local(sender));
                    }
                    let ctx = dest_contexts.first().expect("dest_contexts is empty");
                    let telemetry = dest_telemetries.first().expect("dest_telemetries is empty");
                    let receiver_entity_key = ctx.register_node_channel_entity(
                        channel_id.clone(),
                        "input".into(),
                        channel_kind,
                        channel_mode,
                        channel_type,
                        channel_impl,
                    );
                    telemetry.set_input_channel_key(receiver_entity_key);
                    Ok((
                        pdata_senders,
                        vec![Receiver::Local(LocalReceiver::mpsc(pdata_receiver))],
                    ))
                }
            }
        }
    }

    /// Creates a receiver node and adds it to the list of runtime nodes.
    fn create_receiver(
        &self,
        pipeline_ctx: &PipelineContext,
        node_id: NodeId,
        node_config: Arc<NodeUserConfig>,
        control_channel_capacity: usize,
        pdata_channel_capacity: usize,
        capabilities: &capability::registry::Capabilities,
    ) -> Result<ReceiverWrapper<PData>, Error> {
        let pipeline_group_id = pipeline_ctx.pipeline_group_id();
        let pipeline_id = pipeline_ctx.pipeline_id();
        let core_id = pipeline_ctx.core_id();
        let name = node_id.name.clone();

        otel_debug!(
            "receiver.create.start",
            pipeline_group_id = pipeline_group_id.as_ref(),
            pipeline_id = pipeline_id.as_ref(),
            core_id = core_id,
            node_id = name.as_ref(),
        );

        // Validate plugin URN structure during registration
        let normalized = otel_arrow_dfe_config::node_urn::validate_plugin_urn(
            node_config.r#type.as_ref(),
            otel_arrow_dfe_config::node::NodeKind::Receiver,
        )
        .map_err(|e| Error::ConfigError(Box::new(e)))?;

        let factory = self
            .get_receiver_factory_map()
            .get(normalized.as_str())
            .ok_or_else(|| Error::UnknownReceiver {
                plugin_urn: normalized.clone(),
            })?;
        let runtime_config = ReceiverConfig::with_channel_capacities(
            name.clone(),
            control_channel_capacity,
            pdata_channel_capacity,
        );
        let create = factory.create;

        let capture_policy = pipeline_ctx
            .compiled_context_bindings()
            .header_capture_policy(&pipeline_ctx.pipeline_key(), &pipeline_ctx.node_id())
            .cloned();
        let authorized_identity_policy = pipeline_ctx
            .compiled_context_bindings()
            .authorized_identity_policy(&pipeline_ctx.pipeline_key(), &pipeline_ctx.node_id())
            .cloned();

        let receiver = create(
            (*pipeline_ctx).clone(),
            node_id.clone(),
            node_config,
            &runtime_config,
            capabilities,
        )
        .map_err(|e| Error::ConfigError(Box::new(e)))?
        .with_capture_policy(capture_policy)
        .with_authorized_identity_policy(authorized_identity_policy);
        pipeline_ctx
            .admission()
            .validate_factory_consumption(normalized.as_str())
            .map_err(|error| {
                Error::ConfigError(Box::new(
                    otel_arrow_dfe_config::error::Error::InvalidUserConfig {
                        error: error.to_string(),
                    },
                ))
            })?;

        otel_debug!(
            "receiver.create.complete",
            pipeline_group_id = pipeline_group_id.as_ref(),
            pipeline_id = pipeline_id.as_ref(),
            core_id = core_id,
            node_id = name.as_ref(),
        );

        Ok(receiver)
    }

    /// Creates a processor node and adds it to the list of runtime nodes.
    fn create_processor(
        &self,
        pipeline_ctx: &PipelineContext,
        node_id: NodeId,
        node_config: Arc<NodeUserConfig>,
        control_channel_capacity: usize,
        pdata_channel_capacity: usize,
        capabilities: &capability::registry::Capabilities,
    ) -> Result<ProcessorWrapper<PData>, Error> {
        let pipeline_group_id = pipeline_ctx.pipeline_group_id();
        let pipeline_id = pipeline_ctx.pipeline_id();
        let core_id = pipeline_ctx.core_id();
        let name = node_id.name.clone();

        otel_debug!(
            "processor.create.start",
            pipeline_group_id = pipeline_group_id.as_ref(),
            pipeline_id = pipeline_id.as_ref(),
            core_id = core_id,
            node_id = name.as_ref(),
        );

        // Validate plugin URN structure during registration
        let normalized = otel_arrow_dfe_config::node_urn::validate_plugin_urn(
            node_config.r#type.as_ref(),
            otel_arrow_dfe_config::node::NodeKind::Processor,
        )
        .map_err(|e| Error::ConfigError(Box::new(e)))?;

        let factory = self
            .get_processor_factory_map()
            .get(normalized.as_str())
            .ok_or(Error::UnknownProcessor {
                plugin_urn: normalized.clone(),
            })?;
        let processor_config = ProcessorConfig::with_channel_capacities(
            name.clone(),
            control_channel_capacity,
            pdata_channel_capacity,
        );
        let create = factory.create;

        let processor = create(
            (*pipeline_ctx).clone(),
            node_id.clone(),
            node_config.clone(),
            &processor_config,
            capabilities,
        )
        .map_err(|e| Error::ConfigError(Box::new(e)))?;
        pipeline_ctx
            .admission()
            .validate_factory_consumption(normalized.as_str())
            .map_err(|error| {
                Error::ConfigError(Box::new(
                    otel_arrow_dfe_config::error::Error::InvalidUserConfig {
                        error: error.to_string(),
                    },
                ))
            })?;

        validate_local_wakeup_requirements(&node_id, processor.runtime_requirements())?;

        otel_debug!(
            "processor.create.complete",
            pipeline_group_id = pipeline_group_id.as_ref(),
            pipeline_id = pipeline_id.as_ref(),
            core_id = core_id,
            node_id = name.as_ref(),
        );

        Ok(processor)
    }

    /// Creates an exporter node and adds it to the list of runtime nodes.
    fn create_exporter(
        &self,
        pipeline_ctx: &PipelineContext,
        node_id: NodeId,
        node_config: Arc<NodeUserConfig>,
        control_channel_capacity: usize,
        pdata_channel_capacity: usize,
        capabilities: &capability::registry::Capabilities,
    ) -> Result<ExporterWrapper<PData>, Error> {
        let pipeline_group_id = pipeline_ctx.pipeline_group_id();
        let pipeline_id = pipeline_ctx.pipeline_id();
        let core_id = pipeline_ctx.core_id();
        let name = node_id.name.clone();

        otel_debug!(
            "exporter.create.start",
            pipeline_group_id = pipeline_group_id.as_ref(),
            pipeline_id = pipeline_id.as_ref(),
            core_id = core_id,
            node_id = name.as_ref(),
        );

        // Validate plugin URN structure during registration
        let normalized = otel_arrow_dfe_config::node_urn::validate_plugin_urn(
            node_config.r#type.as_ref(),
            otel_arrow_dfe_config::node::NodeKind::Exporter,
        )
        .map_err(|e| Error::ConfigError(Box::new(e)))?;

        let factory = self
            .get_exporter_factory_map()
            .get(normalized.as_str())
            .ok_or(Error::UnknownExporter {
                plugin_urn: normalized.clone(),
            })?;
        let exporter_config = ExporterConfig::with_channel_capacities(
            name.clone(),
            control_channel_capacity,
            pdata_channel_capacity,
        );
        let create = factory.create;

        let propagation_policy = pipeline_ctx
            .compiled_context_bindings()
            .header_propagation_policy(&pipeline_ctx.pipeline_key(), &pipeline_ctx.node_id())
            .cloned();

        let exporter = create(
            (*pipeline_ctx).clone(),
            node_id.clone(),
            node_config,
            &exporter_config,
            capabilities,
        )
        .map_err(|e| Error::ConfigError(Box::new(e)))?
        .with_propagation_policy(propagation_policy);
        pipeline_ctx
            .admission()
            .validate_factory_consumption(normalized.as_str())
            .map_err(|error| {
                Error::ConfigError(Box::new(
                    otel_arrow_dfe_config::error::Error::InvalidUserConfig {
                        error: error.to_string(),
                    },
                ))
            })?;

        otel_debug!(
            "exporter.create.complete",
            pipeline_group_id = pipeline_group_id.as_ref(),
            pipeline_id = pipeline_id.as_ref(),
            core_id = core_id,
            node_id = name.as_ref(),
        );

        Ok(exporter)
    }
}

trait TelemetryWrapped: Sized {
    fn with_control_channel_metrics(
        self,
        pipeline_ctx: &PipelineContext,
        channel_metrics: &mut ChannelMetricsRegistry,
        channel_metrics_enabled: bool,
    ) -> Self;
    fn with_node_telemetry_guard(self, guard: NodeTelemetryGuard) -> Self;
}

impl<PData> TelemetryWrapped for ReceiverWrapper<PData> {
    fn with_control_channel_metrics(
        self,
        pipeline_ctx: &PipelineContext,
        channel_metrics: &mut ChannelMetricsRegistry,
        channel_metrics_enabled: bool,
    ) -> Self {
        ReceiverWrapper::with_control_channel_metrics(
            self,
            pipeline_ctx,
            channel_metrics,
            channel_metrics_enabled,
        )
    }

    fn with_node_telemetry_guard(self, guard: NodeTelemetryGuard) -> Self {
        ReceiverWrapper::with_node_telemetry_guard(self, guard)
    }
}

impl<PData> TelemetryWrapped for ProcessorWrapper<PData> {
    fn with_control_channel_metrics(
        self,
        pipeline_ctx: &PipelineContext,
        channel_metrics: &mut ChannelMetricsRegistry,
        channel_metrics_enabled: bool,
    ) -> Self {
        ProcessorWrapper::with_control_channel_metrics(
            self,
            pipeline_ctx,
            channel_metrics,
            channel_metrics_enabled,
        )
    }

    fn with_node_telemetry_guard(self, guard: NodeTelemetryGuard) -> Self {
        ProcessorWrapper::with_node_telemetry_guard(self, guard)
    }
}

impl<PData> TelemetryWrapped for ExporterWrapper<PData> {
    fn with_control_channel_metrics(
        self,
        pipeline_ctx: &PipelineContext,
        channel_metrics: &mut ChannelMetricsRegistry,
        channel_metrics_enabled: bool,
    ) -> Self {
        ExporterWrapper::with_control_channel_metrics(
            self,
            pipeline_ctx,
            channel_metrics,
            channel_metrics_enabled,
        )
    }

    fn with_node_telemetry_guard(self, guard: NodeTelemetryGuard) -> Self {
        ExporterWrapper::with_node_telemetry_guard(self, guard)
    }
}

struct NodeRegistration {
    node_id: NodeId,
    node_type: NodeType,
    context: PipelineContext,
    telemetry: NodeTelemetryHandle,
}

struct BuildState<PData> {
    nodes: NodeDefs<PData, PipeNode>,
    registry: HashMap<NodeName, NodeRegistration>,
    channel_metrics: ChannelMetricsRegistry,
    admission_metrics: admission::metrics::AdmissionMetricsRegistry,
}

impl<PData> BuildState<PData> {
    fn new() -> Self {
        Self {
            nodes: NodeDefs::default(),
            registry: HashMap::new(),
            channel_metrics: ChannelMetricsRegistry::default(),
            admission_metrics: admission::metrics::AdmissionMetricsRegistry::default(),
        }
    }

    fn next_node_id(
        &mut self,
        name: NodeName,
        node_type: NodeType,
        inner: PipeNode,
    ) -> Result<NodeId, Error> {
        self.nodes.next(name, node_type, inner)
    }

    fn register_node(
        &mut self,
        node_type: NodeType,
        node_id: NodeId,
        context: PipelineContext,
        telemetry: NodeTelemetryHandle,
    ) -> Result<(), Error> {
        if self.registry.contains_key(&node_id.name) {
            return Err(match node_type {
                NodeType::Receiver => Error::ReceiverAlreadyExists { receiver: node_id },
                NodeType::Processor => Error::ProcessorAlreadyExists { processor: node_id },
                NodeType::Exporter => Error::ExporterAlreadyExists { exporter: node_id },
            });
        }

        let _ = self.registry.insert(
            node_id.name.clone(),
            NodeRegistration {
                node_id,
                node_type,
                context,
                telemetry,
            },
        );
        Ok(())
    }

    fn registration(&self, name: &NodeName) -> Result<&NodeRegistration, Error> {
        self.registry
            .get(name)
            .ok_or_else(|| Error::UnknownNode { node: name.clone() })
    }

    fn node_context(&self, name: &NodeName) -> Result<PipelineContext, Error> {
        Ok(self.registration(name)?.context.clone())
    }

    fn node_telemetry(&self, name: &NodeName) -> Result<NodeTelemetryHandle, Error> {
        Ok(self.registration(name)?.telemetry.clone())
    }

    fn resolve_destination_id(&self, name: &NodeName) -> Result<NodeId, Error> {
        let registration = self.registration(name)?;
        match registration.node_type {
            NodeType::Processor | NodeType::Exporter => Ok(registration.node_id.clone()),
            NodeType::Receiver => Err(Error::UnknownNode { node: name.clone() }),
        }
    }
}

/// Represents a source endpoint for a hyper-edge in the runtime graph.
struct NodeIdPortName {
    node_id: NodeId,
    port: PortName,
}

/// Represents the channel wiring for a hyper-edge in the runtime graph.
struct HyperEdgeWiring<PData> {
    /// All the source endpoints for this hyper-edge.
    sources: Vec<NodeIdPortName>,
    /// The senders assigned to the sources.
    senders: Vec<Sender<PData>>,
    /// The destinations and their assigned receivers.
    destinations: Vec<(NodeId, Receiver<PData>)>,
}

impl<PData> HyperEdgeWiring<PData>
where
    PData: 'static + Clone + Debug,
{
    fn apply(
        self,
        pipeline: &mut RuntimePipeline<PData>,
        pipeline_group_id: &PipelineGroupId,
        pipeline_id: &PipelineId,
        core_id: usize,
    ) -> Result<(), Error> {
        debug_assert_eq!(self.sources.len(), self.senders.len());

        // When there are multiple sources sharing a channel to the same
        // destination(s), mark each source so it tags outgoing messages with
        // its node id.  This lets the destination distinguish which source
        // sent each message.
        let multi_source = self.sources.len() > 1;

        for (source, sender) in self.sources.into_iter().zip(self.senders) {
            let src_node = pipeline
                .get_mut_node_with_pdata_sender(source.node_id.index)
                .ok_or_else(|| Error::UnknownNode {
                    node: source.node_id.name.clone(),
                })?;
            if multi_source {
                src_node.set_source_tagging(SourceTagging::Enabled);
            }
            otel_debug!(
                "pdata.sender.set",
                pipeline_group_id = pipeline_group_id.as_ref(),
                pipeline_id = pipeline_id.as_ref(),
                core_id = core_id,
                node_id = source.node_id.name.as_ref(),
                port = source.port.as_ref(),
            );
            src_node.set_pdata_sender(source.node_id, source.port, sender)?;
        }
        for (dest, receiver) in self.destinations {
            let dest_node = pipeline
                .get_mut_node_with_pdata_receiver(dest.index)
                .ok_or_else(|| Error::UnknownNode {
                    node: dest.name.clone(),
                })?;
            otel_debug!(
                "pdata.receiver.set",
                pipeline_group_id = pipeline_group_id.as_ref(),
                pipeline_id = pipeline_id.as_ref(),
                core_id = core_id,
                node_id = dest.name.as_ref(),
            );

            dest_node.set_pdata_receiver(dest, receiver)?;
        }
        Ok(())
    }
}

/// Represents a hyper-edge in the runtime graph, corresponding to one or more source ports,
/// its dispatch policy, and the set of destination node ids connected to those ports.
struct HyperEdgeRuntime {
    sources: Vec<NodeIdPortName>,

    dispatch_policy: DispatchPolicy,

    // names are from the configuration, not yet resolved
    destinations: Vec<NodeName>,
}

/// Represents a hyper-edge with resolved destination node IDs.
struct ResolvedHyperEdgeRuntime {
    sources: Vec<NodeIdPortName>,
    destinations: Vec<NodeId>,
    dispatch_policy: DispatchPolicy,
    source_ids_display: String,
    destination_ids_display: String,
}

#[derive(Hash, PartialEq, Eq)]
struct HyperEdgeKey {
    dispatch_policy: std::mem::Discriminant<DispatchPolicy>,
    destinations: Vec<NodeName>,
}
impl HyperEdgeRuntime {
    fn resolve<PData>(
        self,
        build_state: &BuildState<PData>,
    ) -> Result<ResolvedHyperEdgeRuntime, Error> {
        let destinations = self
            .destinations
            .iter()
            .map(|name| build_state.resolve_destination_id(name))
            .collect::<Result<Vec<_>, Error>>()?;
        let source_ids_display = self
            .sources
            .iter()
            .map(|source| format!("{}:{}", source.node_id.name, source.port))
            .collect::<Vec<_>>()
            .join(", ");
        let destination_ids_display = destinations
            .iter()
            .map(|dest| dest.name.as_ref().to_string())
            .collect::<Vec<_>>()
            .join(", ");
        Ok(ResolvedHyperEdgeRuntime {
            sources: self.sources,
            destinations,
            dispatch_policy: self.dispatch_policy,
            source_ids_display,
            destination_ids_display,
        })
    }
}

impl ResolvedHyperEdgeRuntime {
    fn channel_id(&self) -> Cow<'static, str> {
        let sources = self
            .sources
            .iter()
            .map(|source| format!("{}:{}", source.node_id.name, source.port))
            .collect::<Vec<_>>();
        let destinations = self
            .destinations
            .iter()
            .map(|dest| dest.name.as_ref().to_string())
            .collect::<Vec<_>>();
        let signature = format!(
            "src:[{}]|dst:[{}]|dispatch:{}",
            sources.join(","),
            destinations.join(","),
            dispatch_policy_label(&self.dispatch_policy)
        );
        let hash = stable_hash64(&signature);
        format!("hyperedge:{:016x}", hash).into()
    }

    fn into_wiring<PData>(
        self,
        pipeline: &RuntimePipeline<PData>,
        build_state: &mut BuildState<PData>,
        buffer_size: NonZeroUsize,
        channel_metrics_enabled: bool,
        pipeline_group_id: &PipelineGroupId,
        pipeline_id: &PipelineId,
        core_id: usize,
    ) -> Result<HyperEdgeWiring<PData>, Error>
    where
        PData: 'static + Clone + Debug + Unwindable,
    {
        let channel_id = self.channel_id();
        let ResolvedHyperEdgeRuntime {
            sources,
            destinations,
            dispatch_policy: _,
            source_ids_display,
            destination_ids_display,
        } = self;
        let span = otel_debug_span!(
            "hyper_edge.wireup",
            pipeline_group_id = pipeline_group_id.as_ref(),
            pipeline_id = pipeline_id.as_ref(),
            core_id = core_id,
            source_ids = source_ids_display,
            dest_ids = destination_ids_display
        );
        let _enter = span.enter();

        let mut source_nodes = Vec::with_capacity(sources.len());
        let mut source_ports = Vec::with_capacity(sources.len());
        let mut source_contexts = Vec::with_capacity(sources.len());
        let mut source_telemetries = Vec::with_capacity(sources.len());
        for source in &sources {
            let src_node =
                pipeline
                    .get_node(source.node_id.index)
                    .ok_or_else(|| Error::UnknownNode {
                        node: source.node_id.name.clone(),
                    })?;
            source_nodes.push(src_node);
            source_ports.push(source.port.clone());
            source_contexts.push(build_state.node_context(&source.node_id.name)?);
            source_telemetries.push(build_state.node_telemetry(&source.node_id.name)?);
        }

        // Get destination nodes: note the order of dest_nodes matches destinations and is
        // preserved by select_channel_type(). The zip() below depends on both of these.
        let mut dest_nodes = Vec::with_capacity(destinations.len());
        let mut dest_contexts = Vec::with_capacity(destinations.len());
        let mut dest_telemetries = Vec::with_capacity(destinations.len());
        for node_id in &destinations {
            let node = pipeline
                .get_node(node_id.index)
                .ok_or_else(|| Error::UnknownNode {
                    node: node_id.name.clone(),
                })?;
            dest_nodes.push(node);
            dest_contexts.push(build_state.node_context(&node_id.name)?);
            dest_telemetries.push(build_state.node_telemetry(&node_id.name)?);
        }

        let (pdata_senders, pdata_receivers) = PipelineFactory::<PData>::select_channel_type(
            &source_nodes,
            &dest_nodes,
            buffer_size,
            channel_id,
            &source_ports,
            &source_contexts,
            &source_telemetries,
            &dest_contexts,
            &dest_telemetries,
            &mut build_state.channel_metrics,
            channel_metrics_enabled,
        )?;

        let destinations = destinations.into_iter().zip(pdata_receivers).collect();
        Ok(HyperEdgeWiring {
            sources,
            senders: pdata_senders,
            destinations,
        })
    }
}

/// Builds hyper-edges directly from the top-level `connections` section.
fn collect_hyper_edges_runtime_from_connections<PData>(
    config: &PipelineConfig,
    build_state: &BuildState<PData>,
) -> Result<Vec<HyperEdgeRuntime>, Error> {
    let mut edges: Vec<HyperEdgeRuntime> = Vec::new();
    let mut edge_index: HashMap<HyperEdgeKey, Vec<usize>> = HashMap::new();

    for connection in config.connection_iter() {
        let mut destinations: Vec<NodeName> = connection
            .to_nodes()
            .into_iter()
            .map(|node_id| node_id.as_ref().to_string().into())
            .collect();
        if destinations.is_empty() {
            continue;
        }
        destinations.sort_unstable_by(|a, b| a.as_ref().cmp(b.as_ref()));
        destinations.dedup_by(|a, b| a.as_ref() == b.as_ref());

        let mut sources = Vec::new();
        for source in connection.from_sources() {
            let source_name: NodeName = source.node_id().as_ref().to_string().into();
            let registration = build_state.registration(&source_name)?;
            if !matches!(
                registration.node_type,
                NodeType::Receiver | NodeType::Processor
            ) {
                return Err(Error::UnknownNode { node: source_name });
            }
            sources.push(NodeIdPortName {
                node_id: registration.node_id.clone(),
                port: source.resolved_output_port(),
            });
        }
        if sources.is_empty() {
            continue;
        }
        sources.sort_by(|left, right| {
            let left_key = (left.node_id.name.as_ref(), left.port.as_ref());
            let right_key = (right.node_id.name.as_ref(), right.port.as_ref());
            left_key.cmp(&right_key)
        });
        sources.dedup_by(|left, right| {
            left.node_id.index == right.node_id.index && left.port.as_ref() == right.port.as_ref()
        });

        let dispatch_policy = connection.effective_dispatch_policy();
        let key = HyperEdgeKey {
            dispatch_policy: std::mem::discriminant(&dispatch_policy),
            destinations: destinations.clone(),
        };

        let mut match_index = None;
        if let Some(indexes) = edge_index.get(&key) {
            'candidate: for &index in indexes {
                let edge = &edges[index];
                for source in &sources {
                    if edge.sources.iter().any(|existing| {
                        existing.node_id.index == source.node_id.index
                            && existing.port.as_ref() != source.port.as_ref()
                    }) {
                        continue 'candidate;
                    }
                }
                match_index = Some(index);
                break;
            }
        }

        if let Some(index) = match_index {
            edges[index].sources.extend(sources);
        } else {
            edges.push(HyperEdgeRuntime {
                sources,
                dispatch_policy,
                destinations,
            });
            edge_index.entry(key).or_default().push(edges.len() - 1);
        }
    }

    for edge in &mut edges {
        edge.sources.sort_by(|left, right| {
            let left_key = (left.node_id.name.as_ref(), left.port.as_ref());
            let right_key = (right.node_id.name.as_ref(), right.port.as_ref());
            left_key.cmp(&right_key)
        });
        edge.sources.dedup_by(|left, right| {
            left.node_id.index == right.node_id.index && left.port.as_ref() == right.port.as_ref()
        });
    }

    Ok(edges)
}

const fn dispatch_policy_label(policy: &DispatchPolicy) -> &'static str {
    match policy {
        DispatchPolicy::OneOf => "one_of",
        DispatchPolicy::Broadcast => "broadcast",
    }
}

fn stable_hash64(value: &str) -> u64 {
    // FNV-1a 64-bit hash for a deterministic, dependency-free channel id.
    let mut hash = 0xcbf29ce484222325u64;
    for byte in value.as_bytes() {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(0x100000001b3);
    }
    hash
}

#[cfg(test)]
mod test {
    use super::*;
    use otel_arrow_dfe_config::policy::{
        RateLimitAggregation, RateLimitEnforcement, RateLimitPressure, RateLimitUnit,
        TokenBucketPolicy,
    };
    use std::time::Duration;

    /// Scenario: runtime metric levels resolve optional data-path measurements.
    /// Guarantees: detailed metrics enable node duration, item counts, and size while normal metrics enable none by default.
    #[test]
    fn detailed_runtime_metrics_enable_optional_data_path_measurements() {
        let normal = Interests::from_metric_level(MetricLevel::Normal);
        assert!(normal.contains(Interests::NODE_METRICS));
        assert!(!normal.contains(Interests::NODE_COMPLETION_DURATION));
        assert!(!normal.contains(Interests::NODE_LOCAL_DURATION));
        assert!(!normal.contains(Interests::NODE_ITEM_COUNTS));
        assert!(!normal.contains(Interests::NODE_SIZE));

        let detailed = Interests::from_metric_level(MetricLevel::Detailed);
        assert!(detailed.contains(Interests::NODE_METRICS));
        assert!(detailed.contains(Interests::NODE_COMPLETION_DURATION));
        assert!(detailed.contains(Interests::NODE_LOCAL_DURATION));
        assert!(detailed.contains(Interests::NODE_ITEM_COUNTS));
        assert!(detailed.contains(Interests::NODE_SIZE));
    }

    /// Scenario: One node opts into optional measurements below the detailed metric level.
    /// Guarantees: Effective node interests combine the pipeline level with only that node's telemetry policy.
    #[test]
    fn node_telemetry_policy_extends_effective_interests() {
        let mut node_config = NodeUserConfig::new_exporter_config("console");
        node_config.policies = Some(otel_arrow_dfe_config::node::NodePolicies {
            telemetry: Some(otel_arrow_dfe_config::node::NodeTelemetryPolicy {
                messages: true,
                completion_duration: true,
                duration: true,
                duration_distribution: otel_arrow_dfe_config::policy::DistributionTier::Detailed,
                item_counts: true,
                size: true,
            }),
        });

        let interests = Interests::for_node(MetricLevel::Normal, &node_config);
        assert!(interests.contains(Interests::NODE_METRICS));
        assert!(interests.contains(Interests::NODE_COMPLETION_DURATION));
        assert!(interests.contains(Interests::NODE_LOCAL_DURATION));
        assert!(interests.contains(Interests::NODE_ITEM_COUNTS));
        assert!(interests.contains(Interests::NODE_SIZE));
    }

    /// Scenario: One node opts into optional telemetry measurements at the basic metric level.
    /// Guarantees: all node telemetry interests, including message metrics, can be enabled below their default levels.
    #[test]
    fn node_telemetry_policy_enables_interests_at_basic_level() {
        let mut node_config = NodeUserConfig::new_exporter_config("console");
        node_config.policies = Some(otel_arrow_dfe_config::node::NodePolicies {
            telemetry: Some(otel_arrow_dfe_config::node::NodeTelemetryPolicy {
                messages: true,
                completion_duration: true,
                duration: true,
                duration_distribution: otel_arrow_dfe_config::policy::DistributionTier::Detailed,
                item_counts: true,
                size: true,
            }),
        });

        let interests = Interests::for_node(MetricLevel::Basic, &node_config);
        assert!(interests.contains(Interests::NODE_METRICS));
        assert!(interests.contains(Interests::NODE_COMPLETION_DURATION));
        assert!(interests.contains(Interests::NODE_LOCAL_DURATION));
        assert!(interests.contains(Interests::NODE_ITEM_COUNTS));
        assert!(interests.contains(Interests::NODE_SIZE));
    }

    fn admission_policy(unit: RateLimitUnit) -> RateLimiterPolicy {
        RateLimiterPolicy {
            enforcement: RateLimitEnforcement::Enforce,
            aggregation: RateLimitAggregation::ReceiverInstance,
            unit,
            pressure: RateLimitPressure::Soft,
            token_bucket: TokenBucketPolicy {
                allow: 10,
                interval: Duration::from_secs(1),
                burst: Some(10),
            },
        }
    }

    /// Scenario: a node explicitly opts out while effective limiters are available.
    /// Guarantees: an empty binding list produces an unconfigured binder.
    #[test]
    fn admission_resolution_honors_explicit_empty_opt_out() {
        let mut node = NodeUserConfig::new_receiver_config("urn:test:receiver:example");
        node.rate_limiters = Some(Vec::new());
        let policies = BTreeMap::from([(
            "ingress".to_owned(),
            admission_policy(RateLimitUnit::RequestBytes),
        )]);

        let binder = resolve_admission_binding(&node, &policies, None).expect("opt out resolves");

        assert!(!binder.is_configured());
    }

    /// Scenario: a node explicitly names a limiter absent from its effective policy map.
    /// Guarantees: resolution fails at startup instead of silently disabling admission.
    #[test]
    fn admission_resolution_rejects_unknown_explicit_name() {
        let mut node = NodeUserConfig::new_receiver_config("urn:test:receiver:example");
        node.rate_limiters = Some(vec!["missing".to_owned()]);

        let error = resolve_admission_binding(&node, &BTreeMap::new(), None)
            .expect_err("unknown limiter must fail");

        assert!(error.contains("does not name an effective limiter"));
    }

    /// Scenario: a node explicitly names two otherwise valid limiters.
    /// Guarantees: V1 rejects multi-limiter composition rather than applying only one
    /// or charging two buckets without atomic reservation semantics.
    #[test]
    fn admission_resolution_rejects_multiple_explicit_names() {
        let mut node = NodeUserConfig::new_receiver_config("urn:test:receiver:example");
        node.rate_limiters = Some(vec!["first".to_owned(), "second".to_owned()]);
        let policy = admission_policy(RateLimitUnit::RequestBytes);
        let policies =
            BTreeMap::from([("first".to_owned(), policy), ("second".to_owned(), policy)]);

        let error = resolve_admission_binding(&node, &policies, None)
            .expect_err("multiple bindings must fail");

        assert!(error.contains("at most one rate limiter binding"));
    }

    /// Scenario: a node omits its binding while an effective limiter exists.
    /// Guarantees: policy declarations remain ambient configuration until a node explicitly
    /// selects a limiter.
    #[test]
    fn admission_resolution_requires_explicit_binding() {
        let node = NodeUserConfig::new_receiver_config("urn:test:receiver:example");
        let policies = BTreeMap::from([(
            "ingress".to_owned(),
            admission_policy(RateLimitUnit::RequestBytes),
        )]);

        let binder =
            resolve_admission_binding(&node, &policies, Some(RateLimiterDeclarationScope::Engine))
                .expect("omitted binding resolves");

        assert!(!binder.is_configured());
    }

    /// Scenario: a node omits its binding while several effective limiters exist.
    /// Guarantees: the node remains unbound without requiring special ambiguity handling.
    #[test]
    fn admission_resolution_ignores_unselected_limiters() {
        let node = NodeUserConfig::new_receiver_config("urn:test:receiver:example");
        let policy = admission_policy(RateLimitUnit::RequestBytes);
        let policies =
            BTreeMap::from([("first".to_owned(), policy), ("second".to_owned(), policy)]);

        let binder =
            resolve_admission_binding(&node, &policies, None).expect("omitted binding resolves");

        assert!(!binder.is_configured());
    }

    #[test]
    fn test_interests() {
        assert_eq!(Interests::ACKS | Interests::NACKS, Interests::ACKS_OR_NACKS);
        assert_eq!(
            Interests::NODE_INPUT_METRICS | Interests::NODE_OUTPUT_METRICS,
            Interests::NODE_METRICS
        );
    }

    // -- ExtensionFactory tests -----------------------------------------------

    #[test]
    fn test_extension_factory_named_factory() {
        fn dummy_create(
            _: &ExtensionContext,
            _: otel_arrow_dfe_config::ExtensionId,
            _: Arc<otel_arrow_dfe_config::extension::ExtensionUserConfig>,
            _: &ExtensionConfig,
        ) -> Result<ExtensionBundle, otel_arrow_dfe_config::error::Error> {
            unimplemented!()
        }
        fn dummy_validate(
            _: &serde_json::Value,
        ) -> Result<(), otel_arrow_dfe_config::error::Error> {
            Ok(())
        }

        let factory = ExtensionFactory {
            name: "urn:test:example",
            description: "test extension",
            documentation_url: "",
            capabilities: None,
            create: dummy_create,
            validate_config: dummy_validate,
        };

        assert_eq!(factory.name(), "urn:test:example");

        let cloned = factory.clone();
        assert_eq!(cloned.name(), "urn:test:example");
        assert_eq!(cloned.description, "test extension");
    }

    // -- Error variant_name tests ---------------------------------------------

    #[test]
    fn test_extension_already_exists_variant_name() {
        let err = Error::ExtensionAlreadyExists {
            extension: "dup_ext".into(),
        };
        assert_eq!(err.variant_name(), "ExtensionAlreadyExists");
    }

    #[test]
    fn test_extension_factory_validate_config() {
        fn dummy_create(
            _: &ExtensionContext,
            _: otel_arrow_dfe_config::ExtensionId,
            _: Arc<otel_arrow_dfe_config::extension::ExtensionUserConfig>,
            _: &ExtensionConfig,
        ) -> Result<ExtensionBundle, otel_arrow_dfe_config::error::Error> {
            unimplemented!()
        }
        fn dummy_validate(
            config: &serde_json::Value,
        ) -> Result<(), otel_arrow_dfe_config::error::Error> {
            if config.is_null() {
                Ok(())
            } else {
                Err(otel_arrow_dfe_config::error::Error::InvalidUserConfig {
                    error: "expected null".into(),
                })
            }
        }

        let factory = ExtensionFactory {
            name: "urn:test:example",
            description: "test",
            documentation_url: "",
            capabilities: None,
            create: dummy_create,
            validate_config: dummy_validate,
        };

        assert!((factory.validate_config)(&serde_json::Value::Null).is_ok());
        assert!((factory.validate_config)(&serde_json::json!({"key": "val"})).is_err());
    }

    #[otel_arrow_dfe_telemetry_macros::metric_set(name = "test.extension.factory")]
    #[derive(Debug, Default, Clone)]
    struct FactoryTestMetrics {
        #[metric(unit = "{tick}")]
        ticks: otel_arrow_dfe_telemetry::instrument::Counter<u64>,
    }

    #[test]
    fn test_extension_factory_create_receives_extension_context() {
        use crate::extension::wrapper::ExtensionVariant;
        use crate::testing::test_extension_ctx;
        use otel_arrow_dfe_config::extension::{ExtensionUrn, ExtensionUserConfig};
        use otel_arrow_dfe_telemetry::registry::EntityKey;
        use std::cell::Cell;

        thread_local! {
            static REGISTERED_ENTITY: Cell<Option<EntityKey>> = const { Cell::new(None) };
        }

        fn entity_registering_create(
            ext_ctx: &ExtensionContext,
            name: otel_arrow_dfe_config::ExtensionId,
            _: Arc<ExtensionUserConfig>,
            _: &ExtensionConfig,
        ) -> Result<ExtensionBundle, otel_arrow_dfe_config::error::Error> {
            let entity = ext_ctx.register_extension_entity(name, ExtensionVariant::Local);
            REGISTERED_ENTITY.with(|cell| cell.set(Some(entity)));
            Err(otel_arrow_dfe_config::error::Error::InvalidUserConfig {
                error: "no-op factory".into(),
            })
        }
        fn dummy_validate(
            _: &serde_json::Value,
        ) -> Result<(), otel_arrow_dfe_config::error::Error> {
            Ok(())
        }

        let factory = ExtensionFactory {
            name: "urn:otel:extension:test_ext",
            description: "test extension that registers an entity via ext_ctx",
            documentation_url: "",
            capabilities: None,
            create: entity_registering_create,
            validate_config: dummy_validate,
        };

        let (ctx, registry) = test_extension_ctx();
        let entities_before = registry.entity_count();
        let metrics_before = registry.metric_set_count();
        let user_config = Arc::new(ExtensionUserConfig::with_type(ExtensionUrn::from(
            "urn:otel:extension:test_ext",
        )));
        let ext_config = ExtensionConfig::with_control_channel_capacity("test_ext", 16);

        let result = (factory.create)(&ctx, "test_ext".into(), user_config, &ext_config);
        assert!(result.is_err());
        assert_eq!(registry.entity_count(), entities_before + 1);

        let entity_key = REGISTERED_ENTITY
            .with(|cell| cell.take())
            .expect("factory should have registered an entity via ext_ctx");
        let _metrics = ctx.register_metric_set_for_entity::<FactoryTestMetrics>(entity_key);
        assert_eq!(registry.metric_set_count(), metrics_before + 1);
    }
}