rvoip-sip 0.3.8

SIP umbrella for RVoIP: api/* (UnifiedCoordinator, StreamPeer, CallbackPeer, Endpoint), server/* (B2BUA helpers), adapter/* (rvoip-core::ConnectionAdapter impl)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
//! Lower-level session orchestration API.
//!
//! [`UnifiedCoordinator`] is the shared engine underneath [`StreamPeer`] and
//! [`CallbackPeer`]. It exposes explicit [`SessionId`] values and direct
//! methods for call creation, incoming-call resolution, registration
//! lifecycle management, event subscription, transfer primitives, audio
//! bridging, and media control.
//!
//! Use this module directly when you are building an application framework on
//! top of `rvoip-sip`: B2BUA logic, gateways, carrier-facing services,
//! custom peer abstractions, or multi-leg call orchestration. It is also the
//! surface that exposes deterministic registration shutdown and metadata such
//! as registrar-accepted expiry, refresh timing, Service-Route, and GRUU. For
//! ordinary client/test code, [`StreamPeer`] is usually more ergonomic. For
//! reactive server endpoints, [`CallbackPeer`] is usually the better starting
//! point.
//!
//! Outbound calls flow through one builder, [`UnifiedCoordinator::invite`],
//! with chainable modifiers — `.with_credentials(...)` for per-call digest
//! auth, `.with_pai(...)` for per-call `P-Asserted-Identity`, and
//! `.with_extra_headers(...)` for caller-supplied typed headers on the
//! first INVITE. Terminate the chain with `.send()`.
//!
//! # Example
//!
//! ```rust,no_run
//! use rvoip_sip::{Config, Event, Result, UnifiedCoordinator};
//!
//! # async fn example() -> Result<()> {
//! let coordinator = UnifiedCoordinator::new(Config::local("app", 5060)).await?;
//! let mut events = coordinator.events().await?;
//!
//! let call_id = coordinator
//!     .invite(Some("sip:app@127.0.0.1:5060".to_string()), "sip:bob@127.0.0.1:5070")
//!     .send()
//!     .await?;
//!
//! while let Some(event) = events.next().await {
//!     match event {
//!         Event::CallAnswered { call_id: id, .. } if id == call_id => {
//!             coordinator.send_dtmf(&call_id, '1').await?;
//!             coordinator.hangup(&call_id).await?;
//!         }
//!         Event::CallEnded { call_id: id, .. } if id == call_id => break,
//!         Event::CallFailed { call_id: id, .. } if id == call_id => break,
//!         _ => {}
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! [`CallbackPeer`]: crate::api::callback_peer::CallbackPeer
//! [`StreamPeer`]: crate::api::stream_peer::StreamPeer

#![deny(missing_docs)]

use crate::adapters::dialog_adapter::StandaloneRequestOptions;
use crate::adapters::{CausalDialogToSessionIngress, DialogAdapter, MediaAdapter};
use crate::api::lifecycle::{
    CallLifecycleSnapshot, ExactTerminalClaim, ExactTerminalCompletion, LifecycleIndex,
    SessionEventPublisher,
};
use crate::auth::SipClientAuth;
use crate::errors::{Result, SessionError};
use crate::retained_tasks::RetainedTasks;
use crate::session_lifecycle::{SessionLeaseAuthority, TeardownOutcome};
use crate::session_registry::{PendingInboundBundle, SessionRegistry, SessionRegistryHandle};
use crate::session_store::SessionStore;
use crate::state_machine::{ProcessEventResult, StateMachine, StateMachineHelpers};
use crate::state_table::types::{Action, EventType, Role, SessionId};
use crate::types::CallState;
use crate::types::{IncomingCallInfo, SessionInfo};
// Callback system removed - using event-driven approach
use futures::FutureExt;
use rvoip_infra_common::events::coordinator::GlobalEventCoordinator;
use rvoip_media_core::types::AudioFrame;
use rvoip_rtp_core::transport::{
    DEFAULT_RTP_PORT_RANGE_END, DEFAULT_RTP_PORT_RANGE_START, MIN_PORT,
};
use rvoip_sip_core::types::sdp::CryptoSuite;
use rvoip_sip_core::types::{headers::HeaderAccess, headers::HeaderName, Method};
use rvoip_sip_core::{Request, Response};
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::net::{IpAddr, SocketAddr};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex as StdMutex, OnceLock, Weak};
use std::time::{Duration, Instant};
use tokio::sync::{mpsc, RwLock};

pub use rvoip_media_core::relay::controller::{
    AudioSource, BridgeError, BridgeHandle, MediaSessionControllerConfig,
};
pub use rvoip_rtp_core::transport::SymmetricRtpPolicy;
pub use rvoip_rtp_core::{RtpSessionBufferConfig, RtpTransportBufferConfig};
pub use rvoip_sip_dialog::api::RelUsage;

const MAX_INBOUND_INVITE_OBSERVERS: usize = 16;
const OUTBOUND_DISPATCH_JOIN_FAILURE: &str = "SIP outbound dispatch task failed (class=join)";

type OutboundDispatchResult =
    std::result::Result<ProcessEventResult, Box<dyn std::error::Error + Send + Sync>>;

fn map_state_machine_dispatch_error(
    error: Box<dyn std::error::Error + Send + Sync>,
) -> SessionError {
    match error.downcast::<SessionError>() {
        Ok(error) => *error,
        Err(_) => SessionError::InternalError(
            "SIP outbound dispatch failed (class=state-machine)".to_string(),
        ),
    }
}

/// Owns a spawned outbound state-machine dispatch until it is joined.
///
/// The state-machine to dialog to transport poll chain is intentionally run
/// from the root of a fresh Tokio task. Keeping this abort-on-drop owner around
/// the join preserves cancellation semantics instead of detaching signaling
/// work when the public builder future is cancelled.
struct AbortOutboundDispatchTaskOnDrop {
    handle: tokio::task::JoinHandle<OutboundDispatchResult>,
    stage_claim: Option<Arc<crate::state_machine::executor::StageDispatchClaim>>,
    armed: bool,
}

#[cfg(test)]
mod guarded_outbound_dispatch_tests {
    use super::{
        map_state_machine_dispatch_error, AbortOutboundDispatchTaskOnDrop, OutboundDispatchResult,
    };
    use crate::errors::SessionError;
    use crate::session_store::SessionState;
    use crate::state_machine::executor::{
        PendingOptionsSlot, ProcessEventResult, StageDispatchClaim,
    };
    use crate::state_table::{Role, SessionId};
    use crate::types::CallState;
    use std::sync::Arc;
    use std::time::Duration;

    #[test]
    fn outbound_dispatch_preserves_typed_conflict() {
        let error = map_state_machine_dispatch_error(Box::new(SessionError::Conflict {
            method: rvoip_sip_core::Method::Info,
        }));
        assert!(matches!(
            error,
            SessionError::Conflict {
                method: rvoip_sip_core::Method::Info
            }
        ));
    }

    #[test]
    fn outbound_dispatch_redacts_unknown_state_machine_error() {
        let error =
            map_state_machine_dispatch_error("lower-layer request and credential detail".into());
        assert!(matches!(
            error,
            SessionError::InternalError(detail)
                if detail == "SIP outbound dispatch failed (class=state-machine)"
        ));
    }

    fn completed_dispatch() -> OutboundDispatchResult {
        Ok(ProcessEventResult {
            old_state: CallState::Active,
            next_state: None,
            transition: None,
            actions_executed: Vec::new(),
            events_published: Vec::new(),
        })
    }

    fn info_claim(session: &mut SessionState) -> Arc<StageDispatchClaim> {
        let options = Arc::new(rvoip_sip_dialog::api::unified::InfoRequestOptions::default());
        session.pending_info_options = Some(Arc::clone(&options));
        Arc::new(StageDispatchClaim::new(PendingOptionsSlot::Info(options)))
    }

    #[tokio::test]
    async fn dropping_public_dispatch_before_claim_aborts_task() {
        let mut session = SessionState::new(
            SessionId("public-cancel-before-claim".to_string()),
            Role::UAC,
        );
        let claim = info_claim(&mut session);
        let (sent, received) = tokio::sync::oneshot::channel();
        let task = tokio::spawn(async move {
            tokio::task::yield_now().await;
            let _ = sent.send(());
            completed_dispatch()
        });
        let owner = AbortOutboundDispatchTaskOnDrop::with_stage_claim(task, claim);
        drop(owner);

        assert!(
            tokio::time::timeout(Duration::from_secs(1), received)
                .await
                .expect("aborted task retained its sender")
                .is_err(),
            "pre-claim cancellation must abort the spawned dispatch"
        );
    }

    #[tokio::test]
    async fn dropping_public_dispatch_after_claim_detaches_task() {
        let mut session = SessionState::new(
            SessionId("public-cancel-after-claim".to_string()),
            Role::UAC,
        );
        let claim = info_claim(&mut session);
        claim.claim_exact(&mut session).unwrap();
        let (sent, received) = tokio::sync::oneshot::channel();
        let task = tokio::spawn(async move {
            tokio::task::yield_now().await;
            let _ = sent.send(());
            completed_dispatch()
        });
        let owner = AbortOutboundDispatchTaskOnDrop::with_stage_claim(task, claim);
        drop(owner);

        tokio::time::timeout(Duration::from_secs(1), received)
            .await
            .expect("claimed dispatch was aborted")
            .expect("claimed dispatch dropped before its work completed");
    }
}

impl AbortOutboundDispatchTaskOnDrop {
    fn new(handle: tokio::task::JoinHandle<OutboundDispatchResult>) -> Self {
        Self {
            handle,
            stage_claim: None,
            armed: true,
        }
    }

    fn with_stage_claim(
        handle: tokio::task::JoinHandle<OutboundDispatchResult>,
        stage_claim: Arc<crate::state_machine::executor::StageDispatchClaim>,
    ) -> Self {
        Self {
            handle,
            stage_claim: Some(stage_claim),
            armed: true,
        }
    }

    async fn join(mut self) -> std::result::Result<OutboundDispatchResult, tokio::task::JoinError> {
        let result = (&mut self.handle).await;
        self.armed = false;
        result
    }
}

impl Drop for AbortOutboundDispatchTaskOnDrop {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        let abort = self
            .stage_claim
            .as_ref()
            .is_none_or(|claim| claim.cancel_before_claim());
        if abort {
            self.handle.abort();
        }
    }
}

/// Authenticated inbound INVITE material exposed only to internal adapter
/// observers before the public `IncomingCall` event is published. `request`
/// is absent when the compatibility event did not retain parseable raw bytes;
/// the authenticated principal is still delivered atomically in that case.
///
/// This deliberately bypasses `SessionRegistry::pending_incoming_request`,
/// whose compatibility slot is not keyed by session and therefore is unsafe
/// for concurrent call routing.
#[derive(Clone)]
pub(crate) struct InboundInviteObservation {
    pub(crate) session_id: SessionId,
    pub(crate) request: Option<Arc<Request>>,
    pub(crate) principal: Option<rvoip_core_traits::identity::AuthenticatedPrincipal>,
}

pub(crate) type InboundInviteObserver =
    Arc<dyn Fn(InboundInviteObservation) + Send + Sync + 'static>;

/// SIP TLS operating mode for signalling transports.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SipTlsMode {
    /// Disable SIP TLS transport.
    #[default]
    Disabled,
    /// Dial outbound TLS connections only. This is the normal mode for
    /// registering to an upstream proxy/B2BUA such as Asterisk; no local
    /// certificate/key is required.
    ClientOnly,
    /// Bind a SIP TLS listener only. Requires a local certificate/key.
    ServerOnly,
    /// Bind a listener and support outbound TLS dials. Requires a local
    /// certificate/key for the listener side.
    ClientAndServer,
}

/// How this UA expects SIP peers to reach the Contact it advertises.
///
/// This is intentionally separate from [`SipTlsMode`]. The TLS mode controls
/// sockets; the contact mode controls the SIP registration/routing contract.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum SipContactMode {
    /// Advertise a Contact address that peers can dial directly. For SIP TLS
    /// this normally means a local TLS listener and listener certificate/key.
    #[default]
    ReachableContact,
    /// RFC 5626 SIP Outbound: advertise outbound Contact parameters and
    /// receive inbound requests over the registered connection-oriented flow.
    RegisteredFlowRfc5626,
    /// Asterisk/PBX symmetric transport style: keep the registration flow
    /// alive and accept inbound requests on that flow without requiring the
    /// registrar to echo RFC 5626 Contact parameters.
    RegisteredFlowSymmetric,
}

/// Named SRTP suite offer policies for common PBX/carrier interop.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SrtpSuitePolicy {
    /// Conservative default: AES-128 CM suites, strongest auth tag first.
    Default,
    /// FreeSWITCH-compatible SDES policy: offer AES-256 CM and AES-128 CM
    /// suites in a deliberate preference order while avoiding AEAD-GCM until
    /// rtp-core supports it end to end.
    FreeSwitchCompatible,
}

/// Validation policy for Base64 key material in RFC 4568 `a=crypto` lines.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SdesBase64Mode {
    /// Accept canonical Base64 and the interoperable form that omits only the
    /// trailing `=` padding. All other malformed encodings and decoded-length
    /// mismatches remain errors.
    #[default]
    Compatible,
    /// Require the canonical RFC 4648 representation, including any trailing
    /// `=` padding required by the selected SDES suite.
    Strict,
}

impl SrtpSuitePolicy {
    /// Suites to advertise for this policy, in local preference order.
    pub fn suites(self) -> Vec<CryptoSuite> {
        match self {
            Self::Default => vec![
                CryptoSuite::AesCm128HmacSha1_80,
                CryptoSuite::AesCm128HmacSha1_32,
            ],
            Self::FreeSwitchCompatible => vec![
                CryptoSuite::AesCm256HmacSha1_80,
                CryptoSuite::AesCm128HmacSha1_80,
                CryptoSuite::AesCm256HmacSha1_32,
                CryptoSuite::AesCm128HmacSha1_32,
            ],
        }
    }
}

/// Media allocation behavior for SIP sessions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MediaMode {
    /// Allocate media-core RTP sessions and RTP ports normally.
    Enabled,
    /// Skip media-core RTP allocation while still emitting SDP.
    ///
    /// The configured `sdp_rtp_port` is advertised unless
    /// [`Config::media_public_addr`] carries a nonzero port, in which case the
    /// explicit public media port is advertised.
    SignalingOnly {
        /// RTP port to advertise in SDP when no public media port override is set.
        sdp_rtp_port: u16,
    },
}

/// SIP media NAT behavior kept as a source-compatible sidecar to [`Config`].
///
/// Existing `Config` struct literals and constructors remain unchanged. Use
/// [`UnifiedCoordinator::new_with_nat`] when overriding the secure default.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct SipNatConfig {
    /// Bounded source-learning/rebinding policy for RTP destinations.
    pub symmetric_rtp: SymmetricRtpPolicy,
}

impl SipNatConfig {
    /// Replace the default bounded symmetric-RTP policy.
    pub const fn with_symmetric_rtp_policy(mut self, policy: SymmetricRtpPolicy) -> Self {
        self.symmetric_rtp = policy;
        self
    }

    fn validate(self) -> Result<()> {
        self.symmetric_rtp
            .validate()
            .map_err(|detail| SessionError::ConfigError(detail.to_string()))
    }
}

/// Construction-time options that cannot be added to the literal-friendly
/// [`Config`] struct without breaking existing 0.3.x callers.
///
/// The default preserves the existing bounded NAT policy and accepts canonical
/// SDES Base64 plus the interoperable form that omits trailing padding.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct SipRuntimeConfig {
    nat: SipNatConfig,
    sdes_base64_mode: SdesBase64Mode,
}

impl SipRuntimeConfig {
    /// Replace the SIP/RTP NAT policy.
    pub const fn with_nat(mut self, nat: SipNatConfig) -> Self {
        self.nat = nat;
        self
    }

    /// Select the inbound RFC 4568 SDES Base64 validation policy.
    ///
    /// Outbound SDP remains canonical in both modes.
    pub const fn with_sdes_base64_mode(mut self, mode: SdesBase64Mode) -> Self {
        self.sdes_base64_mode = mode;
        self
    }

    /// Return the configured SIP/RTP NAT policy.
    pub const fn nat(self) -> SipNatConfig {
        self.nat
    }

    /// Return the configured inbound SDES Base64 policy.
    pub const fn sdes_base64_mode(self) -> SdesBase64Mode {
        self.sdes_base64_mode
    }
}

#[derive(Debug, Clone, Copy)]
enum SetupTeardownTimeoutTerminal {
    Cancelled,
    Failed,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum SetupTeardownWatchdogKind {
    AcceptedCall,
    AcceptedCallWithSdp,
    Cancellation,
    OutboundSetup,
    InboundSetup,
}

impl SetupTeardownWatchdogKind {
    fn watched_states(self) -> &'static [CallState] {
        match self {
            Self::AcceptedCall | Self::AcceptedCallWithSdp => {
                &[CallState::Answering, CallState::AnsweringHangupPending]
            }
            Self::Cancellation => &[CallState::CancelPending, CallState::Cancelling],
            Self::OutboundSetup => &[CallState::Initiating],
            Self::InboundSetup => &[
                CallState::Ringing,
                CallState::Answering,
                CallState::AnsweringHangupPending,
            ],
        }
    }

    fn reason(self) -> &'static str {
        match self {
            Self::AcceptedCall => "UAS accepted call did not receive ACK",
            Self::AcceptedCallWithSdp => "UAS accepted call with SDP did not receive ACK",
            Self::Cancellation => "UAC cancellation did not receive terminal INVITE outcome",
            Self::OutboundSetup => "UAC INVITE did not receive a final setup outcome",
            Self::InboundSetup => "UAS INVITE did not receive a final setup outcome",
        }
    }

    fn terminal(self) -> SetupTeardownTimeoutTerminal {
        match self {
            Self::Cancellation => SetupTeardownTimeoutTerminal::Cancelled,
            Self::AcceptedCall
            | Self::AcceptedCallWithSdp
            | Self::OutboundSetup
            | Self::InboundSetup => SetupTeardownTimeoutTerminal::Failed,
        }
    }
}

/// One compact, generation-qualified timeout record. The old implementation
/// retained a full Tokio task (and a roughly 14 KiB async state machine) for
/// every armed call timeout. Records now share one coordinator scheduler and
/// instantiate the heavy timeout handler only when a deadline actually fires.
struct SetupTeardownDeadline {
    deadline: Instant,
    sequence: u64,
    handle: SessionRegistryHandle,
    entered_state_at: Instant,
    kind: SetupTeardownWatchdogKind,
}

impl PartialEq for SetupTeardownDeadline {
    fn eq(&self, other: &Self) -> bool {
        self.deadline == other.deadline && self.sequence == other.sequence
    }
}

impl Eq for SetupTeardownDeadline {}

impl PartialOrd for SetupTeardownDeadline {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SetupTeardownDeadline {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // BinaryHeap is a max-heap. Reverse both fields so the earliest
        // deadline, then the oldest insertion, is popped first.
        other
            .deadline
            .cmp(&self.deadline)
            .then_with(|| other.sequence.cmp(&self.sequence))
    }
}

struct SetupTeardownDeadlineQueue {
    deadlines: BinaryHeap<SetupTeardownDeadline>,
    live_sequences_by_lifetime: HashMap<SessionRegistryHandle, Vec<u64>>,
    cancelled_sequences: HashSet<u64>,
    closing_lifetimes: HashSet<SessionRegistryHandle>,
    next_sequence: u64,
    accepting: bool,
}

impl Default for SetupTeardownDeadlineQueue {
    fn default() -> Self {
        Self {
            deadlines: BinaryHeap::new(),
            live_sequences_by_lifetime: HashMap::new(),
            cancelled_sequences: HashSet::new(),
            closing_lifetimes: HashSet::new(),
            next_sequence: 0,
            accepting: true,
        }
    }
}

impl SetupTeardownDeadlineQueue {
    fn push(
        &mut self,
        deadline: Instant,
        handle: SessionRegistryHandle,
        entered_state_at: Instant,
        kind: SetupTeardownWatchdogKind,
    ) -> bool {
        self.prune_cancelled_head();
        let previous = self.deadlines.peek().map(|entry| entry.deadline);
        let sequence = self.next_sequence;
        self.next_sequence = self.next_sequence.wrapping_add(1);
        self.live_sequences_by_lifetime
            .entry(handle.clone())
            .or_default()
            .push(sequence);
        self.deadlines.push(SetupTeardownDeadline {
            deadline,
            sequence,
            handle,
            entered_state_at,
            kind,
        });
        previous.is_none_or(|previous| deadline < previous)
    }

    fn next_deadline(&mut self) -> Option<Instant> {
        self.prune_cancelled_head();
        self.deadlines.peek().map(|entry| entry.deadline)
    }

    fn begin_lifetime_close(&mut self, handle: &SessionRegistryHandle) -> usize {
        self.closing_lifetimes.insert(handle.clone());
        let sequences = self
            .live_sequences_by_lifetime
            .remove(handle)
            .unwrap_or_default();
        let cancelled = sequences.len();
        self.cancelled_sequences.extend(sequences);
        self.prune_cancelled_records();
        cancelled
    }

    fn finish_lifetime_close(&mut self, handle: &SessionRegistryHandle) {
        self.closing_lifetimes.remove(handle);
    }

    fn is_lifetime_closing(&self, handle: &SessionRegistryHandle) -> bool {
        self.closing_lifetimes.contains(handle)
    }

    fn consume_live_sequence(&mut self, handle: &SessionRegistryHandle, sequence: u64) -> bool {
        let mut remove_lifetime = false;
        let found = self
            .live_sequences_by_lifetime
            .get_mut(handle)
            .is_some_and(|sequences| {
                let Some(index) = sequences.iter().position(|current| *current == sequence) else {
                    return false;
                };
                sequences.swap_remove(index);
                remove_lifetime = sequences.is_empty();
                true
            });
        if remove_lifetime {
            self.live_sequences_by_lifetime.remove(handle);
        }
        found
    }

    fn live_deadline_count(&self) -> usize {
        self.live_sequences_by_lifetime.values().map(Vec::len).sum()
    }

    fn prune_cancelled_head(&mut self) {
        while self
            .deadlines
            .peek()
            .is_some_and(|entry| self.cancelled_sequences.contains(&entry.sequence))
        {
            let cancelled = self
                .deadlines
                .pop()
                .expect("peeked cancelled setup timeout deadline");
            self.cancelled_sequences.remove(&cancelled.sequence);
        }
    }

    fn prune_cancelled_records(&mut self) {
        let live = self.live_deadline_count();
        if live == 0 {
            self.deadlines.clear();
            self.cancelled_sequences.clear();
            return;
        }
        self.prune_cancelled_head();
        // Rebuilding only after tombstones reach the number of live records
        // amortizes cancellation to O(1) while bounding retained heap storage
        // to less than twice the active deadline population.
        if self.cancelled_sequences.len() >= live {
            let cancelled = &self.cancelled_sequences;
            self.deadlines
                .retain(|entry| !cancelled.contains(&entry.sequence));
            self.cancelled_sequences.clear();
        }
    }

    fn take_due(&mut self, now: Instant, limit: usize) -> Vec<SetupTeardownDeadline> {
        let mut due = Vec::with_capacity(limit.min(self.deadlines.len()));
        while due.len() < limit
            && self
                .deadlines
                .peek()
                .is_some_and(|entry| entry.deadline <= now)
        {
            let entry = self.deadlines.pop().expect("peeked setup timeout deadline");
            if self.cancelled_sequences.remove(&entry.sequence) {
                continue;
            }
            if self.consume_live_sequence(&entry.handle, entry.sequence) {
                due.push(entry);
            }
        }
        due
    }

    fn drain(&mut self) -> Vec<SetupTeardownDeadline> {
        let mut live = Vec::with_capacity(self.live_deadline_count());
        while let Some(entry) = self.deadlines.pop() {
            if self.cancelled_sequences.remove(&entry.sequence) {
                continue;
            }
            if self.consume_live_sequence(&entry.handle, entry.sequence) {
                live.push(entry);
            }
        }
        self.live_sequences_by_lifetime.clear();
        self.cancelled_sequences.clear();
        self.closing_lifetimes.clear();
        live
    }
}

struct SetupTeardownDeadlineScheduler {
    queue: StdMutex<SetupTeardownDeadlineQueue>,
    /// Queue-order changes consumed exclusively by the single heap runner.
    changed: tokio::sync::Notify,
    /// One-shot close wakeup shared by optional long-sleep watchdogs.
    closed: tokio::sync::Notify,
    fire_slots: Arc<tokio::sync::Semaphore>,
    tasks: Arc<RetainedTasks>,
    session_store: OnceLock<Weak<SessionStore>>,
    #[cfg(test)]
    fire_test_gate: SetupTeardownFireTestGate,
    #[cfg(test)]
    runner_waiting_deadline: StdMutex<Option<Instant>>,
    #[cfg(test)]
    runner_waiting_changed: tokio::sync::Notify,
}

#[cfg(test)]
struct SetupTeardownFireTestGate {
    pause_next: std::sync::atomic::AtomicBool,
    started: tokio::sync::Semaphore,
    resume: tokio::sync::Semaphore,
}

#[cfg(test)]
impl Default for SetupTeardownFireTestGate {
    fn default() -> Self {
        Self {
            pause_next: std::sync::atomic::AtomicBool::new(false),
            started: tokio::sync::Semaphore::new(0),
            resume: tokio::sync::Semaphore::new(0),
        }
    }
}

impl Default for SetupTeardownDeadlineScheduler {
    fn default() -> Self {
        Self {
            queue: StdMutex::new(SetupTeardownDeadlineQueue::default()),
            changed: tokio::sync::Notify::new(),
            closed: tokio::sync::Notify::new(),
            fire_slots: Arc::new(tokio::sync::Semaphore::new(
                SETUP_TEARDOWN_TIMEOUT_CONCURRENCY,
            )),
            tasks: RetainedTasks::new(),
            session_store: OnceLock::new(),
            #[cfg(test)]
            fire_test_gate: SetupTeardownFireTestGate::default(),
            #[cfg(test)]
            runner_waiting_deadline: StdMutex::new(None),
            #[cfg(test)]
            runner_waiting_changed: tokio::sync::Notify::new(),
        }
    }
}

impl SetupTeardownDeadlineScheduler {
    fn attach_session_store(&self, session_store: &Arc<SessionStore>) {
        let _ = self.session_store.set(Arc::downgrade(session_store));
    }

    fn schedule(
        &self,
        deadline: Instant,
        handle: SessionRegistryHandle,
        entered_state_at: Instant,
        kind: SetupTeardownWatchdogKind,
    ) -> bool {
        let advances_deadline = {
            let mut queue = self
                .queue
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            let exact_lifetime_is_current = self
                .session_store
                .get()
                .and_then(Weak::upgrade)
                .is_none_or(|store| store.get_session_retained_snapshot_exact(&handle).is_ok());
            if !queue.accepting || queue.is_lifetime_closing(&handle) || !exact_lifetime_is_current
            {
                return false;
            }
            crate::cleanup_diag::record_setup_teardown_watchdog_armed();
            queue.push(deadline, handle, entered_state_at, kind)
        };
        if advances_deadline {
            self.changed.notify_one();
        }
        true
    }

    fn begin_lifetime_close(&self, handle: &SessionRegistryHandle) {
        let cancelled = self
            .queue
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .begin_lifetime_close(handle);
        for _ in 0..cancelled {
            crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
        }
        if cancelled != 0 {
            self.changed.notify_one();
        }
    }

    fn finish_lifetime_close(&self, handle: &SessionRegistryHandle) {
        self.queue
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .finish_lifetime_close(handle);
    }

    fn next_deadline_if_accepting(&self) -> Option<Option<Instant>> {
        let mut queue = self
            .queue
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        queue.accepting.then(|| queue.next_deadline())
    }

    fn take_due_if_accepting(
        &self,
        now: Instant,
        limit: usize,
    ) -> Option<Vec<SetupTeardownDeadline>> {
        let mut queue = self
            .queue
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        queue.accepting.then(|| queue.take_due(now, limit))
    }

    fn begin_close(&self) {
        {
            let mut queue = self
                .queue
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            queue.accepting = false;
        }
        self.tasks.close();
        self.changed.notify_waiters();
        self.closed.notify_waiters();
    }

    /// Admit owner-scoped lifecycle work through the lock-free retained-task
    /// fence. This is used by per-call paths such as hangup and media-idle
    /// supervision, so it must not contend on the deadline heap mutex.
    fn spawn_lifecycle_task(
        &self,
        future: impl std::future::Future<Output = ()> + Send + 'static,
    ) -> bool {
        self.tasks.spawn(future)
    }

    /// Admit a cold deadline-fire child after it has been removed from the
    /// heap. A close racing this admission rejects the child and the runner
    /// accounts the claimed deadline as disarmed.
    fn spawn_deadline_fire(
        &self,
        future: impl std::future::Future<Output = ()> + Send + 'static,
    ) -> bool {
        self.tasks.spawn(future)
    }

    fn is_accepting(&self) -> bool {
        self.queue
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .accepting
    }

    async fn sleep_or_closed(&self, duration: Duration) -> bool {
        let sleep = tokio::time::sleep(duration);
        tokio::pin!(sleep);
        let closed = self.closed.notified();
        tokio::pin!(closed);
        closed.as_mut().enable();
        if !self.is_accepting() {
            return false;
        }
        tokio::select! {
            _ = &mut sleep => true,
            _ = &mut closed => false,
        }
    }

    fn drain_queued(&self) -> Vec<SetupTeardownDeadline> {
        self.queue
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .drain()
    }

    async fn close_and_wait(&self, timeout: Duration) -> Result<()> {
        self.begin_close();
        if tokio::time::timeout(timeout, self.tasks.wait_idle())
            .await
            .is_err()
        {
            return Err(SessionError::InternalError(format!(
                "setup/teardown deadline scheduler drain timed out with {} retained tasks",
                self.tasks.count()
            )));
        }
        if self.tasks.panicked() {
            return Err(SessionError::InternalError(
                "setup/teardown deadline scheduler retained task panicked".to_string(),
            ));
        }
        Ok(())
    }

    #[cfg(test)]
    fn pause_next_fire_for_test(&self) {
        self.fire_test_gate
            .pause_next
            .store(true, Ordering::Release);
    }

    #[cfg(test)]
    async fn pause_if_requested_for_test(&self) {
        if !self.fire_test_gate.pause_next.swap(false, Ordering::AcqRel) {
            return;
        }
        self.fire_test_gate.started.add_permits(1);
        let permit = self
            .fire_test_gate
            .resume
            .acquire()
            .await
            .expect("setup/teardown fire test gate remains open");
        permit.forget();
    }

    #[cfg(test)]
    async fn wait_for_paused_fire_for_test(&self) {
        let permit = self
            .fire_test_gate
            .started
            .acquire()
            .await
            .expect("setup/teardown fire test gate remains open");
        permit.forget();
    }

    #[cfg(test)]
    fn resume_paused_fire_for_test(&self) {
        self.fire_test_gate.resume.add_permits(1);
    }

    #[cfg(test)]
    fn is_accepting_for_test(&self) -> bool {
        self.is_accepting()
    }

    #[cfg(test)]
    fn record_runner_waiting_for_test(&self, deadline: Instant) {
        *self
            .runner_waiting_deadline
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(deadline);
        self.runner_waiting_changed.notify_waiters();
    }

    #[cfg(test)]
    async fn wait_for_runner_deadline_for_test(&self, expected: Instant) {
        loop {
            let changed = self.runner_waiting_changed.notified();
            tokio::pin!(changed);
            changed.as_mut().enable();
            if *self
                .runner_waiting_deadline
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                == Some(expected)
            {
                return;
            }
            changed.await;
        }
    }

    #[cfg(test)]
    fn len(&self) -> usize {
        self.queue
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .live_deadline_count()
    }

    #[cfg(any(test, feature = "perf-tests"))]
    fn perf_diagnostic_counts(&self) -> serde_json::Value {
        let queue = self
            .queue
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let mut accepted_call = 0_usize;
        let mut accepted_call_with_sdp = 0_usize;
        let mut cancellation = 0_usize;
        let mut outbound_setup = 0_usize;
        let mut inbound_setup = 0_usize;
        for deadline in queue.deadlines.iter() {
            if queue.cancelled_sequences.contains(&deadline.sequence) {
                continue;
            }
            match deadline.kind {
                SetupTeardownWatchdogKind::AcceptedCall => accepted_call += 1,
                SetupTeardownWatchdogKind::AcceptedCallWithSdp => accepted_call_with_sdp += 1,
                SetupTeardownWatchdogKind::Cancellation => cancellation += 1,
                SetupTeardownWatchdogKind::OutboundSetup => outbound_setup += 1,
                SetupTeardownWatchdogKind::InboundSetup => inbound_setup += 1,
            }
        }
        serde_json::json!({
            "pending_deadlines": queue.live_deadline_count(),
            "retained_deadline_records": queue.deadlines.len(),
            "cancelled_deadline_records": queue.cancelled_sequences.len(),
            "closing_lifetimes": queue.closing_lifetimes.len(),
            "fire_in_flight": SETUP_TEARDOWN_TIMEOUT_CONCURRENCY
                .saturating_sub(self.fire_slots.available_permits()),
            "retained_tasks": self.tasks.count(),
            "retained_task_panicked": self.tasks.panicked(),
            "accepting": queue.accepting,
            "fire_concurrency_limit": SETUP_TEARDOWN_TIMEOUT_CONCURRENCY,
            "deadline_record_bytes": std::mem::size_of::<SetupTeardownDeadline>(),
            "pending_by_owner": {
                "accepted_call": accepted_call,
                "accepted_call_with_sdp": accepted_call_with_sdp,
                "cancellation": cancellation,
                "outbound_setup": outbound_setup,
                "inbound_setup": inbound_setup,
            },
        })
    }
}

/// Generation-scoped admission fence for setup/teardown deadlines during
/// exact terminal reclamation.
#[derive(Clone)]
pub(crate) struct SetupTeardownDeadlineCancellation {
    scheduler: Arc<SetupTeardownDeadlineScheduler>,
}

impl SetupTeardownDeadlineCancellation {
    fn begin_lifetime_close(&self, handle: &SessionRegistryHandle) {
        self.scheduler.begin_lifetime_close(handle);
    }

    fn finish_lifetime_close(&self, handle: &SessionRegistryHandle) {
        self.scheduler.finish_lifetime_close(handle);
    }
}

const SETUP_TEARDOWN_DEADLINE_BATCH: usize = 2_048;
const SETUP_TEARDOWN_TIMEOUT_CONCURRENCY: usize = 64;
const SETUP_TEARDOWN_SCHEDULER_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
const EXACT_RESPONSE_OWNER_DEADLINE: Duration = Duration::from_secs(5);
const EXACT_RESPONSE_RETRY_DELAY: Duration = Duration::from_millis(100);
const EXACT_RESPONSE_SLOW_RETRY_DELAY: Duration = Duration::from_secs(1);
const EXACT_RESPONSE_DEADLINE_BATCH: usize = 2_048;
const EXACT_RESPONSE_DEADLINE_CONCURRENCY: usize = 256;
const EXACT_RESPONSE_SEND_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(2);
const EXACT_RESPONSE_SHUTDOWN_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
const EXACT_RESPONSE_MAX_RETRIES: u8 = 10;

struct ExactResponseDeadline {
    deadline: Instant,
    sequence: u64,
    transaction: rvoip_sip_dialog::transaction::TransactionKey,
}

impl PartialEq for ExactResponseDeadline {
    fn eq(&self, other: &Self) -> bool {
        self.deadline == other.deadline && self.sequence == other.sequence
    }
}

impl Eq for ExactResponseDeadline {}

impl PartialOrd for ExactResponseDeadline {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ExactResponseDeadline {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        other
            .deadline
            .cmp(&self.deadline)
            .then_with(|| other.sequence.cmp(&self.sequence))
    }
}

struct ExactResponseDeadlineQueue {
    deadlines: BinaryHeap<ExactResponseDeadline>,
    next_sequence: u64,
    accepting: bool,
    closing_lifetimes: HashSet<SessionRegistryHandle>,
}

impl Default for ExactResponseDeadlineQueue {
    fn default() -> Self {
        Self {
            deadlines: BinaryHeap::new(),
            next_sequence: 0,
            accepting: true,
            closing_lifetimes: HashSet::new(),
        }
    }
}

/// Single-writer owners for generation-scoped INFO and standalone REGISTER
/// final responses.
pub(crate) struct PendingExactResponseRegistry {
    entries: dashmap::DashMap<
        rvoip_sip_dialog::transaction::TransactionKey,
        Arc<crate::api::incoming::ExactResponseObligation>,
    >,
    retry_attempts: dashmap::DashMap<rvoip_sip_dialog::transaction::TransactionKey, u8>,
    deadlines: StdMutex<ExactResponseDeadlineQueue>,
    changed: tokio::sync::Notify,
    fire_in_flight: Arc<AtomicUsize>,
    session_store: OnceLock<Weak<SessionStore>>,
}

struct ExactResponseFireGuard {
    fire_in_flight: Arc<AtomicUsize>,
}

impl Drop for ExactResponseFireGuard {
    fn drop(&mut self) {
        self.fire_in_flight.fetch_sub(1, Ordering::AcqRel);
    }
}

pub(crate) enum ExactResponseRegistration {
    Registered,
    Closed,
    Collision,
}

enum ManagedExactResponseOutcome {
    Completed,
    Busy,
    ZeroWireRetryable,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ExactResponseRetryCause {
    BusyOrTimeout,
    ZeroWire,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct ExactResponseRetryPlan {
    delay: Duration,
    slow_path: bool,
}

impl Default for PendingExactResponseRegistry {
    fn default() -> Self {
        Self {
            entries: dashmap::DashMap::new(),
            retry_attempts: dashmap::DashMap::new(),
            deadlines: StdMutex::new(ExactResponseDeadlineQueue::default()),
            changed: tokio::sync::Notify::new(),
            fire_in_flight: Arc::new(AtomicUsize::new(0)),
            session_store: OnceLock::new(),
        }
    }
}

impl PendingExactResponseRegistry {
    fn attach_session_store(&self, session_store: &Arc<SessionStore>) {
        let _ = self.session_store.set(Arc::downgrade(session_store));
    }

    fn begin_fire(&self) -> ExactResponseFireGuard {
        self.fire_in_flight.fetch_add(1, Ordering::AcqRel);
        ExactResponseFireGuard {
            fire_in_flight: Arc::clone(&self.fire_in_flight),
        }
    }

    fn register(
        &self,
        obligation: Arc<crate::api::incoming::ExactResponseObligation>,
    ) -> ExactResponseRegistration {
        if !obligation.has_owner_scope()
            || !obligation.transaction().is_server()
            || !(200..=699).contains(&obligation.fallback_status())
        {
            return ExactResponseRegistration::Collision;
        }
        let transaction = obligation.transaction().clone();
        let mut deadlines = self
            .deadlines
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let exact_lifetime_is_current = obligation.lifecycle_handle().is_none_or(|handle| {
            self.session_store
                .get()
                .and_then(Weak::upgrade)
                .is_some_and(|store| store.get_session_retained_snapshot_exact(handle).is_ok())
        });
        if !deadlines.accepting
            || !exact_lifetime_is_current
            || obligation
                .lifecycle_handle()
                .is_some_and(|handle| deadlines.closing_lifetimes.contains(handle))
        {
            return ExactResponseRegistration::Closed;
        }
        if let Some(existing) = self.entries.get(&transaction) {
            return if Arc::ptr_eq(existing.value(), &obligation) {
                ExactResponseRegistration::Registered
            } else {
                ExactResponseRegistration::Collision
            };
        }
        self.entries.insert(transaction.clone(), obligation);
        let previous = deadlines.deadlines.peek().map(|entry| entry.deadline);
        let deadline = Instant::now() + EXACT_RESPONSE_OWNER_DEADLINE;
        let sequence = deadlines.next_sequence;
        deadlines.next_sequence = deadlines.next_sequence.wrapping_add(1);
        deadlines.deadlines.push(ExactResponseDeadline {
            deadline,
            sequence,
            transaction,
        });
        drop(deadlines);
        if previous.is_none_or(|previous| deadline < previous) {
            self.changed.notify_one();
        }
        ExactResponseRegistration::Registered
    }

    fn remove_owner(&self, obligation: &crate::api::incoming::ExactResponseObligation) {
        let transaction = obligation.transaction();
        if self
            .entries
            .remove_if(transaction, |_, current| {
                std::ptr::eq(current.as_ref(), obligation)
            })
            .is_some()
        {
            self.retry_attempts.remove(transaction);
        }
    }

    fn retry_plan(
        &self,
        transaction: &rvoip_sip_dialog::transaction::TransactionKey,
        cause: ExactResponseRetryCause,
    ) -> ExactResponseRetryPlan {
        if cause == ExactResponseRetryCause::BusyOrTimeout {
            return ExactResponseRetryPlan {
                delay: EXACT_RESPONSE_RETRY_DELAY,
                slow_path: false,
            };
        }

        let mut attempts = self.retry_attempts.entry(transaction.clone()).or_insert(0);
        if *attempts < EXACT_RESPONSE_MAX_RETRIES {
            *attempts += 1;
            ExactResponseRetryPlan {
                delay: EXACT_RESPONSE_RETRY_DELAY,
                slow_path: false,
            }
        } else {
            ExactResponseRetryPlan {
                delay: EXACT_RESPONSE_SLOW_RETRY_DELAY,
                slow_path: true,
            }
        }
    }

    fn reschedule(
        &self,
        transaction: &rvoip_sip_dialog::transaction::TransactionKey,
        delay: Duration,
    ) {
        let mut deadlines = self
            .deadlines
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let Some(obligation) = self.entries.get(transaction) else {
            return;
        };
        let generation_is_closing = obligation
            .lifecycle_handle()
            .is_some_and(|handle| deadlines.closing_lifetimes.contains(handle));
        drop(obligation);
        if !deadlines.accepting || generation_is_closing {
            return;
        }
        let previous = deadlines.deadlines.peek().map(|entry| entry.deadline);
        let deadline = Instant::now() + delay;
        let sequence = deadlines.next_sequence;
        deadlines.next_sequence = deadlines.next_sequence.wrapping_add(1);
        deadlines.deadlines.push(ExactResponseDeadline {
            deadline,
            sequence,
            transaction: transaction.clone(),
        });
        drop(deadlines);
        if previous.is_none_or(|previous| deadline < previous) {
            self.changed.notify_one();
        }
    }

    fn next_deadline_if_accepting(&self) -> Option<Option<Instant>> {
        let deadlines = self
            .deadlines
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        deadlines
            .accepting
            .then(|| deadlines.deadlines.peek().map(|entry| entry.deadline))
    }

    fn take_due_if_accepting(
        &self,
        now: Instant,
        limit: usize,
    ) -> Option<Vec<rvoip_sip_dialog::transaction::TransactionKey>> {
        let mut deadlines = self
            .deadlines
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if !deadlines.accepting {
            return None;
        }
        let mut due = Vec::with_capacity(limit.min(deadlines.deadlines.len()));
        while due.len() < limit
            && deadlines
                .deadlines
                .peek()
                .is_some_and(|entry| entry.deadline <= now)
        {
            let entry = deadlines
                .deadlines
                .pop()
                .expect("peeked exact-response deadline");
            let eligible = self
                .entries
                .get(&entry.transaction)
                .is_some_and(|obligation| {
                    obligation.lifecycle_handle().map_or_else(
                        || obligation.has_owner_scope(),
                        |handle| !deadlines.closing_lifetimes.contains(handle),
                    )
                });
            if eligible {
                due.push(entry.transaction);
            }
        }
        Some(due)
    }

    fn obligation(
        &self,
        transaction: &rvoip_sip_dialog::transaction::TransactionKey,
    ) -> Option<Arc<crate::api::incoming::ExactResponseObligation>> {
        self.entries
            .get(transaction)
            .map(|entry| Arc::clone(entry.value()))
    }

    fn snapshot(&self) -> Vec<Arc<crate::api::incoming::ExactResponseObligation>> {
        self.entries
            .iter()
            .map(|entry| Arc::clone(entry.value()))
            .collect()
    }

    fn snapshot_lifetime(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Vec<Arc<crate::api::incoming::ExactResponseObligation>> {
        self.entries
            .iter()
            .filter(|entry| entry.value().lifecycle_handle() == Some(handle))
            .map(|entry| Arc::clone(entry.value()))
            .collect()
    }

    fn begin_lifetime_close(&self, handle: &SessionRegistryHandle) {
        self.deadlines
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .closing_lifetimes
            .insert(handle.clone());
        self.changed.notify_waiters();
    }

    fn finish_lifetime_close(&self, handle: &SessionRegistryHandle) {
        self.deadlines
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .closing_lifetimes
            .remove(handle);
    }

    async fn drain_lifetime(
        &self,
        handle: &SessionRegistryHandle,
        dialog_adapter: &DialogAdapter,
    ) -> Result<()> {
        let deadline = Instant::now() + EXACT_RESPONSE_SHUTDOWN_DRAIN_TIMEOUT;
        loop {
            let pending = self.snapshot_lifetime(handle);
            if pending.is_empty() {
                return Ok(());
            }
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Err(SessionError::InternalError(format!(
                    "exact response lifetime drain timed out for {} with {} pending obligations",
                    handle.session_id(),
                    pending.len()
                )));
            }
            let attempt_timeout = remaining.min(EXACT_RESPONSE_SEND_ATTEMPT_TIMEOUT);
            let batch = run_bounded_exact_response_batch(
                pending,
                EXACT_RESPONSE_DEADLINE_CONCURRENCY,
                |obligation| async move {
                    let _fire = self.begin_fire();
                    let owner = Arc::clone(&obligation);
                    if matches!(
                        tokio::time::timeout(
                            attempt_timeout,
                            author_pending_exact_response_with_adapter(
                                dialog_adapter,
                                obligation,
                                503,
                            ),
                        )
                        .await,
                        Ok(ManagedExactResponseOutcome::Completed)
                    ) {
                        // `ExactResponseClaim::complete` normally removes via
                        // the coordinator weak reference. Exact teardown also
                        // removes directly so draining remains correct while
                        // the coordinator itself is being released.
                        self.remove_owner(owner.as_ref());
                    }
                },
            );
            let _ = tokio::time::timeout(remaining, batch).await;
            if self.snapshot_lifetime(handle).is_empty() {
                return Ok(());
            }
            if Instant::now() >= deadline {
                return Err(SessionError::InternalError(format!(
                    "exact response lifetime drain timed out for {} with pending obligations",
                    handle.session_id()
                )));
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    }

    fn begin_close(&self) {
        self.deadlines
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .accepting = false;
        self.changed.notify_waiters();
    }

    fn clear(&self) {
        self.entries.clear();
        self.retry_attempts.clear();
        let mut deadlines = self
            .deadlines
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        deadlines.deadlines.clear();
        deadlines.closing_lifetimes.clear();
    }

    #[cfg(any(test, feature = "perf-tests"))]
    fn perf_diagnostic_counts(&self) -> serde_json::Value {
        let deadlines = self
            .deadlines
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        serde_json::json!({
            "pending_obligations": self.entries.len(),
            "retry_attempts": self.retry_attempts.len(),
            "pending_deadlines": deadlines.deadlines.len(),
            "closing_lifetimes": deadlines.closing_lifetimes.len(),
            "fire_in_flight": self.fire_in_flight.load(Ordering::Acquire),
            "accepting": deadlines.accepting,
            "fire_concurrency_limit": EXACT_RESPONSE_DEADLINE_CONCURRENCY,
            "deadline_record_bytes": std::mem::size_of::<ExactResponseDeadline>(),
        })
    }

    #[cfg(test)]
    fn len(&self) -> usize {
        self.entries.len()
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CoordinatorShutdownOutcome {
    Succeeded,
    RegistrationRefreshDrainFailed,
    ExactResponseDrainFailed,
    SchedulerDrainFailed,
    DialogStopFailed,
    DriverPanicked,
}

impl CoordinatorShutdownOutcome {
    fn into_result(self) -> Result<()> {
        match self {
            Self::Succeeded => Ok(()),
            Self::RegistrationRefreshDrainFailed => Err(SessionError::InternalError(
                "coordinator shutdown failed (class=registration-refresh-drain)".to_string(),
            )),
            Self::ExactResponseDrainFailed => Err(SessionError::InternalError(
                "coordinator shutdown failed (class=exact-response-drain)".to_string(),
            )),
            Self::SchedulerDrainFailed => Err(SessionError::InternalError(
                "coordinator shutdown failed (class=setup-teardown-scheduler-drain)".to_string(),
            )),
            Self::DialogStopFailed => Err(SessionError::InternalError(
                "coordinator shutdown failed (class=dialog-stop)".to_string(),
            )),
            Self::DriverPanicked => Err(SessionError::InternalError(
                "coordinator shutdown failed (class=driver-panicked)".to_string(),
            )),
        }
    }
}

struct CoordinatorShutdownAttempt {
    outcome: StdMutex<Option<CoordinatorShutdownOutcome>>,
    completed: tokio::sync::Notify,
}

impl CoordinatorShutdownAttempt {
    fn new() -> Arc<Self> {
        Arc::new(Self {
            outcome: StdMutex::new(None),
            completed: tokio::sync::Notify::new(),
        })
    }

    fn outcome(&self) -> Option<CoordinatorShutdownOutcome> {
        *self
            .outcome
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn finish(&self, outcome: CoordinatorShutdownOutcome) {
        let mut slot = self
            .outcome
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if slot.is_some() {
            return;
        }
        *slot = Some(outcome);
        drop(slot);
        self.completed.notify_waiters();
    }

    async fn wait(&self) -> CoordinatorShutdownOutcome {
        loop {
            let completed = self.completed.notified();
            tokio::pin!(completed);
            completed.as_mut().enable();
            if let Some(outcome) = self.outcome() {
                return outcome;
            }
            completed.await;
        }
    }
}

#[derive(Default)]
struct CoordinatorShutdownFlights {
    current: StdMutex<Option<Arc<CoordinatorShutdownAttempt>>>,
}

impl CoordinatorShutdownFlights {
    fn begin(&self) -> (Arc<CoordinatorShutdownAttempt>, bool) {
        let mut current = self
            .current
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if let Some(attempt) = current.as_ref() {
            match attempt.outcome() {
                None | Some(CoordinatorShutdownOutcome::Succeeded) => {
                    return (Arc::clone(attempt), false);
                }
                Some(
                    CoordinatorShutdownOutcome::RegistrationRefreshDrainFailed
                    | CoordinatorShutdownOutcome::ExactResponseDrainFailed
                    | CoordinatorShutdownOutcome::SchedulerDrainFailed
                    | CoordinatorShutdownOutcome::DialogStopFailed
                    | CoordinatorShutdownOutcome::DriverPanicked,
                ) => {}
            }
        }
        let attempt = CoordinatorShutdownAttempt::new();
        *current = Some(Arc::clone(&attempt));
        (attempt, true)
    }
}

struct CoordinatorConstructionGuard {
    coordinator: Option<Arc<UnifiedCoordinator>>,
}

struct CausalIngressConstructionGuard {
    ingress: Option<CausalDialogToSessionIngress>,
}

impl CausalIngressConstructionGuard {
    fn new(ingress: CausalDialogToSessionIngress) -> Self {
        Self {
            ingress: Some(ingress),
        }
    }

    fn disarm(&mut self) {
        self.ingress = None;
    }
}

impl Drop for CausalIngressConstructionGuard {
    fn drop(&mut self) {
        if let Some(ingress) = self.ingress.take() {
            ingress.close_pending();
        }
    }
}

impl CoordinatorConstructionGuard {
    fn new(coordinator: Arc<UnifiedCoordinator>) -> Self {
        Self {
            coordinator: Some(coordinator),
        }
    }

    fn disarm(&mut self) {
        self.coordinator = None;
    }
}

impl Drop for CoordinatorConstructionGuard {
    fn drop(&mut self) {
        if let Some(coordinator) = self.coordinator.take() {
            // Constructor cancellation cannot perform async cleanup in Drop.
            // Start the same cancellation-safe ordered shutdown driver used by
            // public shutdown; its retained Arc owns partial dependencies until
            // cleanup reaches a terminal outcome.
            coordinator.shutdown();
        }
    }
}

#[cfg(test)]
fn exact_terminal_completion_result(completion: ExactTerminalCompletion) -> Result<()> {
    match completion {
        ExactTerminalCompletion::Released => Ok(()),
        ExactTerminalCompletion::ReleaseFailed => Err(SessionError::InternalError(
            "exact terminal resource release failed".to_string(),
        )),
        ExactTerminalCompletion::OwnerDropped => Err(SessionError::InternalError(
            "exact terminal release owner stopped before completion".to_string(),
        )),
    }
}

/// Resolve an established local-BYE dispatch against its authoritative wire
/// confirmation. A post-send state/lifecycle race may make dispatch report an
/// error even though the adapter retained the exact new transaction. Only
/// that concrete side effect permits joining confirmation; without it the
/// original dispatch error remains authoritative. Confirmation still fails
/// closed on non-2xx, timeout, and an unobservable transaction.
async fn complete_established_bye_dispatch<F>(
    dispatch: Result<()>,
    retained_new_bye: bool,
    confirmation: F,
) -> Result<()>
where
    F: std::future::Future<Output = Result<()>>,
{
    match dispatch {
        Ok(()) => confirmation.await,
        Err(_) if retained_new_bye => confirmation.await,
        Err(error) => Err(error),
    }
}

/// Committed session-lifecycle result for one exact outbound BYE wire
/// completion.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum LocalByeLifecycleCommit {
    Ended,
    Cancelled,
    AlreadyReleased,
}

fn local_bye_terminal_kind(state: CallState) -> LocalByeLifecycleCommit {
    if matches!(
        state,
        CallState::CancelPending | CallState::Cancelling | CallState::Cancelled
    ) {
        LocalByeLifecycleCommit::Cancelled
    } else {
        LocalByeLifecycleCommit::Ended
    }
}

/// Feed an exact outbound-BYE transaction outcome into the YAML lifecycle.
///
/// The transaction layer owns response correlation and authentication retry;
/// this helper owns only the application-visible state transition. It is safe
/// for both the causal completion handler and a public waiter to call: the
/// per-session executor lane admits one transition, while a later caller sees
/// the already-final state or the already-released exact lifetime.
pub(crate) async fn commit_local_bye_lifecycle_exact(
    state_machine: Arc<StateMachine>,
    handle: &SessionRegistryHandle,
) -> Result<LocalByeLifecycleCommit> {
    if state_machine
        .store
        .get_session_snapshot_exact(handle)
        .is_err()
    {
        return Ok(LocalByeLifecycleCommit::AlreadyReleased);
    }
    let task_handle = handle.clone();
    let task_state_machine = Arc::clone(&state_machine);
    let task = AbortOutboundDispatchTaskOnDrop::new(tokio::spawn(async move {
        task_state_machine
            .process_event_exact(&task_handle, EventType::DialogTerminated)
            .await
    }));
    let result = match task.join().await {
        Ok(Ok(result)) => result,
        Ok(Err(error)) => {
            let error = SessionError::from(error);
            let current = state_machine.store.get_session_snapshot_exact(handle).ok();
            let Some(current) = current else {
                return Ok(LocalByeLifecycleCommit::AlreadyReleased);
            };
            if current.call_state.is_final() {
                tracing::debug!(
                    session = %handle.session_id(),
                    %error,
                    state = ?current.call_state,
                    "local BYE transition reached a terminal state before an action error"
                );
                return Ok(local_bye_terminal_kind(current.call_state));
            }
            return Err(error);
        }
        Err(_) => {
            return Err(SessionError::InternalError(
                "local BYE lifecycle dispatch task failed (class=join)".to_string(),
            ));
        }
    };

    let committed_state = result.next_state.unwrap_or(result.old_state);
    if result.transition.is_none() && !result.old_state.is_final() {
        return Err(SessionError::InvalidTransition(format!(
            "outbound BYE completion has no lifecycle transition from {:?}",
            result.old_state
        )));
    }
    if !committed_state.is_final() {
        return Err(SessionError::InvalidTransition(format!(
            "outbound BYE completion remained in non-terminal state {:?}",
            committed_state
        )));
    }

    Ok(local_bye_terminal_kind(committed_state))
}

fn shared_hangup_completion_result(succeeded: bool) -> Result<()> {
    if succeeded {
        Ok(())
    } else {
        Err(SessionError::InvalidTransition(
            "the exact hangup operation failed".to_string(),
        ))
    }
}

struct RetainedHangupTaskCompletion {
    control: Arc<crate::session_store::state::SessionHangupControl>,
    finished: bool,
}

impl RetainedHangupTaskCompletion {
    fn new(control: Arc<crate::session_store::state::SessionHangupControl>) -> Self {
        Self {
            control,
            finished: false,
        }
    }

    fn finish(&mut self, succeeded: bool) {
        self.control.finish(succeeded);
        self.finished = true;
    }
}

impl Drop for RetainedHangupTaskCompletion {
    fn drop(&mut self) {
        if !self.finished {
            self.control.finish(false);
        }
    }
}

/// Runtime configuration for [`UnifiedCoordinator`].
///
/// `Config` controls SIP and media binding, advertised addresses, TLS,
/// registration Contact behavior, registration refresh/unregister policy, SRTP
/// policy, session timers, reliable provisionals, caller identity headers,
/// outbound proxy routing for INVITEs and REGISTERs, NAT/media address
/// discovery, and codec negotiation.
///
/// Start with [`Config::local`] for loopback examples, [`Config::on`] for a
/// specific LAN/host address, then adjust the feature-specific fields for the
/// deployment profile. The profile constructors are conservative starting
/// points for common interop targets; they do not imply carrier certification
/// or full RFC 5626 multi-flow behavior.
///
/// # Examples
///
/// ```rust
/// use rvoip_sip::{Config, SipContactMode, SipTlsMode};
///
/// let lan = Config::on("alice", "192.168.1.50".parse().unwrap(), 5060);
/// assert_eq!(lan.local_uri, "sip:alice@192.168.1.50:5060");
///
/// let tls_registered = Config::local("alice", 5060)
///     .tls_registered_flow_symmetric("urn:uuid:00000000-0000-0000-0000-000000000001");
/// assert_eq!(tls_registered.sip_tls_mode, SipTlsMode::ClientOnly);
/// assert_eq!(
///     tls_registered.sip_contact_mode,
///     SipContactMode::RegisteredFlowSymmetric
/// );
/// ```
#[derive(Clone)]
pub struct Config {
    /// Local IP address for media
    pub local_ip: IpAddr,
    /// SIP port
    pub sip_port: u16,
    /// Starting port for media
    pub media_port_start: u16,
    /// Ending port for media
    pub media_port_end: u16,
    /// Requested media port range capacity when configured by capacity.
    ///
    /// `None` means the explicit start/end range is authoritative. When set,
    /// validation checks that the configured range can satisfy the requested
    /// number of RTP ports.
    pub media_port_capacity: Option<usize>,
    /// Bind address for SIP
    pub bind_addr: SocketAddr,
    /// Optional advertised address for SIP Via sent-by and fallback Contact
    /// generation. This is distinct from [`Config::bind_addr`]: bind can be
    /// `0.0.0.0`, while the advertised address must name a concrete interface.
    pub sip_advertised_addr: Option<SocketAddr>,
    /// Optional path to custom state table YAML
    /// Priority: 1) this config path, 2) embedded default
    pub state_table_path: Option<String>,
    /// Local SIP URI (e.g., "sip:alice@127.0.0.1:5060")
    pub local_uri: String,
    /// Policy for RFC 3262 `100rel` reliable provisionals on outgoing INVITE.
    ///
    /// Default is `Supported` — advertise capability without demanding it,
    /// which is the safe setting for interop and unchanged wire behavior.
    /// Set to `Required` when connecting to a carrier that mandates 100rel,
    /// or `NotSupported` to omit the tag entirely.
    pub use_100rel: RelUsage,

    /// Whether the default inbound INVITE path sends automatic `180 Ringing`.
    ///
    /// Default: `true`, which is appropriate for PBX-style ringing behavior
    /// and preserves previous API behavior. Set to `false` for IVR,
    /// contact-center, and auto-answer services that immediately send a final
    /// response and do not need the extra provisional response.
    pub auto_180_ringing: bool,

    /// Whether INVITE server transactions arm the automatic RFC 3261
    /// `100 Trying` timer.
    ///
    /// Default: `true`, which preserves RFC-friendly behavior for ordinary
    /// endpoints. Set to `false` only for fixed fast-answer services that
    /// immediately send a final response and do not need one timer task per
    /// inbound INVITE.
    pub auto_100_trying: bool,

    /// Whether inbound INVITEs are accepted immediately in the session event
    /// path before application callback dispatch.
    ///
    /// Default: `false`, preserving normal app-controlled accept/reject/defer
    /// behavior. Set to `true` only for fixed auto-answer services and
    /// high-CPS benchmarks where the app callback must not sit on the first
    /// final response path.
    pub fast_auto_accept_incoming_calls: bool,

    /// Maximum seconds a locally-initiated setup teardown state may wait for
    /// its matching dialog event before rvoip-sip synthesizes the existing
    /// `DialogTimeout` transition and releases local resources.
    ///
    /// This bounds UAC pre-answer cancellation (`CancelPending`/`Cancelling`)
    /// and UAS accepted-but-unacked calls (`Answering`/
    /// `AnsweringHangupPending`). `0` disables the watchdog. Default: `120`.
    pub setup_teardown_timeout_secs: u64,

    /// Maximum seconds an inbound answered call may remain active without
    /// receiving any RTP packets after answer before rvoip-sip sends local BYE
    /// cleanup and releases the session.
    ///
    /// This is disabled by default because SIP permits long silent calls. It
    /// is intended for high-density auto-answer servers and carrier burst
    /// tests where an answered call that never produces RTP is more likely to
    /// be an abandoned late-setup edge than a valid silent call. `0` disables
    /// the watchdog.
    pub active_call_no_media_timeout_secs: u64,

    /// Maximum seconds an inbound answered call may remain active without RTP
    /// packet-count progress after it has previously received media.
    ///
    /// This is disabled by default because SIP permits silent calls and
    /// application-layer policy varies. It is intended for high-density
    /// auto-answer servers and carrier burst tests where a media-bearing call
    /// that stops receiving RTP and never receives BYE should not retain
    /// server resources indefinitely. `0` disables the watchdog.
    pub active_call_media_idle_timeout_secs: u64,

    /// RFC 4028 `Session-Expires` value in seconds to advertise on outgoing
    /// INVITEs. `None` disables session timers entirely. Common carrier
    /// value is 1800 (30 min).
    pub session_timer_secs: Option<u32>,

    /// Minimum-session-expires (`Min-SE:`) we're willing to accept, in
    /// seconds. Default 90 per RFC 4028 §5.
    pub session_timer_min_se: u32,

    /// Default Digest credentials for UAC 401/407 retry.
    ///
    /// This is the Digest shorthand. When a supported outbound request is
    /// challenged and no per-request auth was supplied, `rvoip-sip` can use
    /// these credentials to compute a Digest response. Use
    /// [`Config::auth`](Self::auth) for Bearer, Basic, AKA, or
    /// multi-challenge negotiation. Default: `None`.
    pub credentials: Option<crate::types::Credentials>,

    /// General UAC auth configuration used for 401/407 retries across
    /// supported SIP access-auth schemes.
    ///
    /// Configure this with [`crate::SipClientAuth`] for Digest, Bearer, Basic,
    /// AKA, or [`crate::SipClientAuth::any`] multi-challenge negotiation.
    /// `credentials` remains the Digest shorthand; precedence is per-request
    /// auth, then this field, then `credentials`.
    pub auth: Option<crate::auth::SipClientAuth>,

    /// Default `P-Asserted-Identity` URI (RFC 3325 §9.1) to attach to every
    /// outgoing INVITE. Carrier trunks (Twilio, Vonage, Bandwidth, most PBX
    /// trunks) require PAI for caller-ID assertion on outbound trunk calls;
    /// without it the call is often hard-rejected or stripped of caller ID.
    /// `None` (the default) suppresses the header entirely. Per-call override
    /// is available via [`UnifiedCoordinator::invite`] + `.with_pai(...)`.
    pub pai_uri: Option<String>,

    /// Optional SIP transport-boundary tracing for diagnostics.
    pub sip_trace: crate::api::events::SipTraceConfig,

    /// SIP_API_DESIGN_2 §12.4 — pluggable trace-output redaction. Every
    /// header value passing through the trace sink is run through the
    /// configured policy before logging; the wire form is unaffected.
    /// `None` selects the production-safe [`DefaultTraceRedactor`]; verbatim
    /// traces require an explicit [`PassthroughRedactor`] development/operator
    /// opt-in. See
    /// [`crate::api::trace_redactor::TraceRedactor`] for the policy
    /// hook contract and [`Config::trace_passthrough_for_development`] for the
    /// explicit unsafe override.
    ///
    /// [`DefaultTraceRedactor`]: crate::api::trace_redactor::DefaultTraceRedactor
    /// [`PassthroughRedactor`]: crate::api::trace_redactor::PassthroughRedactor
    pub trace_redaction: Option<std::sync::Arc<dyn crate::api::trace_redactor::TraceRedactor>>,

    /// Outbound proxy URI (RFC 3261 §8.1.2). When set, a `Route:
    /// <outbound-proxy-uri;lr>` header is pre-loaded as the first Route on
    /// every outgoing INVITE this UA originates, forcing the dialog-
    /// initiating request through the specified proxy. Typical values:
    /// `sip:sbc.example.com;lr`, `sips:sbc.example.com:5061;lr`.
    ///
    /// The URI should carry the `;lr` parameter to signal a loose-routing
    /// proxy (RFC 3261 §16.12.1.1). rvoip-sip does **not** auto-add `;lr`
    /// — set it explicitly in the URI string.
    ///
    /// Applied to outgoing INVITEs and REGISTERs. For REGISTER, the registrar
    /// remains the SIP Request-URI while the network destination is the
    /// outbound proxy and a loose Route header is included. `None` (the
    /// default) suppresses the header entirely. Per-request override is not
    /// yet exposed.
    pub outbound_proxy_uri: Option<String>,

    /// Enable RFC 5626 "SIP Outbound" behaviour on outgoing REGISTERs.
    ///
    /// When `true` and [`Config::sip_instance`] is set, the REGISTER Contact
    /// carries the outbound-aware parameters:
    ///
    /// - `+sip.instance="<urn:...>"` (RFC 5626 §4.1) — UA-stable instance
    ///   URN, so the registrar can associate a binding with a specific
    ///   physical device across flow failures.
    /// - `reg-id=1` (RFC 5626 §4.2) — flow identifier. Multi-flow support
    ///   will bump this; today we always register flow 1.
    /// - The Contact URI gets a `;ob` flag (RFC 5626 §5.4) signalling that
    ///   the UA wants the registrar to preserve the flow association.
    ///
    /// Enable this for carriers and SBCs that assume RFC 5626 — most
    /// modern carrier infra does. Default: `false` (pre-5626 REGISTER
    /// behaviour for backwards compatibility).
    ///
    /// When the registrar echoes the outbound Contact in a 2xx REGISTER,
    /// rvoip-sip-dialog starts CRLFCRLF keep-alive pings on the registration
    /// flow. Flow failure is surfaced back into rvoip-sip so the
    /// registration can be refreshed.
    pub sip_outbound_enabled: bool,

    /// UA-stable instance URN advertised on outbound REGISTERs (RFC 5626
    /// §4.1). Typically a `urn:uuid:<uuid>` generated once per device and
    /// persisted across process restarts. Without this, the registrar
    /// cannot tell a restarted UA apart from a different device with the
    /// same AoR — flow stickiness breaks.
    ///
    /// When [`Config::sip_outbound_enabled`] is `true` and this is `None`,
    /// a warning is logged and outbound-aware parameters are suppressed
    /// on the REGISTER (falling back to pre-5626 behaviour). Callers
    /// SHOULD supply a stable URN explicitly; leaving it `None` is only
    /// appropriate for single-shot dev / lab usage.
    pub sip_instance: Option<String>,

    /// Interval in seconds between RFC 5626 §5.1 CRLFCRLF keep-alive pings
    /// on long-lived TCP / TLS flows. Default 25 s per the RFC
    /// recommendation (ping every 25 s, flow declared dead after 30 s
    /// without a response).
    ///
    /// This is honored when outbound registration flow support is
    /// enabled with a stable [`Config::sip_instance`].
    pub outbound_keepalive_interval_secs: u64,

    /// Automatically refresh successful registrations before they expire.
    ///
    /// When enabled, rvoip-sip schedules a re-REGISTER after a successful
    /// REGISTER 2xx using the registrar-accepted expiry. Default: `true`.
    pub registration_auto_refresh: bool,

    /// Maximum percentage of the refresh interval to subtract as jitter.
    ///
    /// The base refresh interval is 85% of the accepted expiry. Jitter is
    /// applied earlier, never later, so a value of 5 means the refresh fires
    /// between 80.75% and 85% of the accepted expiry. Default: `5`.
    pub registration_refresh_jitter_percent: u8,

    /// Timeout for best-effort unregister during graceful shutdown.
    ///
    /// `0` disables unregister-on-shutdown. Default: `3` seconds.
    pub unregister_on_shutdown_timeout_secs: u64,

    /// SIP TLS signalling mode.
    pub sip_tls_mode: SipTlsMode,

    /// SIP Contact reachability strategy.
    ///
    /// [`SipContactMode::ReachableContact`] is the classic SIP UA model:
    /// the Contact URI is directly reachable by the peer. For SIP TLS that
    /// means this process usually also runs a TLS listener. The registered
    /// flow modes are for proxy/B2BUA deployments where inbound requests are
    /// expected on the existing outbound registration flow.
    pub sip_contact_mode: SipContactMode,

    /// Optional local SIP TLS listener address. Used for
    /// [`SipTlsMode::ServerOnly`] and [`SipTlsMode::ClientAndServer`].
    /// When unset, rvoip-sip-dialog retains its legacy default of deriving the
    /// TLS listener address from [`Config::bind_addr`] by adding 1 to the
    /// port.
    pub tls_bind_addr: Option<SocketAddr>,

    /// Optional advertised address for SIP TLS Via sent-by and fallback
    /// Contact generation. This is distinct from [`Config::tls_bind_addr`]:
    /// bind can be `0.0.0.0`, while the advertised address must be routable
    /// by peers.
    pub tls_advertised_addr: Option<SocketAddr>,

    /// Optional Contact URI override used by rvoip-sip-dialog for
    /// dialog-creating and target-refresh requests. Registrations can
    /// still override Contact per REGISTER via [`Registration`].
    pub contact_uri: Option<String>,

    /// Path to the PEM-encoded TLS listener certificate (RFC 3261
    /// §26.2 / RFC 5630). Required only for [`SipTlsMode::ServerOnly`]
    /// and [`SipTlsMode::ClientAndServer`]. It is not required for
    /// [`SipTlsMode::ClientOnly`], where this endpoint connects to a
    /// remote TLS server and verifies that server's certificate.
    pub tls_cert_path: Option<std::path::PathBuf>,

    /// Path to the PEM-encoded PKCS#8 listener private key matching
    /// [`Config::tls_cert_path`].
    pub tls_key_path: Option<std::path::PathBuf>,

    /// Optional PEM-encoded client certificate chain for mutual TLS.
    /// Leave unset for normal server-authenticated SIP TLS.
    pub tls_client_cert_path: Option<std::path::PathBuf>,

    /// Optional PEM-encoded PKCS#8 private key matching
    /// [`Config::tls_client_cert_path`].
    pub tls_client_key_path: Option<std::path::PathBuf>,

    /// Optional path to a PEM-encoded CA bundle to *add to* the system
    /// trust store on the client side. Used for enterprise PKI / private
    /// carriers where the server cert is signed by a private CA not in
    /// the system root store. Default: `None` (system roots only).
    pub tls_extra_ca_path: Option<std::path::PathBuf>,

    /// Inbound SIP TLS client-certificate verification policy.
    ///
    /// This controls certificates presented by peers connecting to this
    /// listener. It is independent from [`Config::tls_client_cert_path`],
    /// which controls the certificate this endpoint presents on outbound
    /// connections. The default is disabled. Tenant-bound mTLS listener
    /// mappings require `Optional` or `Required` with an explicit client CA.
    pub tls_server_client_auth: rvoip_sip_transport::transport::tls::TlsServerClientAuthConfig,

    /// **Dev only.** When `true`, server certs are accepted without
    /// identity verification. Required for self-signed test certs. The
    /// TLS handshake still runs end-to-end (encrypted), but a malicious
    /// peer can MITM. Default: `false`. **Must not** be enabled in
    /// production.
    ///
    /// Gated behind the `dev-insecure-tls` Cargo feature — production
    /// builds physically cannot access this field. The matching
    /// `InsecureCertVerifier` in `sip-transport` is also feature-gated,
    /// so even with the feature enabled the verifier type only exists
    /// in the dev-build binary.
    #[cfg(feature = "dev-insecure-tls")]
    pub tls_insecure_skip_verify: bool,

    /// Offer RFC 4568 SDES-SRTP on outgoing INVITEs.
    ///
    /// When `true`:
    ///
    /// - The `m=audio` line in the offer uses `RTP/SAVP` (RFC 4568
    ///   §3.1.4) instead of `RTP/AVP`.
    /// - One `a=crypto:` line per suite in
    ///   [`Config::srtp_offered_suites`] is attached, each with a
    ///   freshly-generated master key (RFC 4568 §6.1).
    /// - When the answer accepts SRTP, paired `SrtpContext`s are
    ///   installed on the outgoing+incoming RTP transport before the
    ///   first packet flows. All RTP payload is then AES-encrypted
    ///   end-to-end per RFC 3711.
    ///
    /// Enable this when targeting:
    /// - **Cloud SIP carriers** (Twilio, Vonage, Bandwidth, Telnyx)
    ///   on production tier — they typically require `srtp=mandatory`.
    /// - **Modern Asterisk / FreeSWITCH** trunks configured with
    ///   `srtp=mandatory`.
    /// - **Microsoft Teams Direct Routing** (which also requires TLS
    ///   for signalling — see [`Config::tls_cert_path`]).
    ///
    /// Leave disabled (the default) for:
    /// - LAN-only PBX deployments where carriers don't enforce SRTP.
    /// - Dev / lab setups exercising the RTP path without crypto
    ///   overhead.
    /// - Codec / RTP profile experiments where SRTP would obscure
    ///   the wire bytes.
    ///
    /// See [`Config::srtp_required`] for the strict-mode variant.
    pub offer_srtp: bool,

    /// Refuse to fall back to plaintext RTP when SRTP can't be
    /// negotiated.
    ///
    /// - **UAC**: a remote SDP answer without an acceptable
    ///   `a=crypto:` line causes the call to surface as
    ///   [`Event::CallFailed`](crate::api::events::Event::CallFailed)
    ///   rather than silently downgrading.
    /// - **UAS**: an offer without `a=crypto:` is rejected with
    ///   `488 Not Acceptable Here`.
    ///
    /// Mirrors the RFC 3261 `Require:` header semantic — fail
    /// loudly rather than silently downgrade a security guarantee.
    /// Pair with [`Config::offer_srtp`] = `true` for the canonical
    /// "I require encrypted media" stance.
    ///
    /// Default: `false` — soft-prefer SRTP but accept plaintext.
    pub srtp_required: bool,

    /// SRTP crypto suites to advertise on outgoing offers, in
    /// preference order. The answerer picks the first suite it
    /// supports.
    ///
    /// Default:
    /// `[AesCm128HmacSha1_80, AesCm128HmacSha1_32]` —
    /// RFC 4568 §6.2.1 MTI suite first (`_80`, ubiquitous), then
    /// `_32` (smaller auth tag for bandwidth-conscious carriers).
    /// Modify when a specific carrier requires a non-default
    /// preference.
    pub srtp_offered_suites: Vec<CryptoSuite>,

    /// Override the RTP-side public address advertised in SDP `c=` /
    /// `o=` and `m=audio <port>` lines. Use when:
    ///
    /// - The rvoip-sip process runs behind a 1:1 NAT or IP alias
    ///   and the operator already knows the external IP/port.
    /// - The deployment uses an SBC that performs media latching, and
    ///   we want to advertise the SBC's public IP rather than rely on
    ///   STUN.
    ///
    /// Mutually exclusive with [`Config::stun_server`]. If both are
    /// set, the static override wins and a warning is logged.
    /// Default: `None` — advertise the local interface address (today's
    /// behaviour).
    pub media_public_addr: Option<SocketAddr>,

    /// Enable AMR discontinuous transmission: replace silence with SID
    /// (comfort-noise) frames and gaps rather than coding it as speech.
    ///
    /// Local sender policy, not a negotiated parameter. RFC 4867 defines no
    /// fmtp for DTX and a sender may use it without telling the peer, because
    /// every conforming AMR receiver must handle SID and NO_DATA frames
    /// regardless. It therefore needs no offer/answer support and cannot be
    /// refused by the far end — but it does change what goes on the wire, so
    /// it is off unless a deployment asks for it.
    ///
    /// Ignored by every codec but AMR. Default: `false`.
    ///
    /// Private with a builder on purpose: `Config`'s constructible shape is
    /// frozen for the 0.3.x line, and this is media policy, not signaling —
    /// set it with [`Config::with_amr_dtx`].
    amr_dtx: bool,

    /// Let AMR sessions ask the peer to change rate on their own.
    ///
    /// A damper watches which modes actually arrive and, at most once every
    /// five seconds, asks for one step toward a mode the peer is not using —
    /// the shape rtpengine documents. Like [`Config::with_amr_dtx`] this is
    /// local policy: a codec mode request is advice to the sender and needs
    /// no negotiation.
    ///
    /// Off by default, and deliberately so: an automatic requester that damps
    /// badly oscillates the peer's rate, which is worse than never asking.
    /// Explicit `request_peer_codec_mode` calls always outrank it.
    ///
    /// Ignored by every codec but AMR. Default: `false`. Set with
    /// [`Config::with_amr_auto_cmr`].
    amr_auto_cmr: bool,

    /// Restrict AMR to these modes, offered as RFC 4867 `mode-set`.
    ///
    /// Unlike [`Config::with_amr_dtx`] and [`Config::with_amr_auto_cmr`],
    /// this one is negotiated rather than local policy. `mode-set` is
    /// bi-directional
    /// (RFC 4867 §8.1): one active set governs both directions, so naming
    /// modes here constrains what the peer may send as well as what this
    /// endpoint sends, and a conforming answerer must echo the set or reject
    /// the payload type.
    ///
    /// Members are mode *indices*, not bitrates: 0..=7 for narrowband
    /// (4.75 – 12.2 kbit/s) and 0..=8 for wideband (6.6 – 23.85 kbit/s).
    /// Members outside the variant's range are dropped rather than offered,
    /// since a set naming a mode the variant lacks is one a peer may reject
    /// the whole payload type over. The rendered list is sorted and
    /// deduplicated so an offer and its echo compare byte for byte.
    ///
    /// Empty or `None` offers no `mode-set` at all, which is the correct
    /// thing for an endpoint that supports every mode — and is the default.
    /// Set it when a deployment or a conformance run needs a specific rate,
    /// such as pinning AMR-WB to 12.65 kbit/s with `Some(vec![2])`.
    ///
    /// Ignored by every codec but AMR. Default: `None`. Set with
    /// [`Config::with_amr_mode_set`].
    amr_mode_set: Option<Vec<u8>>,

    /// Media allocation behavior.
    ///
    /// Default: [`MediaMode::Enabled`], which allocates real media-core RTP
    /// sessions and RTP ports. [`MediaMode::SignalingOnly`] skips media-core
    /// RTP allocation but still emits SDP; useful for signaling-only services
    /// and controlled tests.
    pub media_mode: MediaMode,

    /// Optional capacity hint for media-core session and RTP port indexes.
    ///
    /// This is intentionally separate from [`Config::server_call_capacity`]:
    /// high-CPS media servers may want RTP/media preallocation without
    /// inflating SIP dialog and transaction indexes.
    pub media_session_capacity: Option<usize>,

    /// RTP session queue sizing for SIP media calls.
    pub rtp_session_buffer_config: RtpSessionBufferConfig,

    /// RTP transport event and receive buffer sizing for SIP media calls.
    pub rtp_transport_buffer_config: RtpTransportBufferConfig,

    /// Media-core controller pool and capacity tuning for SIP media calls.
    pub media_session_controller_config: MediaSessionControllerConfig,

    /// STUN server (RFC 8489 §14) to probe for the RTP-side public
    /// mapping at coordinator boot. Format: `"host:port"` or `"host"`
    /// (default port 3478). Common public servers:
    /// `stun.l.google.com:19302`, `stun.cloudflare.com:3478`.
    ///
    /// The probe runs once at startup using a fresh UDP socket bound to
    /// [`Config::local_ip`]. This is best-effort address discovery: it is
    /// useful for simple cone-NAT labs, but it does not guarantee the exact
    /// mapping of a later per-call RTP socket. Symmetric NATs and production
    /// Internet edges should use a static [`Config::media_public_addr`] today
    /// or ICE in a future WebRTC/edge layer. Failure mode: probe timeout /
    /// unreachable / unparseable response → log a warning and fall back to
    /// the local interface address. STUN is intentionally soft-fail — the
    /// call path is never blocked on it.
    ///
    /// Default: `None` — no probe runs (today's behaviour).
    pub stun_server: Option<String>,

    /// RFC 3389 Comfort Noise (PT 13) advertisement.
    ///
    /// When `true`, outgoing offers and answers carry `13` in the
    /// `m=audio` format list plus `a=rtpmap:13 CN/8000` so peers know
    /// we accept Comfort Noise during silence periods. The session
    /// also enables media-core comfort-noise support so callers can drive CN
    /// packets through their chosen media-control path.
    ///
    /// Default: `false` — peers see the pre-Sprint-3 PCMU + PCMA +
    /// telephone-event format set with no CN.
    pub comfort_noise_enabled: bool,

    /// RFC 3264 §6 strict codec matching for SDP answers.
    ///
    /// When `true` (default), the SDP answer's format list is the
    /// strict intersection of the offer's formats and our supported
    /// set, in offerer-preference order. RFC-correct: a peer that
    /// offered `0 101` (PCMU + telephone-event only) gets answered
    /// with `0 101`, not `0 8 101`.
    ///
    /// When `false`, the answer always advertises our full supported
    /// set regardless of offer (the pre-Sprint-3.5 permissive
    /// behaviour). Set to `false` for deployments where a carrier or
    /// PBX accidentally relied on the legacy "always full set"
    /// answer shape — this provides a one-line escape hatch back to
    /// the prior behaviour without code changes.
    ///
    /// Default: `true`.
    pub strict_codec_matching: bool,

    /// RTP payload types this UA advertises in outgoing offers and accepts in
    /// answers. Default `[0, 8, 101]` (PCMU + PCMA + telephone-event)
    /// preserves the established beta media profile.
    ///
    /// Beta validation intentionally rejects audio payload types that
    /// media-core cannot encode/decode end to end. The advertised full-media
    /// set is limited to PCMU (`0`), PCMA (`8`), telephone-event (`101`),
    /// comfort noise (`13`) when `comfort_noise_enabled = true`, G.729 (`18`)
    /// when the `g729` feature is enabled, and Opus (`111`) when the `opus`
    /// feature is enabled. G.722 (`9`) retains wire metadata support but is
    /// rejected because no working encoder/decoder is implemented.
    ///
    /// Default: `vec![0, 8, 101]`.
    pub offered_codecs: Vec<u8>,

    /// G.729 Annex B VAD/DTX/CNG SDP preference for payload type 18.
    ///
    /// When PT 18 is present in [`Config::offered_codecs`] and the `g729`
    /// feature is enabled, outgoing offers carry `a=fmtp:18 annexb=yes` when
    /// this is `true` and `a=fmtp:18 annexb=no` when this is `false`. Answers
    /// disable Annex B if either side advertises `annexb=no`.
    ///
    /// Default: `true` (G.729A speech plus Annex B).
    pub g729_annex_b: bool,

    /// Capacity for the legacy incoming-call compatibility channel.
    ///
    /// Modern [`CallbackPeer`](crate::api::callback_peer::CallbackPeer) and
    /// [`StreamPeer`](crate::api::stream_peer::StreamPeer) consumers receive
    /// incoming calls through the app event publisher. The compatibility
    /// receiver exposed by [`UnifiedCoordinator::get_incoming_call`] is still
    /// kept for lower-level callers, so the buffer must be large enough for
    /// bursts without becoming a hidden backpressure point in the dialog event
    /// handler. Default: `1000`.
    pub incoming_call_channel_capacity: usize,

    /// Capacity for the internal state-machine event channel.
    ///
    /// State transitions publish lightweight internal events that the session
    /// event handler consumes and maps onto public API events where needed.
    /// This buffer must absorb short bursts so SIP request processing does not
    /// block behind event fan-out during load tests. Default: `1000`.
    pub state_event_channel_capacity: usize,

    /// Capacity for SIP transport event channels.
    ///
    /// This controls the per-transport receive queue (UDP/TCP/WS) and the
    /// combined transport-manager queue feeding the transaction layer. It is
    /// intentionally larger than the app-facing queues because one call setup
    /// produces multiple SIP messages and retransmission bursts can otherwise
    /// backpressure the UDP receive loop. Default: `10000`.
    pub sip_transport_channel_capacity: usize,

    /// Optional SIP transport-manager forwarding worker count.
    ///
    /// `None` preserves the single per-transport event bridge. Values above
    /// `1` enable keyed sharding between transport receive/parse and
    /// transaction-manager ingress.
    pub sip_transport_dispatch_workers: Option<usize>,

    /// Optional SIP transport-manager forwarding queue capacity.
    ///
    /// `None` uses [`Config::sip_transport_channel_capacity`]. When dispatch
    /// workers are enabled, this capacity is divided across workers.
    pub sip_transport_dispatch_queue_capacity: Option<usize>,

    /// Optional SIP UDP receive socket buffer size (`SO_RCVBUF`) in bytes.
    ///
    /// `None` preserves the OS default, which is appropriate for clients and
    /// small servers. High-CPS server profiles should set this alongside the
    /// transport channel capacity so kernel UDP bursts do not overflow before
    /// the async receive loop can drain them.
    pub sip_udp_recv_buffer_size: Option<usize>,

    /// Optional SIP UDP send socket buffer size (`SO_SNDBUF`) in bytes.
    ///
    /// `None` preserves the OS default. Server deployments with large reply
    /// bursts can set this to match the receive-side sizing policy.
    pub sip_udp_send_buffer_size: Option<usize>,

    /// Optional UDP parse worker count for the SIP UDP receive path.
    ///
    /// `None` keeps the transport default. High-CPS UDP servers can set this
    /// when parsing/dispatch work behind the socket receive loop needs more
    /// parallelism.
    pub sip_udp_parse_workers: Option<usize>,

    /// Optional per-worker UDP parse queue capacity.
    ///
    /// `None` uses the SIP transport channel capacity. When set, this bounds
    /// how many datagrams each UDP parse worker may buffer before overload is
    /// counted and dropped explicitly.
    pub sip_udp_parse_queue_capacity: Option<usize>,

    /// Optional UDP parse worker dispatch strategy.
    ///
    /// `None` preserves the transport default (`SourceHash`). High-CPS perf
    /// tests can opt into `RoundRobin` when the traffic generator sends all
    /// calls from a single source socket and source hashing cannot fan out.
    pub sip_udp_parse_dispatch: Option<rvoip_sip_transport::UdpParseDispatch>,

    /// Capacity for the transaction-manager event channel consumed by dialog
    /// core.
    ///
    /// A small transaction event queue can block transaction processing while
    /// dialog/session cleanup catches up. Default: `10000`.
    pub transaction_event_channel_capacity: usize,

    /// Optional transaction-manager ingress worker count.
    ///
    /// `None` preserves the single receive/handle loop used by clients and
    /// ordinary endpoints. High-CPS servers can set this above `1` to fan out
    /// transaction handling by a stable call/transaction key while preserving
    /// per-call request ordering.
    pub sip_transaction_dispatch_workers: Option<usize>,

    /// Optional transaction-manager ingress queue capacity.
    ///
    /// `None` uses [`Config::transaction_event_channel_capacity`]. When
    /// dispatch workers are enabled, this capacity is divided across workers.
    pub sip_transaction_dispatch_queue_capacity: Option<usize>,

    /// Optional per-transaction command channel capacity.
    ///
    /// Each SIP transaction owns a private command queue for timer and
    /// state-machine messages. This is not a global call burst queue; raising it
    /// increases per-transaction memory. `None` uses
    /// [`Config::DEFAULT_SIP_TRANSACTION_COMMAND_CHANNEL_CAPACITY`]. High-CPS
    /// tuned profiles may raise it when measured timer/state command pressure
    /// proves the default is too small.
    pub sip_transaction_command_channel_capacity: Option<usize>,

    /// Optional priority-lane burst limit for transaction ingress workers.
    ///
    /// This applies only when [`Config::sip_transaction_dispatch_workers`] is
    /// greater than `1`. The transaction dispatcher lets ACK and BYE requests
    /// jump ahead of older normal-lane work on their assigned worker, then
    /// gives one ready normal item a turn after this many consecutive priority
    /// items. `None` uses the transaction-layer default (`64`). Lower this
    /// when INVITE/CANCEL/response work must make progress during teardown
    /// storms; raise it when ACK/BYE latency is the dominant failure mode and
    /// normal-lane delay is acceptable.
    pub sip_transaction_dispatch_priority_burst_max: Option<usize>,

    /// Optional cached INVITE `2xx` retransmission maintenance budget.
    ///
    /// The transaction manager keeps a short-lived cache of successful INVITE
    /// responses so duplicate INVITEs can be answered without rebuilding the
    /// SIP response. This limit controls how many cached `2xx` responses the
    /// proactive maintenance task may retransmit per 100 ms tick. `None` uses
    /// the transaction-layer default (`2048`). Lower this to pace retransmit
    /// storms when UDP send pressure starves teardown work; raise it when the
    /// host send path has headroom and UAC timeout/dead-call volume is driven
    /// by uncleared INVITE `2xx` loss bursts.
    pub sip_invite_2xx_retransmit_max_due_per_tick: Option<usize>,

    /// Optional rvoip-sip-dialog transaction-event dispatch worker count.
    ///
    /// `None` preserves the single dialog event processor. High-CPS servers can
    /// set this above `1` to fan out transaction events by stable call key while
    /// preserving per-call dialog ordering.
    pub sip_dialog_dispatch_workers: Option<usize>,

    /// Optional rvoip-sip-dialog transaction-event dispatch queue capacity.
    ///
    /// `None` uses the dialog max-dialog capacity hint. When dispatch workers
    /// are enabled, this capacity is divided across workers.
    pub sip_dialog_dispatch_queue_capacity: Option<usize>,

    /// Capacity for the infra-common global cross-crate event bus used inside
    /// this coordinator.
    ///
    /// ACK, BYE, media, and app-session events all cross this bus before they
    /// reach their local consumers. The default is intentionally modest so
    /// ordinary clients and PBX apps do not retain a large app-event ring.
    /// High-CPS server profiles should size it with the other signaling queues
    /// so the event bridge does not drop cleanup-driving events.
    /// Default: [`Config::DEFAULT_APP_EVENT_CHANNEL_CAPACITY`].
    pub global_event_channel_capacity: usize,

    /// Number of async workers used to publish app-level session events onto
    /// the global infra-common event bus.
    ///
    /// Internal per-call waits use the lifecycle index directly, but public
    /// event subscribers still receive events through the global bus. This
    /// worker pool avoids spawning one task per non-terminal event under
    /// server load. Default: logical CPU count capped at 16.
    pub session_event_dispatcher_workers: usize,

    /// Per-worker queue capacity for app-level session event publication.
    ///
    /// This bounded queue sits in front of the global event coordinator for
    /// every app event. Terminal publication awaits both queue admission and
    /// the worker's delivery acknowledgement, so exact session cleanup begins
    /// only after the terminal event's ordered publication attempt completes.
    /// Default: [`Config::DEFAULT_APP_EVENT_CHANNEL_CAPACITY`].
    pub session_event_dispatcher_channel_capacity: usize,

    /// Expected server-side active call capacity for hot lookup indexes.
    ///
    /// `None` keeps client/small-endpoint behavior lazy and uses existing
    /// channel-derived defaults. Server/high-CPS profiles should set this to
    /// the expected active-call burst size so dialog, transaction, session,
    /// lifecycle, and media indexes can reserve capacity up front without
    /// tying that memory reservation to the larger event-queue capacities.
    pub server_call_capacity: Option<usize>,

    /// Maximum active, quarantined, and retired SIP lifecycle records retained
    /// by the session authority.
    ///
    /// This is distinct from [`Config::server_call_capacity`], which limits
    /// simultaneous active lifetimes. A short-call, high-CPS server can retire
    /// many identifiers during the 64-second SIP anti-reuse horizon even when
    /// its active concurrency remains modest. Set this to at least the active
    /// capacity plus the expected call-arrival rate multiplied by that horizon,
    /// with suitable burst headroom. It requires `server_call_capacity` and
    /// must be greater than or equal to it. `None` preserves the library's
    /// conservative default retained-capacity calculation.
    pub server_retained_lifecycle_capacity: Option<usize>,

    /// Server-side admission limit for concurrently retained SIP call sessions.
    ///
    /// This is an enforcement knob, not a preallocation hint. When set and the
    /// session store is already at or above this limit, new inbound INVITEs are
    /// rejected by the library with a SIP overload response instead of being
    /// accepted into unbounded work. Server performance recipes should size
    /// this high enough for the expected CPS multiplied by call lifetime.
    /// `None` preserves endpoint/client behavior with no library admission cap.
    pub server_call_admission_limit: Option<usize>,

    /// Soft threshold for server-side admission pacing.
    ///
    /// When set and the active retained session count is at or above this
    /// value but below [`Config::server_call_admission_limit`], inbound INVITE
    /// processing is delayed by
    /// [`Config::server_call_admission_pacing_delay_ms`]. This gives active
    /// calls a chance to drain before the hard overload policy starts
    /// rejecting. `None` disables soft pacing.
    pub server_call_admission_soft_limit: Option<usize>,

    /// Delay applied when the server admission soft threshold is reached.
    ///
    /// Applies only when [`Config::server_call_admission_soft_limit`] is set.
    /// Values below `1` are rejected when set.
    pub server_call_admission_pacing_delay_ms: Option<u64>,

    /// `Retry-After` value in seconds for Config-owned server overload
    /// rejections.
    ///
    /// Applies only when [`Config::server_call_admission_limit`] is set and an
    /// inbound INVITE arrives while the server is at capacity. `Some(n)` adds
    /// `Retry-After: n` to the default `503 Service Unavailable` response;
    /// `None` omits the header. Default is `Some(1)`.
    pub server_overload_retry_after_secs: Option<u32>,

    /// Enable SIP UDP transport and duplicate-recovery diagnostics.
    ///
    /// This is a Config-owned replacement for benchmark-only diagnostic env
    /// toggles. It enables UDP receive/send counters and SIP duplicate
    /// INVITE/BYE cache counters for this process.
    pub sip_udp_diagnostics: bool,

    /// Enable high-cardinality transaction timing diagnostics.
    ///
    /// This records per-message transaction dispatch, handler, transaction
    /// creation, existing-transaction dispatch, and event-send histograms. It
    /// is intentionally separate from [`Config::sip_udp_diagnostics`] because
    /// it adds hot-path timestamp and atomic work under high CPS.
    pub sip_transaction_timing_diagnostics: bool,

    /// Enable high-cardinality dialog timing diagnostics.
    ///
    /// This records transaction-event-to-dialog queueing, dialog handler,
    /// dialog lookup, and dialog-to-session publish histograms. It is separate
    /// from transaction timing so 20k CPS tests can isolate the current hot
    /// layer.
    pub sip_dialog_timing_diagnostics: bool,

    /// Enable media setup/teardown timing diagnostics.
    ///
    /// This records media start/stop, RTP port allocation, RTP session
    /// creation, event subscription, and handler-spawn timing.
    pub media_setup_diagnostics: bool,

    /// Enable cleanup-stage timing diagnostics.
    ///
    /// This records cleanup and high-rate call-progress subpath counters used
    /// by the perf listener and high-CPS investigations.
    pub cleanup_diagnostics: bool,

    /// Enable per-operation cleanup diagnostic event logs.
    ///
    /// This is intentionally separate from [`Config::cleanup_diagnostics`]
    /// because it emits one log line per measured operation and is much more
    /// expensive under load.
    pub cleanup_diagnostic_events: bool,

    /// Maximum allowed RSS growth in MB/hour for perf soak release gates.
    ///
    /// This is compiled only with the `perf-tests` feature because it is a
    /// benchmark/release-gate control, not a production runtime memory limit.
    /// `None` uses [`Config::DEFAULT_PERF_MAX_RSS_GROWTH_MB_PER_HR`].
    #[cfg(feature = "perf-tests")]
    pub perf_max_rss_growth_mb_per_hr: Option<f64>,

    /// Enable SRTP negotiation diagnostic log lines.
    pub srtp_diagnostics: bool,

    /// Enable RTP packet diagnostic log lines.
    pub rtp_diagnostics: bool,

    /// Enable SDP media diagnostic log lines.
    pub media_sdp_diagnostics: bool,

    /// SIP_API_DESIGN_2 §7.4 — application-supplied headers stamped
    /// on every outbound message the state machine emits
    /// **automatically** (session-timer auto-BYE, dialog-terminated-
    /// during-INVITE auto-CANCEL, REFER-completion auto-NOTIFY).
    ///
    /// Stack-managed names (`Call-ID`, `CSeq`, `Via`, `Max-Forwards`,
    /// `Content-Length`, `Record-Route`) are rejected at
    /// [`Config::validate`] time. Method-shaped names that have a
    /// dedicated builder setter (e.g. `Authorization`) are accepted
    /// here — auto-emit messages have no per-call builder to route
    /// through.
    ///
    /// Applies to auto-emitted messages only; application-initiated
    /// builders inherit `Config` defaults through the §6.1 merge
    /// table, not through this field. The §7.4 precedence rule is:
    /// the state machine's auto-emit handler checks
    /// `pending_<method>_options` stash first; if populated those
    /// win and `auto_emit_extra_headers` is **not** appended.
    pub auto_emit_extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
}

impl std::fmt::Debug for Config {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Config")
            .field("sip_port", &self.sip_port)
            .field("media_port_start", &self.media_port_start)
            .field("media_port_end", &self.media_port_end)
            .field("media_port_capacity", &self.media_port_capacity)
            .field("use_100rel", &self.use_100rel)
            .field("auto_180_ringing", &self.auto_180_ringing)
            .field("auto_100_trying", &self.auto_100_trying)
            .field(
                "fast_auto_accept_incoming_calls",
                &self.fast_auto_accept_incoming_calls,
            )
            .field(
                "setup_teardown_timeout_secs",
                &self.setup_teardown_timeout_secs,
            )
            .field("session_timer_secs", &self.session_timer_secs)
            .field("session_timer_min_se", &self.session_timer_min_se)
            .field("credentials_configured", &self.credentials.is_some())
            .field("auth_configured", &self.auth.is_some())
            .field("pai_configured", &self.pai_uri.is_some())
            .field("sip_trace_enabled", &self.sip_trace.enabled)
            .field("sip_trace_capacity", &self.sip_trace.capacity)
            .field(
                "sip_trace_sensitive_redaction",
                &self.sip_trace.redact_sensitive_headers,
            )
            .field("sip_trace_include_body", &self.sip_trace.include_body)
            .field(
                "trace_redaction_configured",
                &self.trace_redaction.is_some(),
            )
            .field(
                "outbound_proxy_configured",
                &self.outbound_proxy_uri.is_some(),
            )
            .field("sip_outbound_enabled", &self.sip_outbound_enabled)
            .field("sip_instance_configured", &self.sip_instance.is_some())
            .field("sip_tls_mode", &self.sip_tls_mode)
            .field("sip_contact_mode", &self.sip_contact_mode)
            .field("tls_bind_configured", &self.tls_bind_addr.is_some())
            .field(
                "tls_advertised_configured",
                &self.tls_advertised_addr.is_some(),
            )
            .field("contact_uri_configured", &self.contact_uri.is_some())
            .field("tls_cert_configured", &self.tls_cert_path.is_some())
            .field("tls_key_configured", &self.tls_key_path.is_some())
            .field(
                "tls_client_cert_configured",
                &self.tls_client_cert_path.is_some(),
            )
            .field(
                "tls_client_key_configured",
                &self.tls_client_key_path.is_some(),
            )
            .field("tls_extra_ca_configured", &self.tls_extra_ca_path.is_some())
            .field(
                "tls_server_client_auth_mode",
                &self.tls_server_client_auth.mode,
            )
            .field("offer_srtp", &self.offer_srtp)
            .field("srtp_required", &self.srtp_required)
            .field("amr_dtx", &self.amr_dtx)
            .field("amr_auto_cmr", &self.amr_auto_cmr)
            .field("amr_mode_set", &self.amr_mode_set)
            .field("srtp_suite_count", &self.srtp_offered_suites.len())
            .field(
                "media_public_address_configured",
                &self.media_public_addr.is_some(),
            )
            .field("media_mode", &self.media_mode)
            .field("media_session_capacity", &self.media_session_capacity)
            .field("stun_configured", &self.stun_server.is_some())
            .field("offered_codec_count", &self.offered_codecs.len())
            .field(
                "incoming_call_channel_capacity",
                &self.incoming_call_channel_capacity,
            )
            .field(
                "state_event_channel_capacity",
                &self.state_event_channel_capacity,
            )
            .field(
                "sip_transport_channel_capacity",
                &self.sip_transport_channel_capacity,
            )
            .field(
                "transaction_event_channel_capacity",
                &self.transaction_event_channel_capacity,
            )
            .field(
                "global_event_channel_capacity",
                &self.global_event_channel_capacity,
            )
            .field("server_call_capacity", &self.server_call_capacity)
            .field(
                "server_retained_lifecycle_capacity",
                &self.server_retained_lifecycle_capacity,
            )
            .field(
                "server_call_admission_limit",
                &self.server_call_admission_limit,
            )
            .field("sip_udp_diagnostics", &self.sip_udp_diagnostics)
            .field(
                "sip_transaction_timing_diagnostics",
                &self.sip_transaction_timing_diagnostics,
            )
            .field(
                "sip_dialog_timing_diagnostics",
                &self.sip_dialog_timing_diagnostics,
            )
            .field("media_setup_diagnostics", &self.media_setup_diagnostics)
            .field("cleanup_diagnostics", &self.cleanup_diagnostics)
            .field(
                "auto_emit_extra_header_count",
                &self.auto_emit_extra_headers.len(),
            )
            .finish_non_exhaustive()
    }
}

impl Config {
    /// Default RTP media port range start.
    pub const DEFAULT_MEDIA_PORT_START: u16 = DEFAULT_RTP_PORT_RANGE_START;

    /// Default RTP media port range end.
    pub const DEFAULT_MEDIA_PORT_END: u16 = DEFAULT_RTP_PORT_RANGE_END;

    /// Default RSS growth threshold for perf soak release gates.
    pub const DEFAULT_PERF_MAX_RSS_GROWTH_MB_PER_HR: f64 = 10.0;

    /// Default app-facing event buffer capacity.
    ///
    /// This is intentionally smaller than the lower-level SIP transport and
    /// transaction defaults so ordinary client/server apps do not reserve a
    /// large broadcast ring unless they opt into a high-CPS profile.
    pub const DEFAULT_APP_EVENT_CHANNEL_CAPACITY: usize = 256;

    /// Default per-transaction command channel capacity.
    pub const DEFAULT_SIP_TRANSACTION_COMMAND_CHANNEL_CAPACITY: usize =
        rvoip_sip_dialog::transaction::DEFAULT_TRANSACTION_COMMAND_CHANNEL_CAPACITY;

    /// Default watchdog timeout for setup/teardown states that are waiting on
    /// dialog-core terminal events.
    pub const DEFAULT_SETUP_TEARDOWN_TIMEOUT_SECS: u64 = 120;

    /// Explicitly allow verbatim SIP trace headers and any included bodies for
    /// controlled development/operator diagnostics.
    ///
    /// This disables both the pluggable default policy and the built-in
    /// sensitive-header/body-key redaction. It can expose credentials, PII,
    /// application context, and SDP key material. Do not use it in production.
    pub fn trace_passthrough_for_development(mut self) -> Self {
        self.trace_redaction = Some(std::sync::Arc::new(
            crate::api::trace_redactor::PassthroughRedactor,
        ));
        self.sip_trace = self.sip_trace.verbatim_for_development();
        self
    }

    /// Create a config for local development/testing on 127.0.0.1.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::Config;
    /// let config = Config::local("alice", 5060);
    /// assert_eq!(config.local_uri, "sip:alice@127.0.0.1:5060");
    /// ```
    pub fn local(name: &str, port: u16) -> Self {
        let ip: IpAddr = "127.0.0.1".parse().unwrap();
        Self {
            local_ip: ip,
            sip_port: port,
            media_port_start: Self::DEFAULT_MEDIA_PORT_START,
            media_port_end: Self::DEFAULT_MEDIA_PORT_END,
            media_port_capacity: None,
            bind_addr: SocketAddr::new(ip, port),
            sip_advertised_addr: None,
            state_table_path: None,
            local_uri: format!("sip:{}@{}:{}", name, ip, port),
            use_100rel: RelUsage::default(),
            auto_180_ringing: true,
            auto_100_trying: true,
            fast_auto_accept_incoming_calls: false,
            setup_teardown_timeout_secs: Self::DEFAULT_SETUP_TEARDOWN_TIMEOUT_SECS,
            active_call_no_media_timeout_secs: 0,
            active_call_media_idle_timeout_secs: 0,
            session_timer_secs: None,
            session_timer_min_se: 90,
            credentials: None,
            auth: None,
            pai_uri: None,
            sip_trace: crate::api::events::SipTraceConfig::default(),
            trace_redaction: Some(crate::api::trace_redactor::default_trace_redactor()),
            outbound_proxy_uri: None,
            sip_outbound_enabled: false,
            sip_instance: None,
            outbound_keepalive_interval_secs: 25,
            registration_auto_refresh: true,
            registration_refresh_jitter_percent: 5,
            unregister_on_shutdown_timeout_secs: 3,
            sip_tls_mode: SipTlsMode::Disabled,
            sip_contact_mode: SipContactMode::ReachableContact,
            tls_bind_addr: None,
            tls_advertised_addr: None,
            contact_uri: None,
            tls_cert_path: None,
            tls_key_path: None,
            tls_client_cert_path: None,
            tls_client_key_path: None,
            tls_extra_ca_path: None,
            tls_server_client_auth:
                rvoip_sip_transport::transport::tls::TlsServerClientAuthConfig::default(),
            #[cfg(feature = "dev-insecure-tls")]
            tls_insecure_skip_verify: false,
            offer_srtp: false,
            srtp_required: false,
            amr_dtx: false,
            amr_auto_cmr: false,
            amr_mode_set: None,
            srtp_offered_suites: SrtpSuitePolicy::Default.suites(),
            media_public_addr: None,
            media_mode: MediaMode::Enabled,
            media_session_capacity: None,
            rtp_session_buffer_config: RtpSessionBufferConfig::default(),
            rtp_transport_buffer_config: RtpTransportBufferConfig::default(),
            media_session_controller_config: MediaSessionControllerConfig::default(),
            stun_server: None,
            comfort_noise_enabled: false,
            strict_codec_matching: true,
            offered_codecs: vec![0, 8, 101],
            g729_annex_b: true,
            incoming_call_channel_capacity: 1000,
            state_event_channel_capacity: 1000,
            sip_transport_channel_capacity: 10_000,
            sip_transport_dispatch_workers: None,
            sip_transport_dispatch_queue_capacity: None,
            sip_udp_recv_buffer_size: None,
            sip_udp_send_buffer_size: None,
            sip_udp_parse_workers: None,
            sip_udp_parse_queue_capacity: None,
            sip_udp_parse_dispatch: None,
            transaction_event_channel_capacity: 10_000,
            sip_transaction_dispatch_workers: None,
            sip_transaction_dispatch_queue_capacity: None,
            sip_transaction_command_channel_capacity: None,
            sip_transaction_dispatch_priority_burst_max: None,
            sip_invite_2xx_retransmit_max_due_per_tick: None,
            sip_dialog_dispatch_workers: None,
            sip_dialog_dispatch_queue_capacity: None,
            global_event_channel_capacity: Self::DEFAULT_APP_EVENT_CHANNEL_CAPACITY,
            session_event_dispatcher_workers: default_session_event_dispatcher_workers(),
            session_event_dispatcher_channel_capacity: Self::DEFAULT_APP_EVENT_CHANNEL_CAPACITY,
            server_call_capacity: None,
            server_retained_lifecycle_capacity: None,
            server_call_admission_limit: None,
            server_call_admission_soft_limit: None,
            server_call_admission_pacing_delay_ms: None,
            server_overload_retry_after_secs: Some(1),
            sip_udp_diagnostics: false,
            sip_transaction_timing_diagnostics: false,
            sip_dialog_timing_diagnostics: false,
            media_setup_diagnostics: false,
            cleanup_diagnostics: false,
            cleanup_diagnostic_events: false,
            #[cfg(feature = "perf-tests")]
            perf_max_rss_growth_mb_per_hr: None,
            srtp_diagnostics: false,
            rtp_diagnostics: false,
            media_sdp_diagnostics: false,
            auto_emit_extra_headers: Vec::new(),
        }
    }

    /// Create a config bound to a specific IP address (e.g. for LAN or production).
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::Config;
    /// let config = Config::on("alice", "192.168.1.50".parse().unwrap(), 5060);
    /// assert_eq!(config.local_uri, "sip:alice@192.168.1.50:5060");
    /// ```
    pub fn on(name: &str, ip: IpAddr, port: u16) -> Self {
        Self {
            local_ip: ip,
            sip_port: port,
            media_port_start: Self::DEFAULT_MEDIA_PORT_START,
            media_port_end: Self::DEFAULT_MEDIA_PORT_END,
            media_port_capacity: None,
            bind_addr: SocketAddr::new(ip, port),
            sip_advertised_addr: None,
            state_table_path: None,
            local_uri: format!("sip:{}@{}:{}", name, ip, port),
            use_100rel: RelUsage::default(),
            auto_180_ringing: true,
            auto_100_trying: true,
            fast_auto_accept_incoming_calls: false,
            setup_teardown_timeout_secs: Self::DEFAULT_SETUP_TEARDOWN_TIMEOUT_SECS,
            active_call_no_media_timeout_secs: 0,
            active_call_media_idle_timeout_secs: 0,
            session_timer_secs: None,
            session_timer_min_se: 90,
            credentials: None,
            auth: None,
            pai_uri: None,
            sip_trace: crate::api::events::SipTraceConfig::default(),
            trace_redaction: Some(crate::api::trace_redactor::default_trace_redactor()),
            outbound_proxy_uri: None,
            sip_outbound_enabled: false,
            sip_instance: None,
            outbound_keepalive_interval_secs: 25,
            registration_auto_refresh: true,
            registration_refresh_jitter_percent: 5,
            unregister_on_shutdown_timeout_secs: 3,
            sip_tls_mode: SipTlsMode::Disabled,
            sip_contact_mode: SipContactMode::ReachableContact,
            tls_bind_addr: None,
            tls_advertised_addr: None,
            contact_uri: None,
            tls_cert_path: None,
            tls_key_path: None,
            tls_client_cert_path: None,
            tls_client_key_path: None,
            tls_extra_ca_path: None,
            tls_server_client_auth:
                rvoip_sip_transport::transport::tls::TlsServerClientAuthConfig::default(),
            #[cfg(feature = "dev-insecure-tls")]
            tls_insecure_skip_verify: false,
            offer_srtp: false,
            srtp_required: false,
            amr_dtx: false,
            amr_auto_cmr: false,
            amr_mode_set: None,
            srtp_offered_suites: SrtpSuitePolicy::Default.suites(),
            media_public_addr: None,
            media_mode: MediaMode::Enabled,
            media_session_capacity: None,
            rtp_session_buffer_config: RtpSessionBufferConfig::default(),
            rtp_transport_buffer_config: RtpTransportBufferConfig::default(),
            media_session_controller_config: MediaSessionControllerConfig::default(),
            stun_server: None,
            comfort_noise_enabled: false,
            strict_codec_matching: true,
            offered_codecs: vec![0, 8, 101],
            g729_annex_b: true,
            incoming_call_channel_capacity: 1000,
            state_event_channel_capacity: 1000,
            sip_transport_channel_capacity: 10_000,
            sip_transport_dispatch_workers: None,
            sip_transport_dispatch_queue_capacity: None,
            sip_udp_recv_buffer_size: None,
            sip_udp_send_buffer_size: None,
            sip_udp_parse_workers: None,
            sip_udp_parse_queue_capacity: None,
            sip_udp_parse_dispatch: None,
            transaction_event_channel_capacity: 10_000,
            sip_transaction_dispatch_workers: None,
            sip_transaction_dispatch_queue_capacity: None,
            sip_transaction_command_channel_capacity: None,
            sip_transaction_dispatch_priority_burst_max: None,
            sip_invite_2xx_retransmit_max_due_per_tick: None,
            sip_dialog_dispatch_workers: None,
            sip_dialog_dispatch_queue_capacity: None,
            global_event_channel_capacity: Self::DEFAULT_APP_EVENT_CHANNEL_CAPACITY,
            session_event_dispatcher_workers: default_session_event_dispatcher_workers(),
            session_event_dispatcher_channel_capacity: Self::DEFAULT_APP_EVENT_CHANNEL_CAPACITY,
            server_call_capacity: None,
            server_retained_lifecycle_capacity: None,
            server_call_admission_limit: None,
            server_call_admission_soft_limit: None,
            server_call_admission_pacing_delay_ms: None,
            server_overload_retry_after_secs: Some(1),
            sip_udp_diagnostics: false,
            sip_transaction_timing_diagnostics: false,
            sip_dialog_timing_diagnostics: false,
            media_setup_diagnostics: false,
            cleanup_diagnostics: false,
            cleanup_diagnostic_events: false,
            #[cfg(feature = "perf-tests")]
            perf_max_rss_growth_mb_per_hr: None,
            srtp_diagnostics: false,
            rtp_diagnostics: false,
            media_sdp_diagnostics: false,
            auto_emit_extra_headers: Vec::new(),
        }
    }

    /// Deployment profile for local examples and integration tests.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::Config;
    /// let config = Config::local_lab("alice", 5060);
    /// assert_eq!(config.local_uri, "sip:alice@127.0.0.1:5060");
    /// ```
    pub fn local_lab(name: &str, port: u16) -> Self {
        Self::local(name, port)
    }

    /// Deployment profile for a directly reachable LAN PBX endpoint.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::Config;
    /// let bind = "0.0.0.0:5060".parse().unwrap();
    /// let advertised = "192.168.1.50:5060".parse().unwrap();
    /// let config = Config::lan_pbx("alice", bind, advertised);
    /// assert_eq!(config.sip_advertised_addr, Some(advertised));
    /// ```
    pub fn lan_pbx(name: &str, bind_addr: SocketAddr, advertised_addr: SocketAddr) -> Self {
        let mut config = Self::on(name, bind_addr.ip(), bind_addr.port());
        config.bind_addr = bind_addr;
        config.sip_advertised_addr = Some(advertised_addr);
        config.media_public_addr = Some(SocketAddr::new(advertised_addr.ip(), 0));
        config
    }

    /// Deployment profile for Asterisk TLS + SDES-SRTP with registered-flow
    /// reuse over the outbound registration connection.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::{Config, SipTlsMode};
    /// let bind = "0.0.0.0:5061".parse().unwrap();
    /// let config = Config::asterisk_tls_registered_flow(
    ///     "alice",
    ///     bind,
    ///     "urn:uuid:00000000-0000-0000-0000-000000000001",
    /// );
    /// assert_eq!(config.sip_tls_mode, SipTlsMode::ClientOnly);
    /// assert!(config.srtp_required);
    /// ```
    pub fn asterisk_tls_registered_flow(
        name: &str,
        bind_addr: SocketAddr,
        sip_instance: impl Into<String>,
    ) -> Self {
        let mut config = Self::on(name, bind_addr.ip(), bind_addr.port())
            .tls_registered_flow_symmetric(sip_instance);
        config.bind_addr = bind_addr;
        config.offer_srtp = true;
        config.srtp_required = true;
        config
    }

    /// Deployment profile for FreeSWITCH/Sofia's internal LAN profile.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::Config;
    /// let bind = "192.168.1.50:5060".parse().unwrap();
    /// let config = Config::freeswitch_internal("alice", bind);
    /// assert!(config.strict_codec_matching);
    /// ```
    pub fn freeswitch_internal(name: &str, bind_addr: SocketAddr) -> Self {
        let mut config = Self::on(name, bind_addr.ip(), bind_addr.port());
        config.bind_addr = bind_addr;
        config.strict_codec_matching = true;
        config
    }

    /// Deployment profile for FreeSWITCH TLS + mandatory SDES-SRTP with a
    /// directly reachable TLS Contact.
    ///
    /// The profile enables SIP TLS listener mode, mandatory SRTP, strict codec
    /// matching, and the FreeSWITCH-compatible SDES suite policy. It does not
    /// pin a single crypto suite; SDP offer/answer decides the negotiated
    /// suite.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::Config;
    /// let udp_bind = "0.0.0.0:5060".parse().unwrap();
    /// let tls_bind = "0.0.0.0:5061".parse().unwrap();
    /// let config = Config::freeswitch_tls_srtp_reachable_contact(
    ///     "alice",
    ///     udp_bind,
    ///     tls_bind,
    ///     "cert.pem",
    ///     "key.pem",
    /// );
    /// assert!(config.offer_srtp);
    /// assert!(config.srtp_required);
    /// ```
    pub fn freeswitch_tls_srtp_reachable_contact(
        name: &str,
        bind_addr: SocketAddr,
        tls_bind_addr: SocketAddr,
        cert_path: impl Into<std::path::PathBuf>,
        key_path: impl Into<std::path::PathBuf>,
    ) -> Self {
        let mut config = Self::freeswitch_internal(name, bind_addr)
            .tls_reachable_contact(tls_bind_addr, cert_path, key_path)
            .with_srtp_suite_policy(SrtpSuitePolicy::FreeSwitchCompatible);
        config.offer_srtp = true;
        config.srtp_required = true;
        config
    }

    /// Deployment profile for carrier/SBC style outbound proxy operation.
    ///
    /// This is a conservative starting point: TLS client mode, registered-flow
    /// Contact behavior, mandatory SDES-SRTP, explicit public media address,
    /// and a preloaded outbound proxy route for INVITEs. REGISTER proxy,
    /// Service-Route/Path, SRV/NAPTR, and ICE remain separate hardening work.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::{Config, SipContactMode};
    /// let bind = "0.0.0.0:5061".parse().unwrap();
    /// let public = "203.0.113.10:5061".parse().unwrap();
    /// let config = Config::carrier_sbc(
    ///     "alice",
    ///     bind,
    ///     public,
    ///     "sips:sbc.example.com:5061;lr",
    ///     "urn:uuid:00000000-0000-0000-0000-000000000001",
    /// );
    /// assert_eq!(config.sip_contact_mode, SipContactMode::RegisteredFlowRfc5626);
    /// assert!(config.srtp_required);
    /// ```
    pub fn carrier_sbc(
        name: &str,
        bind_addr: SocketAddr,
        public_addr: SocketAddr,
        outbound_proxy_uri: impl Into<String>,
        sip_instance: impl Into<String>,
    ) -> Self {
        let mut config = Self::on(name, bind_addr.ip(), bind_addr.port())
            .tls_registered_flow_rfc5626(sip_instance);
        config.bind_addr = bind_addr;
        config.sip_advertised_addr = Some(public_addr);
        config.tls_advertised_addr = Some(public_addr);
        config.media_public_addr = Some(SocketAddr::new(public_addr.ip(), 0));
        config.outbound_proxy_uri = Some(outbound_proxy_uri.into());
        config.offer_srtp = true;
        config.srtp_required = true;
        config
    }

    /// Placeholder deployment profile for a SIP proxy plus RTPengine lab.
    ///
    /// The signaling side preloads the outbound proxy route; media relay
    /// integration remains explicit because RTPengine control belongs above
    /// rvoip-sip.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::Config;
    /// let bind = "0.0.0.0:5060".parse().unwrap();
    /// let advertised = "192.168.1.50:5060".parse().unwrap();
    /// let config = Config::proxy_rtpengine(
    ///     "alice",
    ///     bind,
    ///     advertised,
    ///     "sip:proxy.example.com;lr",
    /// );
    /// assert_eq!(config.outbound_proxy_uri.as_deref(), Some("sip:proxy.example.com;lr"));
    /// ```
    pub fn proxy_rtpengine(
        name: &str,
        bind_addr: SocketAddr,
        advertised_addr: SocketAddr,
        outbound_proxy_uri: impl Into<String>,
    ) -> Self {
        let mut config = Self::lan_pbx(name, bind_addr, advertised_addr);
        config.outbound_proxy_uri = Some(outbound_proxy_uri.into());
        config
    }

    /// Replace the SDES-SRTP offer suite list with a named policy.
    ///
    /// This only changes the advertised suite order/list. Callers still choose
    /// whether SRTP is offered or mandatory with [`Config::offer_srtp`] and
    /// [`Config::srtp_required`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::{Config, SrtpSuitePolicy};
    /// let config = Config::local("alice", 5060)
    ///     .with_srtp_suite_policy(SrtpSuitePolicy::FreeSwitchCompatible);
    /// assert_eq!(config.srtp_offered_suites.len(), 4);
    /// ```
    pub fn with_srtp_suite_policy(mut self, policy: SrtpSuitePolicy) -> Self {
        self.srtp_offered_suites = policy.suites();
        self
    }

    /// Set the G.729 Annex B SDP preference used when PT 18 is advertised.
    ///
    /// `true` emits `a=fmtp:18 annexb=yes` for G.729A plus Annex B
    /// VAD/DTX/CNG. `false` emits `a=fmtp:18 annexb=no` for G.729A speech
    /// only.
    pub fn with_g729_annex_b(mut self, enabled: bool) -> Self {
        self.g729_annex_b = enabled;
        self
    }

    /// Enable AMR discontinuous transmission (silence as SID/comfort noise).
    ///
    /// Local sender policy, never negotiated — see the field's documentation
    /// for the RFC 4867 reasoning. Ignored by every codec but AMR.
    pub fn with_amr_dtx(mut self, enabled: bool) -> Self {
        self.amr_dtx = enabled;
        self
    }

    /// The configured AMR DTX policy.
    pub fn amr_dtx(&self) -> bool {
        self.amr_dtx
    }

    /// Let AMR sessions issue automatic damped codec-mode requests.
    ///
    /// Local policy; explicit `request_peer_codec_mode` calls always outrank
    /// it. Ignored by every codec but AMR.
    pub fn with_amr_auto_cmr(mut self, enabled: bool) -> Self {
        self.amr_auto_cmr = enabled;
        self
    }

    /// The configured automatic-CMR policy.
    pub fn amr_auto_cmr(&self) -> bool {
        self.amr_auto_cmr
    }

    /// Restrict AMR to these mode indices, offered as RFC 4867 `mode-set`.
    ///
    /// Bi-directional and negotiated: one active set governs both directions.
    /// An empty slice clears the restriction (no `mode-set` is offered, the
    /// correct shape for an endpoint supporting every mode). Out-of-range
    /// members are dropped at offer time rather than offered; the rendered
    /// list is sorted and deduplicated so an offer and its echo compare byte
    /// for byte. Ignored by every codec but AMR.
    pub fn with_amr_mode_set(mut self, modes: &[u8]) -> Self {
        self.amr_mode_set = if modes.is_empty() {
            None
        } else {
            Some(modes.to_vec())
        };
        self
    }

    /// The configured AMR `mode-set` restriction, if any.
    pub fn amr_mode_set(&self) -> Option<&[u8]> {
        self.amr_mode_set.as_deref()
    }

    /// Set the legacy incoming-call compatibility channel capacity.
    ///
    /// The default is `1000`, which is enough for normal bursty call-arrival
    /// workloads while still bounding memory. Values below `1` are rejected by
    /// [`Config::validate`].
    pub fn with_incoming_call_channel_capacity(mut self, capacity: usize) -> Self {
        self.incoming_call_channel_capacity = capacity;
        self
    }

    /// Set SIP signaling channel capacities from one expected-concurrency knob.
    ///
    /// `capacity` is the expected number of concurrent or burst-arriving calls.
    /// Per-call queues use that value directly; lower-level transport and
    /// transaction event queues use `capacity * 10` because a single call
    /// generates multiple SIP messages and transaction lifecycle events.
    /// Values below `1` are rejected by [`Config::validate`].
    pub fn with_channel_capacity(mut self, capacity: usize) -> Self {
        let event_capacity = capacity.saturating_mul(10);
        self.incoming_call_channel_capacity = capacity;
        self.state_event_channel_capacity = capacity;
        self.sip_transport_channel_capacity = event_capacity;
        self.transaction_event_channel_capacity = event_capacity;
        self.global_event_channel_capacity = event_capacity;
        self.session_event_dispatcher_channel_capacity = event_capacity;
        self
    }

    /// Set a server-side active-call capacity profile.
    ///
    /// This reserves hot lookup indexes for `capacity` active or
    /// burst-arriving calls without changing event queue sizes. Clients should
    /// usually leave this unset and use the defaults.
    pub fn with_server_capacity(mut self, capacity: usize) -> Self {
        self.server_call_capacity = Some(capacity);
        self
    }

    /// Set the bound for active and retained SIP lifecycle records.
    ///
    /// Configure [`Config::server_call_capacity`] as well. The retained bound
    /// must cover the active capacity and enough completed calls for the
    /// lifecycle anti-reuse horizon.
    pub fn with_server_retained_lifecycle_capacity(mut self, capacity: usize) -> Self {
        self.server_retained_lifecycle_capacity = Some(capacity);
        self
    }

    /// Set the server-side active-call admission limit.
    ///
    /// Unlike [`Config::with_server_capacity`], this is enforced at runtime for
    /// inbound INVITEs. Once the session store reaches `limit`, additional
    /// inbound calls are rejected with SIP `503 Service Unavailable` and the
    /// configured `Retry-After` header.
    pub fn with_server_call_admission_limit(mut self, limit: usize) -> Self {
        self.server_call_admission_limit = Some(limit);
        self
    }

    /// Set the soft threshold where server-side inbound admission starts
    /// pacing instead of immediately admitting new calls.
    pub fn with_server_call_admission_soft_limit(mut self, limit: usize) -> Self {
        self.server_call_admission_soft_limit = Some(limit);
        self
    }

    /// Set the delay used while server-side inbound admission is above the
    /// soft threshold but below the hard limit.
    pub fn with_server_call_admission_pacing_delay_ms(mut self, delay_ms: u64) -> Self {
        self.server_call_admission_pacing_delay_ms = Some(delay_ms);
        self
    }

    /// Remove the server-side active-call admission limit.
    pub fn without_server_call_admission_limit(mut self) -> Self {
        self.server_call_admission_limit = None;
        self
    }

    /// Set the `Retry-After` value used for server overload rejections.
    pub fn with_server_overload_retry_after_secs(mut self, seconds: u32) -> Self {
        self.server_overload_retry_after_secs = Some(seconds);
        self
    }

    /// Omit `Retry-After` from server overload rejections.
    pub fn without_server_overload_retry_after(mut self) -> Self {
        self.server_overload_retry_after_secs = None;
        self
    }

    /// Apply a high-CPS UDP auto-answer profile.
    ///
    /// This keeps media enabled, suppresses automatic provisional responses,
    /// sizes SIP event queues from `capacity`, and configures the UDP receive
    /// path for a single fast parse worker with a queue sized to the same
    /// burst capacity. It disables automatic `100 Trying` because fixed
    /// immediate-answer services should send the final response before Timer
    /// 100 would fire, and avoiding the timer task/message reduces hot-path
    /// work. It does not enable the fused fast-auto-accept path yet; that
    /// remains an explicit opt-in until the 8000 CPS cleanup/retransmit target
    /// is stable. It raises
    /// [`Config::sip_transaction_command_channel_capacity`] to
    /// `(capacity / 8).clamp(128, 1000)` unless an earlier setter already set
    /// an explicit value. It does not enlarge socket buffers and does not set
    /// [`Config::server_call_capacity`]. It also leaves
    /// [`Config::sip_transaction_dispatch_priority_burst_max`] and
    /// [`Config::sip_invite_2xx_retransmit_max_due_per_tick`] unset so load
    /// tests can tune dispatch fairness and retransmit pacing explicitly.
    pub fn with_high_cps_udp_auto_answer(mut self, capacity: usize) -> Self {
        self = self.with_channel_capacity(capacity);
        self.auto_180_ringing = false;
        self.auto_100_trying = false;
        self.sip_udp_parse_workers = Some(1);
        self.sip_udp_parse_queue_capacity = Some(capacity);
        self.sip_transaction_command_channel_capacity
            .get_or_insert_with(|| (capacity / 8).clamp(128, 1000));
        self.media_mode = MediaMode::Enabled;
        self
    }

    /// Apply a YAML-backed performance recipe to this config.
    ///
    /// When [`crate::PerformanceConfig::recipe_path`] is set, that YAML file
    /// is loaded. Otherwise the bundled default recipe book is used.
    pub fn try_with_performance_config(
        self,
        performance: crate::api::performance::PerformanceConfig,
    ) -> Result<Self> {
        let book = if let Some(path) = &performance.recipe_path {
            crate::api::performance::PerformanceRecipeBook::from_path(path)?
        } else {
            crate::api::performance::PerformanceRecipeBook::bundled()?
        };
        book.apply(self, &performance)
    }

    /// Apply the bundled PBX media server performance recipe.
    ///
    /// This convenience helper applies the bundled
    /// `pbx-media-server` YAML recipe. Use
    /// [`Config::try_with_performance_config`] with a custom
    /// [`crate::PerformanceConfig::recipe_path`] when deployments need a
    /// modified recipe book.
    pub fn with_pbx_media_server_performance(self, capacity: usize) -> Self {
        self.try_with_performance_config(
            crate::api::performance::PerformanceConfig::pbx_media_server(capacity),
        )
        .expect("bundled pbx-media-server performance recipe is valid")
    }

    /// Apply the bundled signaling-only high-performance server recipe.
    ///
    /// This convenience helper applies the bundled
    /// `signaling-only-server-high-performance` YAML recipe. Use
    /// [`Config::try_with_performance_config`] with a custom
    /// [`crate::PerformanceConfig::recipe_path`] when deployments need a
    /// modified recipe book.
    pub fn with_signaling_only_server_high_performance(
        self,
        capacity: usize,
        sdp_rtp_port: u16,
    ) -> Self {
        self.try_with_performance_config(
            crate::api::performance::PerformanceConfig::signaling_only_server_high_performance(
                capacity,
            )
            .with_signaling_only_rtp_port(sdp_rtp_port),
        )
        .expect("bundled signaling-only-server-high-performance performance recipe is valid")
    }

    fn dialog_index_capacity_hint(&self) -> usize {
        self.server_call_capacity
            .unwrap_or(self.transaction_event_channel_capacity)
            .max(1)
    }

    fn transaction_index_capacity_hint(&self) -> usize {
        self.server_call_capacity
            // INVITE server transactions, BYE server transactions, ACK
            // indexes, and retransmission caches can remain live beyond the
            // active-call count. Size for the short transaction-retention
            // window, not just simultaneous dialogs.
            .map(|capacity| capacity.saturating_mul(16))
            .unwrap_or(self.transaction_event_channel_capacity)
            .max(1)
    }

    /// Set the RTP media port range.
    ///
    /// The default range is [`Config::DEFAULT_MEDIA_PORT_START`] through
    /// [`Config::DEFAULT_MEDIA_PORT_END`]. Values are checked by
    /// [`Config::validate`].
    pub fn with_media_ports(mut self, start: u16, end: u16) -> Self {
        self.media_port_start = start;
        self.media_port_end = end;
        self.media_port_capacity = None;
        self
    }

    /// Set the RTP media port range by start port and requested capacity.
    ///
    /// Validation rejects capacity `0`, start ports below [`MIN_PORT`], and
    /// requested capacities that do not fit in the `u16` port space.
    pub fn with_media_port_capacity(mut self, start: u16, capacity: usize) -> Self {
        self.media_port_start = start;
        self.media_port_end = capacity
            .checked_sub(1)
            .and_then(|offset| (start as usize).checked_add(offset))
            .and_then(|end| u16::try_from(end).ok())
            .unwrap_or(u16::MAX);
        self.media_port_capacity = Some(capacity);
        self
    }

    /// Advertise a concrete peer-facing SIP address while retaining the configured local
    /// bind address. Useful for containers, 1:1 NAT, and host networking.
    pub fn with_sip_advertised_addr(mut self, address: SocketAddr) -> Self {
        self.sip_advertised_addr = Some(address);
        self
    }

    /// Return to bind-derived SIP Via/Contact generation.
    pub fn without_sip_advertised_addr(mut self) -> Self {
        self.sip_advertised_addr = None;
        self
    }

    /// Advertise a routable RTP address in SDP. Port `0` means retain each
    /// session's allocated local RTP port while replacing only the IP.
    pub fn with_media_public_addr(mut self, address: SocketAddr) -> Self {
        self.media_public_addr = Some(address);
        self
    }

    /// Return to local-address or STUN-derived RTP advertisement.
    pub fn without_media_public_addr(mut self) -> Self {
        self.media_public_addr = None;
        self
    }

    /// Enable or disable automatic `180 Ringing` on inbound INVITEs.
    ///
    /// `true` is the PBX-friendly default. `false` is useful for IVR,
    /// call-center, and benchmark listeners that answer immediately with a
    /// final response.
    pub fn with_auto_180_ringing(mut self, enabled: bool) -> Self {
        self.auto_180_ringing = enabled;
        self
    }

    /// Enable or disable the automatic RFC 3261 `100 Trying` timer.
    ///
    /// The default is `true`. High-CPS immediate-answer services can set this
    /// to `false` to avoid spawning a timer task for every INVITE when a final
    /// response is expected well before Timer 100 would fire.
    pub fn with_auto_100_trying(mut self, enabled: bool) -> Self {
        self.auto_100_trying = enabled;
        self
    }

    /// Enable or disable immediate session-path accept for inbound INVITEs.
    ///
    /// This is intentionally separate from [`Config::auto_180_ringing`]:
    /// disabling 180 only removes the provisional response, while enabling
    /// this option sends the final answer before app callbacks run.
    pub fn with_fast_auto_accept_incoming_calls(mut self, enabled: bool) -> Self {
        self.fast_auto_accept_incoming_calls = enabled;
        self
    }

    /// Set the watchdog timeout for setup teardown states.
    ///
    /// The watchdog only fires if a session is still in the same setup state
    /// after the timeout. It then drives the existing state-table
    /// `DialogTimeout` transition so cleanup and terminal event publication
    /// use the normal path. Use `0` to disable the watchdog.
    pub fn with_setup_teardown_timeout_secs(mut self, seconds: u64) -> Self {
        self.setup_teardown_timeout_secs = seconds;
        self
    }

    /// Set the watchdog timeout for answered inbound calls with no RTP.
    ///
    /// The watchdog is disabled when set to `0`. When enabled, it only arms
    /// for UAS calls that have reached `Active` with a media session and
    /// releases the call if the media session's RTP receive counter has not
    /// advanced by the timeout.
    pub fn with_active_call_no_media_timeout_secs(mut self, seconds: u64) -> Self {
        self.active_call_no_media_timeout_secs = seconds;
        self
    }

    /// Set the watchdog timeout for answered inbound calls whose RTP stops.
    ///
    /// The watchdog is disabled when set to `0`. When enabled, it only arms
    /// for UAS calls that have reached `Active` with a media session. The
    /// watchdog disarms while RTP packet counts advance and releases the call
    /// if the packet count stops advancing for the configured interval.
    pub fn with_active_call_media_idle_timeout_secs(mut self, seconds: u64) -> Self {
        self.active_call_media_idle_timeout_secs = seconds;
        self
    }

    /// Set media allocation behavior.
    pub fn with_media_mode(mut self, mode: MediaMode) -> Self {
        self.media_mode = mode;
        self
    }

    /// Set the media-core session and RTP allocator capacity hint.
    pub fn with_media_session_capacity(mut self, capacity: usize) -> Self {
        self.media_session_capacity = Some(capacity);
        self
    }

    /// Set RTP session queue sizing for SIP media calls.
    pub fn with_rtp_session_buffer_config(mut self, config: RtpSessionBufferConfig) -> Self {
        self.rtp_session_buffer_config = config;
        self
    }

    /// Set RTP transport event and receive buffer sizing for SIP media calls.
    pub fn with_rtp_transport_buffer_config(mut self, config: RtpTransportBufferConfig) -> Self {
        self.rtp_transport_buffer_config = config;
        self
    }

    /// Set media-core controller pool and capacity tuning for SIP media calls.
    pub fn with_media_session_controller_config(
        mut self,
        config: MediaSessionControllerConfig,
    ) -> Self {
        self.rtp_session_buffer_config = config.rtp_session_buffer_config;
        self.rtp_transport_buffer_config = config.rtp_transport_buffer_config;
        self.media_session_controller_config = config;
        self
    }

    /// Enable or disable real media-core RTP allocation.
    ///
    /// Disabling media switches to [`MediaMode::SignalingOnly`] with SDP port
    /// `9`, the discard port convention used for signaling-only tests.
    pub fn with_media_enabled(mut self, enabled: bool) -> Self {
        self.media_mode = if enabled {
            MediaMode::Enabled
        } else {
            MediaMode::SignalingOnly { sdp_rtp_port: 9 }
        };
        self
    }

    /// Skip media-core RTP allocation while still generating SDP.
    pub fn with_signaling_only_media(mut self, sdp_rtp_port: u16) -> Self {
        self.media_mode = MediaMode::SignalingOnly { sdp_rtp_port };
        self
    }

    /// Set the internal state-machine event channel capacity.
    ///
    /// The default is `1000`. Values below `1` are rejected by
    /// [`Config::validate`].
    pub fn with_state_event_channel_capacity(mut self, capacity: usize) -> Self {
        self.state_event_channel_capacity = capacity;
        self
    }

    /// Set the SIP transport event channel capacity.
    ///
    /// The default is `10000`. Values below `1` are rejected by
    /// [`Config::validate`].
    pub fn with_sip_transport_channel_capacity(mut self, capacity: usize) -> Self {
        self.sip_transport_channel_capacity = capacity;
        self
    }

    /// Set the SIP transport-manager forwarding worker count.
    ///
    /// Values above `1` enable keyed sharding between transport receive/parse
    /// and transaction-manager ingress. Values below `1` are rejected by
    /// [`Config::validate`].
    pub fn with_sip_transport_dispatch_workers(mut self, workers: usize) -> Self {
        self.sip_transport_dispatch_workers = Some(workers);
        self
    }

    /// Set the SIP transport-manager forwarding queue capacity.
    ///
    /// `None` uses [`Config::sip_transport_channel_capacity`]. Values below
    /// `1` are rejected by [`Config::validate`].
    pub fn with_sip_transport_dispatch_queue_capacity(mut self, capacity: usize) -> Self {
        self.sip_transport_dispatch_queue_capacity = Some(capacity);
        self
    }

    /// Set SIP transport-manager forwarding worker and queue overrides
    /// together.
    pub fn with_sip_transport_dispatch_config(
        mut self,
        workers: Option<usize>,
        queue_capacity: Option<usize>,
    ) -> Self {
        self.sip_transport_dispatch_workers = workers;
        self.sip_transport_dispatch_queue_capacity = queue_capacity;
        self
    }

    /// Set SIP UDP socket receive/send buffer sizes in bytes.
    ///
    /// Use this for high-CPS server profiles where the kernel UDP queue must
    /// absorb bursts while application queues drain. Pass `None` for either
    /// side to keep that side at the OS default.
    pub fn with_sip_udp_socket_buffers(
        mut self,
        recv_buffer_size: Option<usize>,
        send_buffer_size: Option<usize>,
    ) -> Self {
        self.sip_udp_recv_buffer_size = recv_buffer_size;
        self.sip_udp_send_buffer_size = send_buffer_size;
        self
    }

    /// Set the SIP UDP receive socket buffer size (`SO_RCVBUF`) in bytes.
    pub fn with_sip_udp_recv_buffer_size(mut self, size: usize) -> Self {
        self.sip_udp_recv_buffer_size = Some(size);
        self
    }

    /// Set the SIP UDP send socket buffer size (`SO_SNDBUF`) in bytes.
    pub fn with_sip_udp_send_buffer_size(mut self, size: usize) -> Self {
        self.sip_udp_send_buffer_size = Some(size);
        self
    }

    /// Set the UDP parse worker count.
    pub fn with_sip_udp_parse_workers(mut self, workers: usize) -> Self {
        self.sip_udp_parse_workers = Some(workers);
        self
    }

    /// Set the per-worker UDP parse queue capacity.
    pub fn with_sip_udp_parse_queue_capacity(mut self, capacity: usize) -> Self {
        self.sip_udp_parse_queue_capacity = Some(capacity);
        self
    }

    /// Set the UDP parse worker dispatch strategy.
    pub fn with_sip_udp_parse_dispatch(
        mut self,
        dispatch: rvoip_sip_transport::UdpParseDispatch,
    ) -> Self {
        self.sip_udp_parse_dispatch = Some(dispatch);
        self
    }

    /// Set UDP parse worker and queue overrides together.
    pub fn with_sip_udp_parse_config(
        mut self,
        workers: Option<usize>,
        queue_capacity: Option<usize>,
    ) -> Self {
        self.sip_udp_parse_workers = workers;
        self.sip_udp_parse_queue_capacity = queue_capacity;
        self
    }

    /// Set the transaction-manager event channel capacity.
    ///
    /// The default is `10000`. Values below `1` are rejected by
    /// [`Config::validate`].
    pub fn with_transaction_event_channel_capacity(mut self, capacity: usize) -> Self {
        self.transaction_event_channel_capacity = capacity;
        self
    }

    /// Set the transaction-manager ingress dispatch worker count.
    ///
    /// Values above `1` enable keyed sharding of incoming transport events.
    /// Values below `1` are rejected by [`Config::validate`].
    pub fn with_sip_transaction_dispatch_workers(mut self, workers: usize) -> Self {
        self.sip_transaction_dispatch_workers = Some(workers);
        self
    }

    /// Set the transaction-manager ingress dispatch queue capacity.
    ///
    /// `None` uses [`Config::transaction_event_channel_capacity`]. Values below
    /// `1` are rejected by [`Config::validate`].
    pub fn with_sip_transaction_dispatch_queue_capacity(mut self, capacity: usize) -> Self {
        self.sip_transaction_dispatch_queue_capacity = Some(capacity);
        self
    }

    /// Set the per-transaction command channel capacity.
    ///
    /// Values below `1` are rejected by [`Config::validate`]. This should be
    /// tuned only for measured high-CPS profiles because it is allocated per
    /// live transaction, not once per endpoint.
    pub fn with_sip_transaction_command_channel_capacity(mut self, capacity: usize) -> Self {
        self.sip_transaction_command_channel_capacity = Some(capacity);
        self
    }

    /// Set the transaction-manager ACK/BYE priority burst limit.
    ///
    /// This only affects multi-worker transaction dispatch. After this many
    /// consecutive priority-lane ACK/BYE events, a worker processes one ready
    /// normal-lane item before resuming priority work. Use lower values when
    /// INVITE/CANCEL/response work is being starved; use higher values when
    /// BYE/ACK latency is the bottleneck. Values below `1` are rejected by
    /// [`Config::validate`].
    pub fn with_sip_transaction_dispatch_priority_burst_max(mut self, max_burst: usize) -> Self {
        self.sip_transaction_dispatch_priority_burst_max = Some(max_burst);
        self
    }

    /// Set the cached INVITE `2xx` retransmission maintenance budget.
    ///
    /// The value is the maximum number of cached INVITE `2xx` responses the
    /// transaction manager may proactively resend per 100 ms tick. Lower values
    /// pace UDP send bursts; higher values clear retransmission backlog faster
    /// when the host send path has capacity. Values below `1` are rejected by
    /// [`Config::validate`].
    pub fn with_sip_invite_2xx_retransmit_max_due_per_tick(
        mut self,
        max_due_per_tick: usize,
    ) -> Self {
        self.sip_invite_2xx_retransmit_max_due_per_tick = Some(max_due_per_tick);
        self
    }

    /// Set transaction-manager ingress worker and queue overrides together.
    pub fn with_sip_transaction_dispatch_config(
        mut self,
        workers: Option<usize>,
        queue_capacity: Option<usize>,
    ) -> Self {
        self.sip_transaction_dispatch_workers = workers;
        self.sip_transaction_dispatch_queue_capacity = queue_capacity;
        self
    }

    /// Set the rvoip-sip-dialog transaction-event dispatch worker count.
    ///
    /// Values above `1` enable keyed sharding of transaction events before
    /// dialog protocol handling. Values below `1` are rejected by
    /// [`Config::validate`].
    pub fn with_sip_dialog_dispatch_workers(mut self, workers: usize) -> Self {
        self.sip_dialog_dispatch_workers = Some(workers);
        self
    }

    /// Set the rvoip-sip-dialog transaction-event dispatch queue capacity.
    ///
    /// `None` uses the dialog max-dialog capacity hint. Values below `1` are
    /// rejected by [`Config::validate`].
    pub fn with_sip_dialog_dispatch_queue_capacity(mut self, capacity: usize) -> Self {
        self.sip_dialog_dispatch_queue_capacity = Some(capacity);
        self
    }

    /// Set rvoip-sip-dialog transaction-event dispatch worker and queue overrides
    /// together.
    pub fn with_sip_dialog_dispatch_config(
        mut self,
        workers: Option<usize>,
        queue_capacity: Option<usize>,
    ) -> Self {
        self.sip_dialog_dispatch_workers = workers;
        self.sip_dialog_dispatch_queue_capacity = queue_capacity;
        self
    }

    /// Set the infra-common global event bus channel capacity.
    ///
    /// The default is `256` ([`Config::DEFAULT_APP_EVENT_CHANNEL_CAPACITY`]); the
    /// `EventCoordinatorConfig` native default of `10000` is overridden by the
    /// unified layer. Values below `1` are rejected by [`Config::validate`].
    pub fn with_global_event_channel_capacity(mut self, capacity: usize) -> Self {
        self.global_event_channel_capacity = capacity;
        self
    }

    /// Set the app-facing event buffering capacity as one knob.
    ///
    /// This sets both [`Config::global_event_channel_capacity`] and
    /// [`Config::session_event_dispatcher_channel_capacity`]. Use the lower
    /// level setters when a deployment needs different capacities for the
    /// global cross-crate broadcast ring and the app-session publish queue.
    pub fn with_app_event_channel_capacity(mut self, capacity: usize) -> Self {
        self.global_event_channel_capacity = capacity;
        self.session_event_dispatcher_channel_capacity = capacity;
        self
    }

    /// Set the app-session event dispatcher worker count.
    ///
    /// Values below `1` are rejected by [`Config::validate`].
    pub fn with_session_event_dispatcher_workers(mut self, workers: usize) -> Self {
        self.session_event_dispatcher_workers = workers;
        self
    }

    /// Set the per-worker app-session event dispatcher queue capacity.
    ///
    /// Values below `1` are rejected by [`Config::validate`].
    pub fn with_session_event_dispatcher_channel_capacity(mut self, capacity: usize) -> Self {
        self.session_event_dispatcher_channel_capacity = capacity;
        self
    }

    /// Enable or disable SIP UDP transport and duplicate-recovery diagnostics.
    pub fn with_sip_udp_diagnostics(mut self, enabled: bool) -> Self {
        self.sip_udp_diagnostics = enabled;
        self
    }

    /// Enable or disable high-cardinality transaction timing diagnostics.
    pub fn with_sip_transaction_timing_diagnostics(mut self, enabled: bool) -> Self {
        self.sip_transaction_timing_diagnostics = enabled;
        self
    }

    /// Enable or disable high-cardinality dialog timing diagnostics.
    pub fn with_sip_dialog_timing_diagnostics(mut self, enabled: bool) -> Self {
        self.sip_dialog_timing_diagnostics = enabled;
        self
    }

    /// Enable or disable media setup/teardown timing diagnostics.
    pub fn with_media_setup_diagnostics(mut self, enabled: bool) -> Self {
        self.media_setup_diagnostics = enabled;
        self
    }

    /// Enable or disable cleanup-stage timing diagnostics.
    pub fn with_cleanup_diagnostics(mut self, enabled: bool) -> Self {
        self.cleanup_diagnostics = enabled;
        self
    }

    /// Enable or disable per-operation cleanup diagnostic event logs.
    pub fn with_cleanup_diagnostic_events(mut self, enabled: bool) -> Self {
        self.cleanup_diagnostic_events = enabled;
        self
    }

    /// Set the RSS growth threshold used by perf soak release gates.
    ///
    /// Compiled only with `perf-tests`; ordinary application builds do not
    /// expose benchmark gate controls.
    #[cfg(feature = "perf-tests")]
    pub fn with_perf_max_rss_growth_mb_per_hr(mut self, limit: f64) -> Self {
        self.perf_max_rss_growth_mb_per_hr = Some(limit);
        self
    }

    /// Enable or disable SRTP negotiation diagnostic log lines.
    pub fn with_srtp_diagnostics(mut self, enabled: bool) -> Self {
        self.srtp_diagnostics = enabled;
        self
    }

    /// Enable or disable RTP packet diagnostic log lines.
    pub fn with_rtp_diagnostics(mut self, enabled: bool) -> Self {
        self.rtp_diagnostics = enabled;
        self
    }

    /// Enable or disable SDP media diagnostic log lines.
    pub fn with_media_sdp_diagnostics(mut self, enabled: bool) -> Self {
        self.media_sdp_diagnostics = enabled;
        self
    }

    /// Configure SIP TLS as a directly reachable Contact listener.
    ///
    /// The UA will both dial outbound TLS and listen on `tls_bind_addr` for
    /// inbound TLS requests sent to its advertised Contact.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::{Config, SipContactMode, SipTlsMode};
    /// let tls_addr = "0.0.0.0:5061".parse().unwrap();
    /// let config = Config::local("alice", 5060)
    ///     .tls_reachable_contact(tls_addr, "cert.pem", "key.pem");
    /// assert_eq!(config.sip_tls_mode, SipTlsMode::ClientAndServer);
    /// assert_eq!(config.sip_contact_mode, SipContactMode::ReachableContact);
    /// ```
    pub fn tls_reachable_contact(
        mut self,
        tls_bind_addr: SocketAddr,
        cert_path: impl Into<std::path::PathBuf>,
        key_path: impl Into<std::path::PathBuf>,
    ) -> Self {
        self.sip_tls_mode = SipTlsMode::ClientAndServer;
        self.sip_contact_mode = SipContactMode::ReachableContact;
        self.tls_bind_addr = Some(tls_bind_addr);
        if self.tls_advertised_addr.is_none() && !tls_bind_addr.ip().is_unspecified() {
            self.tls_advertised_addr = Some(tls_bind_addr);
        }
        self.tls_cert_path = Some(cert_path.into());
        self.tls_key_path = Some(key_path.into());
        self
    }

    /// Configure how the inbound SIP TLS listener verifies client
    /// certificates.
    ///
    /// `Optional` and `Required` policies must name a PEM client-CA bundle;
    /// [`Config::validate`] rejects incomplete configurations. Use this with
    /// a tenant-bound [`crate::SipListenerAuthPolicy`] mTLS fingerprint map.
    pub fn with_tls_server_client_auth(
        mut self,
        policy: rvoip_sip_transport::transport::tls::TlsServerClientAuthConfig,
    ) -> Self {
        self.tls_server_client_auth = policy;
        self
    }

    /// Require every inbound SIP TLS peer to present a certificate chaining
    /// to `client_ca_path`.
    pub fn require_tls_client_certificate(
        self,
        client_ca_path: impl Into<std::path::PathBuf>,
    ) -> Self {
        self.with_tls_server_client_auth(
            rvoip_sip_transport::transport::tls::TlsServerClientAuthConfig::required(
                client_ca_path,
            ),
        )
    }

    /// Verify an inbound SIP TLS client certificate when one is presented,
    /// while allowing peers without a certificate to use another configured
    /// listener authentication mechanism.
    pub fn verify_optional_tls_client_certificate(
        self,
        client_ca_path: impl Into<std::path::PathBuf>,
    ) -> Self {
        self.with_tls_server_client_auth(
            rvoip_sip_transport::transport::tls::TlsServerClientAuthConfig::optional(
                client_ca_path,
            ),
        )
    }

    /// Configure SIP TLS for RFC 5626 registered-flow reuse.
    ///
    /// No TLS listener certificate/key is required because inbound requests
    /// are expected on the outbound registration flow.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::{Config, SipContactMode};
    /// let config = Config::local("alice", 5060)
    ///     .tls_registered_flow_rfc5626("urn:uuid:00000000-0000-0000-0000-000000000001");
    /// assert_eq!(config.sip_contact_mode, SipContactMode::RegisteredFlowRfc5626);
    /// assert!(config.sip_outbound_enabled);
    /// ```
    pub fn tls_registered_flow_rfc5626(mut self, sip_instance: impl Into<String>) -> Self {
        self.sip_tls_mode = SipTlsMode::ClientOnly;
        self.sip_contact_mode = SipContactMode::RegisteredFlowRfc5626;
        self.sip_outbound_enabled = true;
        self.sip_instance = Some(sip_instance.into());
        self
    }

    /// Configure SIP TLS for PBX symmetric-transport registered-flow reuse.
    ///
    /// This mode keeps the registration flow alive but does not require the
    /// registrar to echo RFC 5626 Contact parameters.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::{Config, SipContactMode};
    /// let config = Config::local("alice", 5060)
    ///     .tls_registered_flow_symmetric("urn:uuid:00000000-0000-0000-0000-000000000001");
    /// assert_eq!(config.sip_contact_mode, SipContactMode::RegisteredFlowSymmetric);
    /// ```
    pub fn tls_registered_flow_symmetric(mut self, sip_instance: impl Into<String>) -> Self {
        self.sip_tls_mode = SipTlsMode::ClientOnly;
        self.sip_contact_mode = SipContactMode::RegisteredFlowSymmetric;
        self.sip_instance = Some(sip_instance.into());
        self
    }

    /// Validate the SIP TLS/contact-mode configuration.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rvoip_sip::Config;
    /// let config = Config::local("alice", 5060);
    /// config.validate().unwrap();
    /// ```
    pub fn validate(&self) -> Result<()> {
        let effective_tls_mode = self.effective_tls_mode();

        if let Some(address) = self.sip_advertised_addr {
            if address.ip().is_unspecified() || address.port() == 0 {
                return Err(SessionError::ConfigError(
                    "sip_advertised_addr must have a non-unspecified IP and nonzero port"
                        .to_string(),
                ));
            }
        }
        if let Some(address) = self.tls_advertised_addr {
            if address.ip().is_unspecified() || address.port() == 0 {
                return Err(SessionError::ConfigError(
                    "tls_advertised_addr must have a non-unspecified IP and nonzero port"
                        .to_string(),
                ));
            }
        }
        if self
            .media_public_addr
            .is_some_and(|address| address.ip().is_unspecified())
        {
            return Err(SessionError::ConfigError(
                "media_public_addr must not use an unspecified IP".to_string(),
            ));
        }

        let tls_client_auth_enabled = self.tls_server_client_auth.mode
            != rvoip_sip_transport::transport::tls::TlsClientAuthMode::Disabled;
        if tls_client_auth_enabled {
            if !matches!(
                effective_tls_mode,
                SipTlsMode::ServerOnly | SipTlsMode::ClientAndServer
            ) {
                return Err(SessionError::ConfigError(
                    "inbound TLS client-certificate authentication requires a SIP TLS listener"
                        .to_string(),
                ));
            }
            if self
                .tls_server_client_auth
                .client_ca_path
                .as_deref()
                .is_none_or(|path| path.as_os_str().is_empty())
            {
                return Err(SessionError::ConfigError(
                    "inbound TLS client-certificate authentication requires an explicit client CA bundle"
                        .to_string(),
                ));
            }
        }

        if self.tls_cert_path.is_some() ^ self.tls_key_path.is_some() {
            return Err(SessionError::ConfigError(
                "TLS listener certificate and key must be provided together".to_string(),
            ));
        }
        if self.tls_client_cert_path.is_some() ^ self.tls_client_key_path.is_some() {
            return Err(SessionError::ConfigError(
                "TLS client certificate and key must be provided together".to_string(),
            ));
        }
        if self.registration_refresh_jitter_percent > 50 {
            return Err(SessionError::ConfigError(
                "registration_refresh_jitter_percent must be <= 50".to_string(),
            ));
        }
        if self.incoming_call_channel_capacity == 0 {
            return Err(SessionError::ConfigError(
                "incoming_call_channel_capacity must be at least 1".to_string(),
            ));
        }
        if self.state_event_channel_capacity == 0 {
            return Err(SessionError::ConfigError(
                "state_event_channel_capacity must be at least 1".to_string(),
            ));
        }
        if self.sip_transport_channel_capacity == 0 {
            return Err(SessionError::ConfigError(
                "sip_transport_channel_capacity must be at least 1".to_string(),
            ));
        }
        if matches!(self.sip_transport_dispatch_workers, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_transport_dispatch_workers must be at least 1 when set".to_string(),
            ));
        }
        if let Some(workers) = self.sip_transport_dispatch_workers {
            if workers
                > rvoip_sip_dialog::transaction::transport::MAX_TRANSPORT_EVENT_DISPATCH_WORKERS
            {
                return Err(SessionError::ConfigError(format!(
                    "sip_transport_dispatch_workers must be <= {} when set",
                    rvoip_sip_dialog::transaction::transport::MAX_TRANSPORT_EVENT_DISPATCH_WORKERS
                )));
            }
        }
        if matches!(self.sip_transport_dispatch_queue_capacity, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_transport_dispatch_queue_capacity must be at least 1 when set".to_string(),
            ));
        }
        if matches!(self.sip_udp_recv_buffer_size, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_udp_recv_buffer_size must be at least 1 when set".to_string(),
            ));
        }
        if matches!(self.sip_udp_send_buffer_size, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_udp_send_buffer_size must be at least 1 when set".to_string(),
            ));
        }
        if matches!(self.sip_udp_parse_workers, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_udp_parse_workers must be at least 1 when set".to_string(),
            ));
        }
        if let Some(workers) = self.sip_udp_parse_workers {
            if workers > rvoip_sip_transport::UdpParseConfig::MAX_WORKERS {
                return Err(SessionError::ConfigError(format!(
                    "sip_udp_parse_workers must be <= {} when set",
                    rvoip_sip_transport::UdpParseConfig::MAX_WORKERS
                )));
            }
        }
        if matches!(self.sip_udp_parse_queue_capacity, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_udp_parse_queue_capacity must be at least 1 when set".to_string(),
            ));
        }
        if self.transaction_event_channel_capacity == 0 {
            return Err(SessionError::ConfigError(
                "transaction_event_channel_capacity must be at least 1".to_string(),
            ));
        }
        if matches!(self.sip_transaction_dispatch_workers, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_transaction_dispatch_workers must be at least 1 when set".to_string(),
            ));
        }
        if let Some(workers) = self.sip_transaction_dispatch_workers {
            if workers > rvoip_sip_dialog::transaction::MAX_TRANSACTION_DISPATCH_WORKERS {
                return Err(SessionError::ConfigError(format!(
                    "sip_transaction_dispatch_workers must be <= {} when set",
                    rvoip_sip_dialog::transaction::MAX_TRANSACTION_DISPATCH_WORKERS
                )));
            }
        }
        if matches!(self.sip_transaction_dispatch_queue_capacity, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_transaction_dispatch_queue_capacity must be at least 1 when set".to_string(),
            ));
        }
        if matches!(self.sip_transaction_command_channel_capacity, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_transaction_command_channel_capacity must be at least 1 when set".to_string(),
            ));
        }
        if matches!(self.sip_transaction_dispatch_priority_burst_max, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_transaction_dispatch_priority_burst_max must be at least 1 when set"
                    .to_string(),
            ));
        }
        if matches!(self.sip_invite_2xx_retransmit_max_due_per_tick, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_invite_2xx_retransmit_max_due_per_tick must be at least 1 when set"
                    .to_string(),
            ));
        }
        if matches!(self.sip_dialog_dispatch_workers, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_dialog_dispatch_workers must be at least 1 when set".to_string(),
            ));
        }
        if let Some(workers) = self.sip_dialog_dispatch_workers {
            if workers > rvoip_sip_dialog::manager::MAX_DIALOG_EVENT_DISPATCH_WORKERS {
                return Err(SessionError::ConfigError(format!(
                    "sip_dialog_dispatch_workers must be <= {} when set",
                    rvoip_sip_dialog::manager::MAX_DIALOG_EVENT_DISPATCH_WORKERS
                )));
            }
        }
        if matches!(self.sip_dialog_dispatch_queue_capacity, Some(0)) {
            return Err(SessionError::ConfigError(
                "sip_dialog_dispatch_queue_capacity must be at least 1 when set".to_string(),
            ));
        }
        if self.global_event_channel_capacity == 0 {
            return Err(SessionError::ConfigError(
                "global_event_channel_capacity must be at least 1".to_string(),
            ));
        }
        if self.session_event_dispatcher_workers == 0 {
            return Err(SessionError::ConfigError(
                "session_event_dispatcher_workers must be at least 1".to_string(),
            ));
        }
        if self.session_event_dispatcher_channel_capacity == 0 {
            return Err(SessionError::ConfigError(
                "session_event_dispatcher_channel_capacity must be at least 1".to_string(),
            ));
        }
        if matches!(self.server_call_capacity, Some(0)) {
            return Err(SessionError::ConfigError(
                "server_call_capacity must be at least 1 when set".to_string(),
            ));
        }
        if matches!(self.server_retained_lifecycle_capacity, Some(0)) {
            return Err(SessionError::ConfigError(
                "server_retained_lifecycle_capacity must be at least 1 when set".to_string(),
            ));
        }
        match (
            self.server_call_capacity,
            self.server_retained_lifecycle_capacity,
        ) {
            (None, Some(_)) => {
                return Err(SessionError::ConfigError(
                    "server_retained_lifecycle_capacity requires server_call_capacity".to_string(),
                ));
            }
            (Some(active), Some(retained)) if retained < active => {
                return Err(SessionError::ConfigError(format!(
                    "server_retained_lifecycle_capacity ({retained}) must be >= server_call_capacity ({active})"
                )));
            }
            (None, None) | (Some(_), None) | (Some(_), Some(_)) => {}
        }
        if matches!(self.server_call_admission_limit, Some(0)) {
            return Err(SessionError::ConfigError(
                "server_call_admission_limit must be at least 1 when set".to_string(),
            ));
        }
        if matches!(self.server_call_admission_soft_limit, Some(0)) {
            return Err(SessionError::ConfigError(
                "server_call_admission_soft_limit must be at least 1 when set".to_string(),
            ));
        }
        if let (Some(soft), Some(hard)) = (
            self.server_call_admission_soft_limit,
            self.server_call_admission_limit,
        ) {
            if soft > hard {
                return Err(SessionError::ConfigError(format!(
                    "server_call_admission_soft_limit ({soft}) must be <= server_call_admission_limit ({hard})"
                )));
            }
        }
        if matches!(self.server_call_admission_pacing_delay_ms, Some(0)) {
            return Err(SessionError::ConfigError(
                "server_call_admission_pacing_delay_ms must be at least 1 when set".to_string(),
            ));
        }
        if matches!(self.server_overload_retry_after_secs, Some(0)) {
            return Err(SessionError::ConfigError(
                "server_overload_retry_after_secs must be at least 1 when set".to_string(),
            ));
        }
        if matches!(self.media_session_capacity, Some(0)) {
            return Err(SessionError::ConfigError(
                "media_session_capacity must be at least 1 when set".to_string(),
            ));
        }
        if matches!(self.media_port_capacity, Some(0)) {
            return Err(SessionError::ConfigError(
                "media_port_capacity must be at least 1 when set".to_string(),
            ));
        }
        if self.rtp_session_buffer_config.sender_channel_capacity == 0 {
            return Err(SessionError::ConfigError(
                "rtp_session_buffer_config.sender_channel_capacity must be at least 1".to_string(),
            ));
        }
        if self.rtp_session_buffer_config.receiver_channel_capacity == 0 {
            return Err(SessionError::ConfigError(
                "rtp_session_buffer_config.receiver_channel_capacity must be at least 1"
                    .to_string(),
            ));
        }
        if self.rtp_session_buffer_config.event_channel_capacity == 0 {
            return Err(SessionError::ConfigError(
                "rtp_session_buffer_config.event_channel_capacity must be at least 1".to_string(),
            ));
        }
        if self.rtp_transport_buffer_config.event_channel_capacity == 0 {
            return Err(SessionError::ConfigError(
                "rtp_transport_buffer_config.event_channel_capacity must be at least 1".to_string(),
            ));
        }
        if self.rtp_transport_buffer_config.recv_buffer_size == 0 {
            return Err(SessionError::ConfigError(
                "rtp_transport_buffer_config.recv_buffer_size must be at least 1".to_string(),
            ));
        }
        if self.rtp_transport_buffer_config.rtcp_recv_buffer_size == 0 {
            return Err(SessionError::ConfigError(
                "rtp_transport_buffer_config.rtcp_recv_buffer_size must be at least 1".to_string(),
            ));
        }
        if self
            .media_session_controller_config
            .audio_frame_pool
            .sample_rate
            == 0
        {
            return Err(SessionError::ConfigError(
                "media_session_controller_config.audio_frame_pool.sample_rate must be at least 1"
                    .to_string(),
            ));
        }
        if self
            .media_session_controller_config
            .audio_frame_pool
            .channels
            == 0
        {
            return Err(SessionError::ConfigError(
                "media_session_controller_config.audio_frame_pool.channels must be at least 1"
                    .to_string(),
            ));
        }
        if self
            .media_session_controller_config
            .audio_frame_pool
            .samples_per_frame
            == 0
        {
            return Err(SessionError::ConfigError(
                "media_session_controller_config.audio_frame_pool.samples_per_frame must be at least 1"
                    .to_string(),
            ));
        }
        if self.media_session_controller_config.rtp_buffer_size == 0 {
            return Err(SessionError::ConfigError(
                "media_session_controller_config.rtp_buffer_size must be at least 1".to_string(),
            ));
        }
        if self.media_session_controller_config.rtp_buffer_max_count == 0 {
            return Err(SessionError::ConfigError(
                "media_session_controller_config.rtp_buffer_max_count must be at least 1"
                    .to_string(),
            ));
        }
        if self
            .media_session_controller_config
            .rtp_buffer_initial_count
            > self.media_session_controller_config.rtp_buffer_max_count
        {
            return Err(SessionError::ConfigError(
                "media_session_controller_config.rtp_buffer_initial_count must be <= rtp_buffer_max_count"
                    .to_string(),
            ));
        }
        #[cfg(feature = "perf-tests")]
        if let Some(limit) = self.perf_max_rss_growth_mb_per_hr {
            if !limit.is_finite() || limit <= 0.0 {
                return Err(SessionError::ConfigError(
                    "perf_max_rss_growth_mb_per_hr must be finite and greater than 0".to_string(),
                ));
            }
        }
        if self.media_port_start < MIN_PORT {
            return Err(SessionError::ConfigError(format!(
                "media_port_start must be >= {}",
                MIN_PORT
            )));
        }
        if self.media_port_start > self.media_port_end {
            return Err(SessionError::ConfigError(
                "media_port_start must be <= media_port_end".to_string(),
            ));
        }
        if let Some(capacity) = self.media_port_capacity {
            let available = self.media_port_end as usize - self.media_port_start as usize + 1;
            if available < capacity {
                return Err(SessionError::ConfigError(format!(
                    "media port range {}-{} provides {} ports, below requested media_port_capacity {}",
                    self.media_port_start, self.media_port_end, available, capacity
                )));
            }
        }
        if let MediaMode::SignalingOnly { sdp_rtp_port: 0 } = self.media_mode {
            return Err(SessionError::ConfigError(
                "signaling-only media SDP RTP port must be at least 1".to_string(),
            ));
        }
        validate_beta_media_codecs(&self.offered_codecs, self.comfort_noise_enabled)?;
        if self.srtp_required && !self.offer_srtp {
            return Err(SessionError::ConfigError(
                "srtp_required=true requires offer_srtp=true".to_string(),
            ));
        }
        if self.offer_srtp && self.srtp_offered_suites.is_empty() {
            return Err(SessionError::ConfigError(
                "offer_srtp=true requires at least one srtp_offered_suites entry".to_string(),
            ));
        }
        if matches!(
            effective_tls_mode,
            SipTlsMode::ServerOnly | SipTlsMode::ClientAndServer
        ) && (self.tls_cert_path.is_none() || self.tls_key_path.is_none())
        {
            return Err(SessionError::ConfigError(
                "SIP TLS listener modes require tls_cert_path and tls_key_path".to_string(),
            ));
        }

        match self.sip_contact_mode {
            SipContactMode::ReachableContact => match effective_tls_mode {
                SipTlsMode::Disabled => {}
                SipTlsMode::ClientOnly => {
                    if self.contact_uri.is_none() {
                        return Err(SessionError::ConfigError(
                            "reachable TLS Contact mode with ClientOnly requires an explicit external contact_uri".to_string(),
                        ));
                    }
                }
                SipTlsMode::ServerOnly | SipTlsMode::ClientAndServer => {
                    if self.tls_bind_addr.is_none() {
                        return Err(SessionError::ConfigError(
                            "reachable TLS Contact mode requires tls_bind_addr".to_string(),
                        ));
                    }
                    if self.tls_cert_path.is_none() || self.tls_key_path.is_none() {
                        return Err(SessionError::ConfigError(
                            "reachable TLS Contact mode requires tls_cert_path and tls_key_path"
                                .to_string(),
                        ));
                    }
                }
            },
            SipContactMode::RegisteredFlowRfc5626 => {
                if !matches!(
                    effective_tls_mode,
                    SipTlsMode::ClientOnly | SipTlsMode::ClientAndServer
                ) {
                    return Err(SessionError::ConfigError(
                        "RFC 5626 registered-flow mode requires SIP TLS ClientOnly or ClientAndServer".to_string(),
                    ));
                }
                if !self.sip_outbound_enabled {
                    return Err(SessionError::ConfigError(
                        "RFC 5626 registered-flow mode requires sip_outbound_enabled=true"
                            .to_string(),
                    ));
                }
                if self
                    .sip_instance
                    .as_deref()
                    .map(str::trim)
                    .filter(|value| !value.is_empty())
                    .is_none()
                {
                    return Err(SessionError::ConfigError(
                        "RFC 5626 registered-flow mode requires a stable sip_instance URN"
                            .to_string(),
                    ));
                }
            }
            SipContactMode::RegisteredFlowSymmetric => {
                if !matches!(
                    effective_tls_mode,
                    SipTlsMode::ClientOnly | SipTlsMode::ClientAndServer
                ) {
                    return Err(SessionError::ConfigError(
                        "symmetric registered-flow mode requires SIP TLS ClientOnly or ClientAndServer".to_string(),
                    ));
                }
            }
        }

        // SIP_API_DESIGN_2 §7.4 — auto_emit_extra_headers stack-managed
        // rejection. The state machine's auto-emit paths can't route
        // through `HeaderPolicy::validate_outbound` (there's no
        // builder), so we hard-fail at Config-construction time when
        // an application stages a name that would desync the dialog
        // or transaction.
        for header in &self.auto_emit_extra_headers {
            if crate::api::headers::policy::forbidden_for_carry_through(&header.name()) {
                return Err(SessionError::ConfigError(format!(
                    "Config.auto_emit_extra_headers contains stack-managed header {:?} \
                     (Call-ID / CSeq / Via / Max-Forwards / Content-Length / Record-Route / \
                     Route are owned by the dialog/transaction layer)",
                    header.name()
                )));
            }
        }

        Ok(())
    }

    fn effective_tls_mode(&self) -> SipTlsMode {
        if self.sip_tls_mode == SipTlsMode::Disabled
            && self.tls_cert_path.is_some()
            && self.tls_key_path.is_some()
        {
            SipTlsMode::ClientAndServer
        } else {
            self.sip_tls_mode
        }
    }
}

fn validate_beta_media_codecs(offered_codecs: &[u8], comfort_noise_enabled: bool) -> Result<()> {
    if offered_codecs.is_empty() {
        return Err(SessionError::ConfigError(
            "offered_codecs must include at least one beta-supported audio codec".to_string(),
        ));
    }

    let base_payloads = match (cfg!(feature = "g729"), cfg!(feature = "opus")) {
        (true, true) => "0, 8, 18, 111, 101, and 13 when comfort_noise_enabled=true",
        (true, false) => "0, 8, 18, 101, and 13 when comfort_noise_enabled=true",
        (false, true) => "0, 8, 111, 101, and 13 when comfort_noise_enabled=true",
        (false, false) => "0, 8, 101, and 13 when comfort_noise_enabled=true",
    };
    let supported_payloads = match (cfg!(feature = "amr-wb"), cfg!(feature = "amr-nb")) {
        (true, true) => format!("{base_payloads}, plus 104/105 (AMR-WB) and 106/107 (AMR-NB)"),
        (true, false) => format!("{base_payloads}, plus 104/105 (AMR-WB)"),
        (false, true) => format!("{base_payloads}, plus 106/107 (AMR-NB)"),
        (false, false) => base_payloads.to_string(),
    };
    let mut has_audio = false;
    let mut seen = std::collections::BTreeSet::new();
    for &pt in offered_codecs {
        if !seen.insert(pt) {
            return Err(SessionError::ConfigError(format!(
                "offered_codecs contains duplicate payload type {}",
                pt
            )));
        }

        match pt {
            0 | 8 => has_audio = true,
            18 => {
                #[cfg(feature = "g729")]
                {
                    has_audio = true;
                }
                #[cfg(not(feature = "g729"))]
                {
                    return Err(SessionError::ConfigError(
                        "payload type 18 requires the rvoip-sip `g729` feature".to_string(),
                    ));
                }
            }
            111 => {
                #[cfg(feature = "opus")]
                {
                    has_audio = true;
                }
                #[cfg(not(feature = "opus"))]
                {
                    return Err(SessionError::ConfigError(
                        "payload type 111 requires the rvoip-sip `opus` feature".to_string(),
                    ));
                }
            }
            // AMR, on the payload types this stack assigns in
            // `adapters/media_adapter.rs`: 104/105 are AMR-WB
            // (bandwidth-efficient / octet-aligned) and 106/107 are AMR-NB.
            //
            // Everything below this validation already handled them — the
            // offer builder emits their rtpmap and fmtp, the answerer
            // resolves them from `a=rtpmap`, and media-core builds an
            // `AmrAdapter` for each — but the gate here had no arm for
            // them, so the whole path was unreachable from `Config` and
            // every AMR offer was rejected before a socket was opened.
            104 | 105 => {
                #[cfg(feature = "amr-wb")]
                {
                    has_audio = true;
                }
                #[cfg(not(feature = "amr-wb"))]
                {
                    return Err(SessionError::ConfigError(
                        "payload types 104/105 require the rvoip-sip `amr-wb` feature".to_string(),
                    ));
                }
            }
            106 | 107 => {
                #[cfg(feature = "amr-nb")]
                {
                    has_audio = true;
                }
                #[cfg(not(feature = "amr-nb"))]
                {
                    return Err(SessionError::ConfigError(
                        "payload types 106/107 require the rvoip-sip `amr-nb` feature".to_string(),
                    ));
                }
            }
            101 => {}
            13 if comfort_noise_enabled => {}
            13 => {
                return Err(SessionError::ConfigError(
                    "payload type 13 requires comfort_noise_enabled=true".to_string(),
                ));
            }
            unsupported => {
                return Err(SessionError::ConfigError(format!(
                    "payload type {} is not beta-supported for full media; supported payloads are {}",
                    unsupported, supported_payloads
                )));
            }
        }
    }

    if !has_audio {
        return Err(SessionError::ConfigError(
            match (cfg!(feature = "g729"), cfg!(feature = "opus")) {
                (true, true) => "offered_codecs must include PCMU (0), PCMA (8), G.729 (18), or Opus (111) for beta full-media support",
                (true, false) => "offered_codecs must include PCMU (0), PCMA (8), or G.729 (18) for beta full-media support",
                (false, true) => "offered_codecs must include PCMU (0), PCMA (8), or Opus (111) for beta full-media support",
                (false, false) => "offered_codecs must include PCMU (0) or PCMA (8) for beta full-media support",
            }
            .to_string(),
        ));
    }

    Ok(())
}

impl Default for Config {
    fn default() -> Self {
        Config::local("user", 5060)
    }
}

#[cfg(test)]
mod config_tests {
    use super::{
        complete_established_bye_dispatch, exact_terminal_completion_result,
        run_bounded_exact_response_batch, Config, ExactResponseRegistration,
        ExactResponseRetryCause, OobAuthRetry, PendingExactResponseRegistry, Registration,
        RegistrationHandle, RegistrationInfo, RegistrationStatus, SetupTeardownDeadline,
        SetupTeardownDeadlineQueue, SetupTeardownDeadlineScheduler, SetupTeardownWatchdogKind,
        UnifiedCoordinator, EXACT_RESPONSE_MAX_RETRIES, EXACT_RESPONSE_RETRY_DELAY,
        EXACT_RESPONSE_SLOW_RETRY_DELAY, SETUP_TEARDOWN_TIMEOUT_CONCURRENCY,
    };
    use crate::api::events::Event;
    use crate::api::handle::CallId;
    use crate::api::incoming::ExactResponseObligation;
    use crate::api::lifecycle::{ExactTerminalClaim, ExactTerminalCompletion};
    use crate::api::trace_redactor::{RedactionDecision, TraceRedactor};
    use crate::errors::SessionError;
    use crate::session_store::SessionStore;
    use crate::state_table::types::{Role, SessionId};
    use crate::types::CallState;
    use rvoip_infra_common::events::coordinator::CrossCrateEventHandler;
    use rvoip_infra_common::events::cross_crate::{DialogToSessionEvent, RvoipCrossCrateEvent};
    use rvoip_sip_core::types::headers::HeaderName;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;
    use std::time::{Duration, Instant};

    struct CanaryTracePolicy(&'static str);

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn production_registration_start_receives_one_typed_request_without_bus_copy() {
        let coordinator = UnifiedCoordinator::new(Config::local("registration-ingress", 0))
            .await
            .expect("start registration ingress coordinator");
        let mut observer = coordinator
            .global_coordinator
            .subscribe("dialog_to_session")
            .await
            .unwrap();
        let mut events = coordinator.events().await.unwrap();
        let subscriptions_before = coordinator
            .global_coordinator
            .stats()
            .await
            .active_subscriptions;
        let registrar = coordinator
            .start_registration_server("registrar.example", std::collections::HashMap::new())
            .await
            .expect("install registration adapter");
        assert_eq!(
            coordinator
                .global_coordinator
                .stats()
                .await
                .active_subscriptions,
            subscriptions_before,
            "production registration start subscribed to dialog_to_session"
        );

        let event = RvoipCrossCrateEvent::DialogToSession(DialogToSessionEvent::IncomingRegister {
            transaction_id: "registration-ingress:REGISTER:server".to_string(),
            from_uri: "sip:alice@registrar.example".to_string(),
            to_uri: "sip:alice@registrar.example".to_string(),
            contact_uri: "sip:alice@127.0.0.1:5060".to_string(),
            expires: 300,
            authorization: None,
            call_id: "registration-ingress@example.invalid".to_string(),
            raw_request: None,
            transport: None,
        });
        let dispatched = coordinator
            .global_coordinator
            .dispatch_authoritative_handler(Arc::new(event))
            .await
            .unwrap_or(false);
        // The built-in registrar may reject an unauthenticated synthetic
        // request, but the typed observation must still be projected exactly
        // once through the installed handler.
        let _ = dispatched;
        let projected = tokio::time::timeout(Duration::from_secs(1), events.next())
            .await
            .expect("installed registrar did not process the typed request")
            .expect("registration observation stream closed unexpectedly");
        match projected {
            crate::api::events::Event::IncomingRegister { register } => {
                assert_eq!(
                    register.transaction_id,
                    "registration-ingress:REGISTER:server"
                );
                assert_eq!(register.from_uri, "sip:alice@registrar.example");
            }
            other => panic!("unexpected registration observation: {other:?}"),
        }
        assert!(matches!(
            observer.try_recv(),
            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
        ));

        registrar.shutdown().await.unwrap();
        coordinator
            .shutdown_gracefully(Some(Duration::ZERO))
            .await
            .unwrap();
        coordinator.global_coordinator.shutdown().await.unwrap();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn standalone_terminal_handler_releases_without_coordinator_backreference() {
        let coordinator = UnifiedCoordinator::new(Config::local("standalone-terminal-owner", 0))
            .await
            .expect("start standalone terminal fixture");
        let store = Arc::clone(&coordinator.helpers.state_machine.store);
        let session_id = SessionId::from("standalone-terminal-session");
        let created = store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("create standalone terminal session");
        let handle = created
            .lifecycle_handle
            .expect("capture standalone terminal lifetime");
        store
            .update_session_exact_with(&handle, None, |session| {
                session.call_state = CallState::Active;
            })
            .expect("place standalone terminal session in Active");
        let mut events = coordinator.events().await.expect("subscribe app events");

        let handler = crate::adapters::SessionCrossCrateEventHandler::new(
            Arc::clone(&coordinator.helpers.state_machine),
            Arc::clone(&coordinator.global_coordinator),
            Arc::clone(&coordinator.dialog_adapter),
            Arc::clone(&coordinator.media_adapter),
            Arc::clone(&coordinator.session_registry),
        );
        handler
            .handle(Arc::new(RvoipCrossCrateEvent::DialogToSession(
                DialogToSessionEvent::CallStateChanged {
                    session_id: session_id.0.clone(),
                    new_state: rvoip_infra_common::events::cross_crate::CallState::Terminated,
                    reason: Some("lower dialog observation".to_string()),
                },
            )))
            .await
            .expect("observational terminal state was accepted");
        assert_eq!(
            store
                .get_session_snapshot_exact(&handle)
                .expect("observation retained exact session")
                .call_state,
            CallState::Active,
            "observational terminal state committed the lifecycle"
        );
        let premature = tokio::time::timeout(Duration::from_millis(75), async {
            loop {
                match events.next().await {
                    Some(Event::CallEnded { call_id, .. } | Event::CallCancelled { call_id })
                        if call_id == session_id =>
                    {
                        return Some(());
                    }
                    Some(_) => {}
                    None => return None,
                }
            }
        })
        .await;
        assert!(
            !matches!(premature, Ok(Some(_))),
            "observational terminal state projected an app terminal event"
        );
        handler
            .handle(Arc::new(RvoipCrossCrateEvent::DialogToSession(
                DialogToSessionEvent::CallTerminated {
                    session_id: session_id.0.clone(),
                    reason:
                        rvoip_infra_common::events::cross_crate::TerminationReason::RemoteHangup,
                },
            )))
            .await
            .expect("standalone handler accepted terminal event");

        tokio::time::timeout(Duration::from_secs(2), async {
            loop {
                match events.next().await {
                    Some(Event::CallEnded { call_id, .. }) if call_id == session_id => break,
                    Some(Event::CallCancelled { call_id }) if call_id == session_id => {
                        panic!("ordinary DialogTerminated projected CallCancelled")
                    }
                    Some(_) => {}
                    None => panic!("app event stream closed before CallEnded"),
                }
            }
        })
        .await
        .expect("committed termination did not publish CallEnded");

        tokio::time::timeout(Duration::from_secs(2), async {
            while store.lifecycle_handle(&session_id).is_some() {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("standalone terminal task released exact session");

        let duplicate = tokio::time::timeout(Duration::from_millis(150), async {
            loop {
                match events.next().await {
                    Some(Event::CallEnded { call_id, .. } | Event::CallCancelled { call_id })
                        if call_id == session_id =>
                    {
                        return Some(());
                    }
                    Some(_) => {}
                    None => return None,
                }
            }
        })
        .await;
        assert!(
            !matches!(duplicate, Ok(Some(_))),
            "committed termination projected more than one terminal app event"
        );
        drop(handler);

        coordinator
            .shutdown_gracefully(Some(Duration::ZERO))
            .await
            .expect("shutdown standalone terminal fixture");
        coordinator.global_coordinator.shutdown().await.unwrap();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn invalid_dialog_termination_retains_exact_session_without_app_terminal() {
        let coordinator = UnifiedCoordinator::new(Config::local("invalid-terminal-owner", 0))
            .await
            .expect("start invalid terminal fixture");
        let store = Arc::clone(&coordinator.helpers.state_machine.store);
        let session_id = SessionId::from("invalid-terminal-session");
        let created = store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("create invalid terminal session");
        let handle = created
            .lifecycle_handle
            .expect("capture invalid terminal lifetime");
        let mut events = coordinator.events().await.expect("subscribe app events");
        let handler = crate::adapters::SessionCrossCrateEventHandler::new(
            Arc::clone(&coordinator.helpers.state_machine),
            Arc::clone(&coordinator.global_coordinator),
            Arc::clone(&coordinator.dialog_adapter),
            Arc::clone(&coordinator.media_adapter),
            Arc::clone(&coordinator.session_registry),
        );

        let error = handler
            .handle(Arc::new(RvoipCrossCrateEvent::DialogToSession(
                DialogToSessionEvent::CallTerminated {
                    session_id: session_id.0.clone(),
                    reason:
                        rvoip_infra_common::events::cross_crate::TerminationReason::RemoteHangup,
                },
            )))
            .await
            .expect_err("Idle has no DialogTerminated YAML transition");
        assert!(matches!(
            error.downcast_ref::<SessionError>(),
            Some(SessionError::InvalidTransition(detail))
                if detail.contains("had no YAML transition")
        ));
        assert!(
            store.get_session_snapshot_exact(&handle).is_ok(),
            "invalid termination released the exact session"
        );

        let terminal = tokio::time::timeout(Duration::from_millis(150), async {
            loop {
                match events.next().await {
                    Some(Event::CallEnded { call_id, .. } | Event::CallCancelled { call_id })
                        if call_id == session_id =>
                    {
                        return Some(());
                    }
                    Some(_) => {}
                    None => return None,
                }
            }
        })
        .await;
        assert!(
            !matches!(terminal, Ok(Some(_))),
            "invalid termination projected an app terminal event"
        );
        drop(handler);
        store
            .remove_session_exact(&handle)
            .await
            .expect("clean up retained invalid terminal fixture");

        coordinator
            .shutdown_gracefully(Some(Duration::ZERO))
            .await
            .expect("shutdown invalid terminal fixture");
        coordinator.global_coordinator.shutdown().await.unwrap();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn late_answer_cancellation_requires_committed_uac_yaml_outcome() {
        let coordinator = UnifiedCoordinator::new(Config::local("cancel-terminal-owner", 0))
            .await
            .expect("start cancellation terminal fixture");
        let store = Arc::clone(&coordinator.helpers.state_machine.store);
        let handler = crate::adapters::SessionCrossCrateEventHandler::new(
            Arc::clone(&coordinator.helpers.state_machine),
            Arc::clone(&coordinator.global_coordinator),
            Arc::clone(&coordinator.dialog_adapter),
            Arc::clone(&coordinator.media_adapter),
            Arc::clone(&coordinator.session_registry),
        );
        let mut events = coordinator.events().await.expect("subscribe app events");

        let cancelled_id = SessionId::from("committed-cancel-terminal");
        let cancelled = store
            .create_session(cancelled_id.clone(), Role::UAC, false)
            .await
            .expect("create committed cancellation session");
        let cancelled_handle = cancelled
            .lifecycle_handle
            .expect("capture committed cancellation lifetime");
        store
            .update_session_exact_with(&cancelled_handle, None, |session| {
                session.call_state = CallState::Cancelling;
            })
            .expect("place UAC cancellation in Cancelling");
        handler
            .handle(Arc::new(RvoipCrossCrateEvent::DialogToSession(
                DialogToSessionEvent::CallTerminated {
                    session_id: cancelled_id.0.clone(),
                    reason: rvoip_infra_common::events::cross_crate::TerminationReason::LocalHangup,
                },
            )))
            .await
            .expect("UAC Cancelling committed its terminal YAML outcome");

        tokio::time::timeout(Duration::from_secs(2), async {
            loop {
                match events.next().await {
                    Some(Event::CallCancelled { call_id }) if call_id == cancelled_id => break,
                    Some(Event::CallEnded { call_id, .. }) if call_id == cancelled_id => {
                        panic!("committed cancellation projected CallEnded")
                    }
                    Some(_) => {}
                    None => panic!("app event stream closed before CallCancelled"),
                }
            }
        })
        .await
        .expect("committed cancellation did not publish CallCancelled");
        tokio::time::timeout(Duration::from_secs(2), async {
            while store.lifecycle_handle(&cancelled_id).is_some() {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("committed cancellation did not release its exact session");

        let rejected_id = SessionId::from("rejected-uas-cancel-terminal");
        let rejected = store
            .create_session(rejected_id.clone(), Role::UAS, false)
            .await
            .expect("create rejected cancellation session");
        let rejected_handle = rejected
            .lifecycle_handle
            .expect("capture rejected cancellation lifetime");
        store
            .update_session_exact_with(&rejected_handle, None, |session| {
                session.call_state = CallState::Cancelling;
            })
            .expect("place UAS cancellation in Cancelling");
        handler
            .handle(Arc::new(RvoipCrossCrateEvent::DialogToSession(
                DialogToSessionEvent::CallTerminated {
                    session_id: rejected_id.0.clone(),
                    reason: rvoip_infra_common::events::cross_crate::TerminationReason::LocalHangup,
                },
            )))
            .await
            .expect_err("UAS Cancelling has no late-answer cancellation YAML row");
        assert!(
            store.get_session_snapshot_exact(&rejected_handle).is_ok(),
            "uncommitted cancellation released its exact session"
        );

        let terminal = tokio::time::timeout(Duration::from_millis(150), async {
            loop {
                match events.next().await {
                    Some(Event::CallEnded { call_id, .. } | Event::CallCancelled { call_id })
                        if call_id == rejected_id =>
                    {
                        return Some(());
                    }
                    Some(_) => {}
                    None => return None,
                }
            }
        })
        .await;
        assert!(
            !matches!(terminal, Ok(Some(_))),
            "uncommitted cancellation projected an app terminal event"
        );
        drop(handler);
        store
            .remove_session_exact(&rejected_handle)
            .await
            .expect("clean up retained rejected cancellation fixture");

        coordinator
            .shutdown_gracefully(Some(Duration::ZERO))
            .await
            .expect("shutdown cancellation terminal fixture");
        coordinator.global_coordinator.shutdown().await.unwrap();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn graceful_shutdown_drains_terminal_child_admitted_by_retained_parent() {
        let coordinator = UnifiedCoordinator::new(Config::local("terminal-child-drain", 0))
            .await
            .expect("start terminal child drain coordinator");
        let retained = Arc::clone(&coordinator.setup_teardown_scheduler.tasks);
        let (parent_started_tx, parent_started_rx) = tokio::sync::oneshot::channel();
        let (allow_child_tx, allow_child_rx) = tokio::sync::oneshot::channel();
        let (child_started_tx, child_started_rx) = tokio::sync::oneshot::channel();
        let (release_child_tx, release_child_rx) = tokio::sync::oneshot::channel();
        let parent_retained = Arc::clone(&retained);
        assert!(retained.spawn(async move {
            let _ = parent_started_tx.send(());
            let _ = allow_child_rx.await;
            assert!(parent_retained.spawn_or_child(async move {
                let _ = child_started_tx.send(());
                let _ = release_child_rx.await;
            }));
        }));
        parent_started_rx.await.expect("retained parent started");

        let shutdown_coordinator = Arc::clone(&coordinator);
        let shutdown = tokio::spawn(async move {
            shutdown_coordinator
                .shutdown_gracefully(Some(Duration::ZERO))
                .await
        });
        tokio::time::timeout(Duration::from_secs(2), async {
            while coordinator.setup_teardown_scheduler.is_accepting_for_test() {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("shutdown closed retained admission");

        let _ = allow_child_tx.send(());
        child_started_rx
            .await
            .expect("terminal child admitted after close");
        tokio::task::yield_now().await;
        assert!(
            !shutdown.is_finished(),
            "shutdown passed the retained terminal child"
        );

        let _ = release_child_tx.send(());
        tokio::time::timeout(Duration::from_secs(2), shutdown)
            .await
            .expect("shutdown drained terminal child")
            .expect("shutdown driver joined")
            .expect("shutdown succeeded after terminal child");
        coordinator.global_coordinator.shutdown().await.unwrap();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn graceful_shutdown_drains_all_retained_session_event_loops() {
        let coordinator = UnifiedCoordinator::new(Config::local("session-event-loop-drain", 0))
            .await
            .expect("start retained session-event loop coordinator");
        let retained = Arc::clone(&coordinator.setup_teardown_scheduler.tasks);
        let minimum_expected =
            crate::adapters::session_event_handler::dialog_dispatch_worker_count() + 6;
        assert!(
            retained.count() >= minimum_expected,
            "retained registry is missing a scheduler, shard, or session-event loop: count={}, expected_at_least={minimum_expected}",
            retained.count()
        );
        let active_diagnostics = coordinator
            .setup_teardown_scheduler
            .perf_diagnostic_counts();
        assert_eq!(
            active_diagnostics["retained_tasks"],
            retained.count(),
            "runtime diagnostics must expose every retained coordinator task"
        );

        coordinator
            .shutdown_gracefully(Some(Duration::ZERO))
            .await
            .expect("shutdown drained retained session-event loops");
        assert_eq!(retained.count(), 0);
        assert!(!retained.panicked());
        let drained_scheduler = coordinator
            .setup_teardown_scheduler
            .perf_diagnostic_counts();
        assert_eq!(drained_scheduler["pending_deadlines"], 0);
        assert_eq!(drained_scheduler["fire_in_flight"], 0);
        assert_eq!(drained_scheduler["retained_tasks"], 0);
        assert_eq!(drained_scheduler["retained_task_panicked"], false);
        assert_eq!(drained_scheduler["accepting"], false);
        let drained_responses = coordinator.pending_exact_responses.perf_diagnostic_counts();
        assert_eq!(drained_responses["pending_obligations"], 0);
        assert_eq!(drained_responses["pending_deadlines"], 0);
        assert_eq!(drained_responses["fire_in_flight"], 0);
        assert_eq!(drained_responses["accepting"], false);
        coordinator.global_coordinator.shutdown().await.unwrap();
    }

    #[test]
    fn shutdown_drains_retained_tasks_before_dialog_and_publisher_stop() {
        fn section<'a>(source: &'a str, start: &str, end: &str) -> &'a str {
            source
                .split(start)
                .nth(1)
                .and_then(|tail| tail.split(end).next())
                .expect("shutdown function source")
        }

        fn assert_ordered(section: &str) {
            let signal = section
                .find("self.shutdown_tx.send(true)")
                .expect("shutdown signal");
            let retained_drain = section
                .find("close_and_wait(SETUP_TEARDOWN_SCHEDULER_DRAIN_TIMEOUT)")
                .expect("retained task drain");
            let dialog_stop = section
                .find("self.dialog_adapter.stop().await")
                .expect("dialog stop");
            let publisher_stop = section
                .find("self.app_event_publisher.shutdown().await")
                .expect("publisher stop");
            assert!(signal < retained_drain);
            assert!(retained_drain < dialog_stop);
            assert!(dialog_stop < publisher_stop);
        }

        let source = include_str!("unified.rs");
        assert_ordered(section(
            source,
            concat!("async fn cleanup_failed_", "construction"),
            concat!("/// Shut down this ", "coordinator"),
        ));
        assert_ordered(section(
            source,
            concat!("async fn run_shutdown_", "sequence"),
            concat!("async fn unregister_registered_", "sessions"),
        ));
    }

    #[test]
    fn watchdog_exact_release_is_independent_of_observational_publication() {
        fn section<'a>(source: &'a str, start: &str, end: &str) -> &'a str {
            source
                .split(start)
                .nth(1)
                .and_then(|tail| tail.split(end).next())
                .unwrap_or_else(|| panic!("missing watchdog source section after {start}"))
        }

        fn assert_nonblocking_observation_before_release(body: &str, label: &str) {
            let observation = body
                .find("publish_terminal_best_effort")
                .unwrap_or_else(|| panic!("{label} lost terminal observation"));
            let release = body
                .find("release_exact_local_resources(")
                .unwrap_or_else(|| panic!("{label} lost exact release"));
            assert!(
                observation < release,
                "{label} must record the committed observation before exact release"
            );
            assert!(
                !body[observation..release].contains(".await"),
                "{label} must not await observational publication"
            );
        }

        let source = include_str!("unified.rs");
        assert!(
            !source.contains(concat!("publish_terminal_then_", "release")),
            "terminal release must not be combined with observational publication"
        );
        let active_media_watchdog = section(
            source,
            concat!(
                "pub(crate) async fn schedule_active_call_",
                "media_timeout_if_current"
            ),
            concat!("pub(crate) fn setup_teardown_", "timeout_duration"),
        );
        assert!(
            active_media_watchdog.contains("hangup_exact_with_reason(&handle, reason)"),
            "active-media watchdog must delegate observation and release to exact hangup"
        );
        assert!(
            !active_media_watchdog.contains("publish_terminal_best_effort")
                && !active_media_watchdog.contains("release_exact_local_resources("),
            "active-media watchdog must not retain its former publication/release bypass"
        );
        assert_nonblocking_observation_before_release(
            section(
                source,
                concat!("async fn fire_setup_", "teardown_deadline"),
                concat!("/// Complete local ", "BYE teardown"),
            ),
            "setup/teardown watchdog",
        );
    }

    #[test]
    fn exact_response_registry_retains_one_owner_and_rejects_key_collision() {
        let registry = PendingExactResponseRegistry::default();
        let transaction = rvoip_sip_dialog::transaction::TransactionKey::new(
            "z9hG4bK-registry-owner".into(),
            rvoip_sip_core::Method::Info,
            true,
        );
        let owner = Arc::new(ExactResponseObligation::new_standalone(
            transaction.clone(),
            503,
        ));
        assert!(matches!(
            registry.register(Arc::clone(&owner)),
            ExactResponseRegistration::Registered
        ));
        drop(owner);
        assert_eq!(registry.len(), 1, "registry did not retain exact owner");
        let retained = registry.perf_diagnostic_counts();
        assert_eq!(retained["pending_obligations"], 1);
        assert_eq!(retained["pending_deadlines"], 1);
        assert_eq!(retained["retry_attempts"], 0);
        assert_eq!(retained["fire_in_flight"], 0);
        let fire = registry.begin_fire();
        assert_eq!(registry.perf_diagnostic_counts()["fire_in_flight"], 1);
        drop(fire);
        assert_eq!(registry.perf_diagnostic_counts()["fire_in_flight"], 0);

        let collision = Arc::new(ExactResponseObligation::new_standalone(transaction, 503));
        assert!(matches!(
            registry.register(collision),
            ExactResponseRegistration::Collision
        ));
        registry.begin_close();
        registry.clear();
        assert_eq!(registry.len(), 0);
        let drained = registry.perf_diagnostic_counts();
        assert_eq!(drained["pending_obligations"], 0);
        assert_eq!(drained["pending_deadlines"], 0);
        assert_eq!(drained["retry_attempts"], 0);
        assert_eq!(drained["fire_in_flight"], 0);
        assert_eq!(drained["accepting"], false);
    }

    #[tokio::test]
    async fn exact_response_lifetime_close_fences_only_that_generation() {
        let store = Arc::new(SessionStore::new());
        let session_id = SessionId("exact-response-close-owner".to_string());
        store
            .create_session(session_id.clone(), Role::UAS, false)
            .await
            .expect("create exact response owner");
        let handle = store
            .lifecycle_handle(&session_id)
            .expect("capture exact response owner");
        let registry = PendingExactResponseRegistry::default();
        registry.attach_session_store(&store);
        let transaction = |label: &str| {
            rvoip_sip_dialog::transaction::TransactionKey::new(
                label.to_string(),
                rvoip_sip_core::Method::Info,
                true,
            )
        };

        let unbound = Arc::new(ExactResponseObligation::new(
            session_id.clone(),
            transaction("z9hG4bK-unbound-owner"),
        ));
        assert!(matches!(
            registry.register(unbound),
            ExactResponseRegistration::Collision
        ));

        let owner = Arc::new(ExactResponseObligation::new(
            session_id.clone(),
            transaction("z9hG4bK-bound-owner"),
        ));
        assert!(owner.bind_lifecycle_handle(&handle));
        assert!(matches!(
            registry.register(owner),
            ExactResponseRegistration::Registered
        ));
        registry.begin_lifetime_close(&handle);
        assert_eq!(registry.snapshot_lifetime(&handle).len(), 1);
        assert_eq!(registry.perf_diagnostic_counts()["closing_lifetimes"], 1);

        let late = Arc::new(ExactResponseObligation::new(
            session_id.clone(),
            transaction("z9hG4bK-late-owner"),
        ));
        assert!(late.bind_lifecycle_handle(&handle));
        assert!(matches!(
            registry.register(late),
            ExactResponseRegistration::Closed
        ));

        let standalone = Arc::new(ExactResponseObligation::new_standalone(
            transaction("z9hG4bK-standalone-owner"),
            503,
        ));
        assert!(matches!(
            registry.register(standalone),
            ExactResponseRegistration::Registered
        ));
        store
            .remove_session_exact(&handle)
            .await
            .expect("retire exact response owner");
        registry.finish_lifetime_close(&handle);

        let stale = Arc::new(ExactResponseObligation::new(
            session_id,
            transaction("z9hG4bK-stale-owner"),
        ));
        assert!(stale.bind_lifecycle_handle(&handle));
        assert!(matches!(
            registry.register(stale),
            ExactResponseRegistration::Closed
        ));
    }

    #[test]
    fn exact_terminal_release_drains_generation_before_dialog_cleanup() {
        let source = include_str!("unified.rs");
        let release = source
            .rsplit("pub(crate) async fn release_exact_local_resources(")
            .next()
            .and_then(|tail| {
                tail.split("pub(crate) async fn release_exact_local_resources_with_retry(")
                    .next()
            })
            .expect("exact terminal release helper source");
        let close = release
            .find("deadlines.begin_lifetime_close(&handle)")
            .expect("generation close fence");
        let drain = release
            .find("drain_lifetime(&handle")
            .expect("generation response drain");
        let dialog_cleanup = release
            .find("dialog_adapter.cleanup_session_exact(&handle)")
            .expect("dialog cleanup");
        assert!(close < drain);
        assert!(drain < dialog_cleanup);
        assert!(release.contains("if removal.is_ok()"));
        assert!(release.contains("finish_lifetime_close(&handle)"));
    }

    #[test]
    fn exact_response_busy_and_timeout_do_not_consume_zero_wire_retry_budget() {
        let registry = PendingExactResponseRegistry::default();
        let transaction = rvoip_sip_dialog::transaction::TransactionKey::new(
            "z9hG4bK-registry-retry-budget".into(),
            rvoip_sip_core::Method::Info,
            true,
        );
        let owner = Arc::new(ExactResponseObligation::new_standalone(
            transaction.clone(),
            503,
        ));
        assert!(matches!(
            registry.register(owner),
            ExactResponseRegistration::Registered
        ));

        for _ in 0..(usize::from(EXACT_RESPONSE_MAX_RETRIES) * 2) {
            let plan = registry.retry_plan(&transaction, ExactResponseRetryCause::BusyOrTimeout);
            assert_eq!(plan.delay, EXACT_RESPONSE_RETRY_DELAY);
            assert!(!plan.slow_path);
        }
        assert!(
            !registry.retry_attempts.contains_key(&transaction),
            "busy/timeout consumed the zero-wire retry budget"
        );

        for _ in 0..EXACT_RESPONSE_MAX_RETRIES {
            let plan = registry.retry_plan(&transaction, ExactResponseRetryCause::ZeroWire);
            assert_eq!(plan.delay, EXACT_RESPONSE_RETRY_DELAY);
            assert!(!plan.slow_path);
        }
        let slow = registry.retry_plan(&transaction, ExactResponseRetryCause::ZeroWire);
        assert_eq!(slow.delay, EXACT_RESPONSE_SLOW_RETRY_DELAY);
        assert!(slow.slow_path);
        assert_eq!(registry.len(), 1, "slow retry removed the obligation");
    }

    #[tokio::test]
    async fn exact_response_due_batch_uses_bounded_parallelism() {
        const ITEMS: usize = 96;
        const CONCURRENCY: usize = 24;

        let active = Arc::new(AtomicUsize::new(0));
        let peak = Arc::new(AtomicUsize::new(0));
        let gate = Arc::new(tokio::sync::Semaphore::new(0));
        let batch = {
            let active = Arc::clone(&active);
            let peak = Arc::clone(&peak);
            let gate = Arc::clone(&gate);
            tokio::spawn(async move {
                run_bounded_exact_response_batch((0..ITEMS).collect(), CONCURRENCY, move |_| {
                    let active = Arc::clone(&active);
                    let peak = Arc::clone(&peak);
                    let gate = Arc::clone(&gate);
                    async move {
                        let current = active.fetch_add(1, Ordering::AcqRel) + 1;
                        peak.fetch_max(current, Ordering::AcqRel);
                        let permit = gate.acquire().await.expect("batch gate open");
                        permit.forget();
                        active.fetch_sub(1, Ordering::AcqRel);
                    }
                })
                .await;
            })
        };

        tokio::time::timeout(Duration::from_secs(1), async {
            while active.load(Ordering::Acquire) != CONCURRENCY {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("bounded batch did not fill its concurrency window");
        assert_eq!(peak.load(Ordering::Acquire), CONCURRENCY);

        gate.add_permits(ITEMS);
        tokio::time::timeout(Duration::from_secs(1), batch)
            .await
            .expect("bounded batch did not drain")
            .expect("bounded batch task panicked");
        assert_eq!(active.load(Ordering::Acquire), 0);
        assert_eq!(peak.load(Ordering::Acquire), CONCURRENCY);
    }

    #[test]
    fn terminal_completion_depends_only_on_exact_release() {
        assert!(exact_terminal_completion_result(ExactTerminalCompletion::Released).is_ok());
        assert!(exact_terminal_completion_result(ExactTerminalCompletion::ReleaseFailed).is_err());
        assert!(exact_terminal_completion_result(ExactTerminalCompletion::OwnerDropped).is_err());
    }

    #[tokio::test]
    async fn post_send_bye_dispatch_race_joins_exact_success_confirmation() {
        let result = complete_established_bye_dispatch(
            Err(SessionError::Other(
                "lower-layer operation failed (class=opaque-erased)".to_string(),
            )),
            true,
            std::future::ready(Ok(())),
        )
        .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn post_send_bye_dispatch_race_does_not_swallow_wire_failure() {
        let result = complete_established_bye_dispatch(
            Err(SessionError::Other(
                "lower-layer operation failed (class=opaque-erased)".to_string(),
            )),
            true,
            std::future::ready(Err(SessionError::ProtocolError(
                "SIP BYE received a non-success final response".to_string(),
            ))),
        )
        .await;

        assert!(matches!(result, Err(SessionError::ProtocolError(_))));
    }

    #[tokio::test]
    async fn pre_send_bye_dispatch_failure_preserves_original_error() {
        let confirmation_polled = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let confirmation_probe = Arc::clone(&confirmation_polled);
        let confirmation = async move {
            confirmation_probe.store(true, std::sync::atomic::Ordering::Relaxed);
            Ok(())
        };
        let result = complete_established_bye_dispatch(
            Err(SessionError::InvalidTransition(
                "BYE was not dispatched".to_string(),
            )),
            false,
            confirmation,
        )
        .await;

        assert!(matches!(result, Err(SessionError::InvalidTransition(_))));
        assert!(!confirmation_polled.load(std::sync::atomic::Ordering::Relaxed));
    }

    #[tokio::test]
    async fn setup_teardown_deadlines_are_compact_ordered_and_bounded() {
        let store = SessionStore::with_capacity(4);
        let mut handles = Vec::new();
        for _ in 0..3 {
            let session_id = SessionId::new();
            store
                .create_session(session_id.clone(), Role::UAC, false)
                .await
                .expect("create exact timeout fixture");
            handles.push(
                store
                    .lifecycle_handle(&session_id)
                    .expect("fixture lifecycle handle"),
            );
        }

        let now = Instant::now();
        let entered_state_at = now;
        let mut queue = SetupTeardownDeadlineQueue::default();
        assert!(queue.push(
            now + Duration::from_secs(3),
            handles[0].clone(),
            entered_state_at,
            SetupTeardownWatchdogKind::OutboundSetup,
        ));
        assert!(queue.push(
            now + Duration::from_secs(1),
            handles[1].clone(),
            entered_state_at,
            SetupTeardownWatchdogKind::InboundSetup,
        ));
        assert!(!queue.push(
            now + Duration::from_secs(2),
            handles[2].clone(),
            entered_state_at,
            SetupTeardownWatchdogKind::Cancellation,
        ));

        assert_eq!(queue.next_deadline(), Some(now + Duration::from_secs(1)));
        let first = queue.take_due(now + Duration::from_secs(2), 1);
        assert_eq!(first.len(), 1);
        assert_eq!(first[0].kind, SetupTeardownWatchdogKind::InboundSetup);
        let second = queue.take_due(now + Duration::from_secs(2), 8);
        assert_eq!(second.len(), 1);
        assert_eq!(second[0].kind, SetupTeardownWatchdogKind::Cancellation);
        assert_eq!(queue.drain().len(), 1);

        assert!(
            std::mem::size_of::<SetupTeardownDeadline>() <= 128,
            "deadline records must stay compact"
        );
        let scheduler = SetupTeardownDeadlineScheduler::default();
        assert_eq!(
            scheduler.fire_slots.available_permits(),
            SETUP_TEARDOWN_TIMEOUT_CONCURRENCY
        );
    }

    #[tokio::test]
    async fn retained_media_watchdog_sleep_wakes_and_joins_on_close() {
        let scheduler = Arc::new(SetupTeardownDeadlineScheduler::default());
        let task_scheduler = Arc::clone(&scheduler);
        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
        let (result_tx, result_rx) = tokio::sync::oneshot::channel();
        assert!(scheduler.spawn_lifecycle_task(async move {
            let _ = started_tx.send(());
            let expired = task_scheduler
                .sleep_or_closed(Duration::from_secs(60))
                .await;
            let _ = result_tx.send(expired);
        }));
        started_rx.await.expect("media watchdog sleep started");

        scheduler
            .close_and_wait(Duration::from_secs(1))
            .await
            .expect("close woke and joined retained media watchdog");
        assert!(!result_rx.await.expect("watchdog returned close outcome"));
        assert_eq!(scheduler.tasks.count(), 0);
    }

    #[tokio::test(start_paused = true)]
    async fn exact_terminal_release_cancels_future_deadline_without_crossing_reuse() {
        let coordinator = UnifiedCoordinator::new(
            Config::local("terminal-release-deadline-cancel", 0)
                .with_setup_teardown_timeout_secs(120),
        )
        .await
        .expect("start deadline-cancellation coordinator");
        let store = Arc::clone(&coordinator.helpers.state_machine.store);
        let session_id = SessionId::from("terminal-release-reused-deadline-id");

        store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("create deadline generation A");
        let generation_a = store
            .lifecycle_handle(&session_id)
            .expect("capture deadline generation A");
        let entered_a = Instant::now();
        store
            .update_session_exact_with(&generation_a, None, |session| {
                session.call_state = CallState::Initiating;
                session.entered_state_at = entered_a;
            })
            .expect("arm deadline generation A");
        let original_deadline = Instant::now() + Duration::from_secs(120);
        assert!(coordinator.setup_teardown_scheduler.schedule(
            original_deadline,
            generation_a.clone(),
            entered_a,
            SetupTeardownWatchdogKind::OutboundSetup,
        ));
        assert_eq!(
            coordinator.setup_teardown_scheduler.len(),
            1,
            "generation A owns one future deadline"
        );

        coordinator
            .release_after_observed_terminal_exact(&generation_a)
            .await;
        assert!(
            Instant::now() < original_deadline,
            "release must cancel instead of waiting for the original deadline"
        );
        assert_eq!(
            coordinator.setup_teardown_scheduler.len(),
            0,
            "exact terminal release must immediately drain pending_deadlines"
        );
        assert!(store.lifecycle_handle(&session_id).is_none());

        assert!(
            store.authority().elapse_reuse_horizon_for_test(&session_id),
            "expire the generation-A raw-ID reuse fence"
        );
        store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("create deadline generation B");
        let generation_b = store
            .lifecycle_handle(&session_id)
            .expect("capture deadline generation B");
        assert_ne!(generation_a, generation_b);
        let entered_b = Instant::now();
        store
            .update_session_exact_with(&generation_b, None, |session| {
                session.call_state = CallState::Initiating;
                session.entered_state_at = entered_b;
            })
            .expect("arm deadline generation B");
        assert!(coordinator.setup_teardown_scheduler.schedule(
            Instant::now() + Duration::from_secs(120),
            generation_b.clone(),
            entered_b,
            SetupTeardownWatchdogKind::OutboundSetup,
        ));

        let stale_generation_a = coordinator.setup_teardown_deadline_cancellation();
        stale_generation_a.begin_lifetime_close(&generation_a);
        stale_generation_a.finish_lifetime_close(&generation_a);
        assert_eq!(
            coordinator.setup_teardown_scheduler.len(),
            1,
            "stale generation-A cancellation must not remove generation B"
        );
        assert_eq!(
            store.lifecycle_handle(&session_id),
            Some(generation_b.clone())
        );

        coordinator
            .release_after_observed_terminal_exact(&generation_b)
            .await;
        assert_eq!(coordinator.setup_teardown_scheduler.len(), 0);
        coordinator
            .shutdown_gracefully(Some(Duration::ZERO))
            .await
            .expect("deadline-cancellation coordinator shut down");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn setup_deadline_paused_before_dispatch_rejects_raw_id_reuse() {
        let coordinator = UnifiedCoordinator::new(Config::local("setup-timeout-exact", 0))
            .await
            .expect("start setup-timeout exact coordinator");
        let store = Arc::clone(&coordinator.helpers.state_machine.store);
        let session_id = SessionId::from("setup-timeout-reused-id");
        store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("create original setup-timeout lifetime");
        let original = store
            .lifecycle_handle(&session_id)
            .expect("original setup-timeout handle");
        let entered_state_at = Instant::now();
        store
            .update_session_exact_with(&original, None, |session| {
                session.call_state = crate::types::CallState::Initiating;
                session.entered_state_at = entered_state_at;
            })
            .expect("arm original setup-timeout lifetime");

        coordinator
            .setup_teardown_scheduler
            .pause_next_fire_for_test();
        let firing_coordinator = Arc::clone(&coordinator);
        let stale_deadline = SetupTeardownDeadline {
            deadline: Instant::now(),
            sequence: 0,
            handle: original.clone(),
            entered_state_at,
            kind: SetupTeardownWatchdogKind::OutboundSetup,
        };
        let fire = tokio::spawn(async move {
            firing_coordinator
                .fire_setup_teardown_deadline(stale_deadline)
                .await;
        });
        tokio::time::timeout(
            Duration::from_secs(2),
            coordinator
                .setup_teardown_scheduler
                .wait_for_paused_fire_for_test(),
        )
        .await
        .expect("setup timeout reached its pre-dispatch pause");

        store
            .remove_session_exact(&original)
            .await
            .expect("retire original setup-timeout lifetime while fire is paused");
        assert!(
            store.authority().elapse_reuse_horizon_for_test(&session_id),
            "expire the setup-timeout raw-ID reuse fence"
        );
        store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("reuse setup-timeout raw identifier");
        let replacement = store
            .lifecycle_handle(&session_id)
            .expect("replacement setup-timeout handle");
        assert_ne!(original, replacement);
        store
            .update_session_exact_with(&replacement, None, |session| {
                session.call_state = crate::types::CallState::Initiating;
                session.entered_state_at = Instant::now();
            })
            .expect("arm replacement setup-timeout lifetime");

        coordinator
            .setup_teardown_scheduler
            .resume_paused_fire_for_test();
        tokio::time::timeout(Duration::from_secs(2), fire)
            .await
            .expect("stale setup-timeout fire completed")
            .expect("stale setup-timeout fire task joined");

        assert_eq!(
            store.lifecycle_handle(&session_id),
            Some(replacement.clone())
        );
        assert_eq!(
            store
                .get_session_exact(&replacement)
                .await
                .expect("replacement setup-timeout lifetime remains live")
                .call_state,
            crate::types::CallState::Initiating,
            "stale setup timeout crossed raw-ID reuse"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn active_media_timeout_paused_before_dispatch_rejects_raw_id_reuse() {
        let coordinator = UnifiedCoordinator::new(Config::local("media-timeout-exact", 0))
            .await
            .expect("start active-media exact coordinator");
        let store = Arc::clone(&coordinator.helpers.state_machine.store);
        let session_id = SessionId::from("media-timeout-reused-id");
        store
            .create_session(session_id.clone(), Role::UAS, false)
            .await
            .expect("create original active-media lifetime");
        let original = store
            .lifecycle_handle(&session_id)
            .expect("original active-media handle");
        store
            .update_session_exact_with(&original, None, |session| {
                session.call_state = crate::types::CallState::Active;
                session.entered_state_at = Instant::now();
            })
            .expect("arm original active-media lifetime");
        assert!(
            store.get_session_snapshot_exact(&original).is_ok(),
            "active-media preflight must accept the original exact lifetime"
        );

        let retained_coordinator = Arc::clone(&coordinator);
        let stale_handle = original.clone();
        let (paused_tx, paused_rx) = tokio::sync::oneshot::channel();
        let (resume_tx, resume_rx) = tokio::sync::oneshot::channel();
        let fire = tokio::spawn(async move {
            let _ = paused_tx.send(());
            let _ = resume_rx.await;
            retained_coordinator
                .hangup_exact_with_reason(&stale_handle, "Active call released after media timeout")
                .await
        });
        paused_rx
            .await
            .expect("active-media timeout reached its pre-dispatch pause");

        store
            .remove_session_exact(&original)
            .await
            .expect("retire original active-media lifetime while fire is paused");
        assert!(
            store.authority().elapse_reuse_horizon_for_test(&session_id),
            "expire the active-media raw-ID reuse fence"
        );
        store
            .create_session(session_id.clone(), Role::UAS, false)
            .await
            .expect("reuse active-media raw identifier");
        let replacement = store
            .lifecycle_handle(&session_id)
            .expect("replacement active-media handle");
        assert_ne!(original, replacement);
        store
            .update_session_exact_with(&replacement, None, |session| {
                session.call_state = crate::types::CallState::Active;
                session.entered_state_at = Instant::now();
            })
            .expect("arm replacement active-media lifetime");

        let _ = resume_tx.send(());
        let dispatch_error = tokio::time::timeout(Duration::from_secs(2), fire)
            .await
            .expect("stale active-media fire completed")
            .expect("stale active-media fire task joined")
            .expect_err("stale active-media handle must fail closed");
        assert!(
            dispatch_error.to_string().contains("not current")
                || dispatch_error.to_string().contains("not found")
                || dispatch_error.to_string().contains("stale"),
            "unexpected stale active-media error: {dispatch_error}"
        );
        assert_eq!(
            store.lifecycle_handle(&session_id),
            Some(replacement.clone())
        );
        assert_eq!(
            store
                .get_session_exact(&replacement)
                .await
                .expect("replacement active-media lifetime remains live")
                .call_state,
            crate::types::CallState::Active,
            "stale active-media timeout crossed raw-ID reuse"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn earlier_deadline_wakes_runner_without_waking_media_waiter() {
        let coordinator = UnifiedCoordinator::new(Config::local("split-watchdog-notifies", 0))
            .await
            .expect("start split-notify coordinator");
        let store = &coordinator.helpers.state_machine.store;

        let late = SessionId::new();
        store
            .create_session(late.clone(), Role::UAC, false)
            .await
            .expect("create late-deadline session");
        let late_entered_at = Instant::now();
        store
            .update_session_with(&late, |session| {
                session.call_state = crate::types::CallState::Initiating;
                session.entered_state_at = late_entered_at;
            })
            .await
            .expect("arm late-deadline state");
        let late_handle = store
            .lifecycle_handle(&late)
            .expect("late-deadline exact handle");
        let late_deadline = Instant::now() + Duration::from_secs(60);
        assert!(coordinator.setup_teardown_scheduler.schedule(
            late_deadline,
            late_handle,
            late_entered_at,
            SetupTeardownWatchdogKind::OutboundSetup,
        ));
        tokio::time::timeout(
            Duration::from_secs(2),
            coordinator
                .setup_teardown_scheduler
                .wait_for_runner_deadline_for_test(late_deadline),
        )
        .await
        .expect("runner began sleeping on late deadline");

        let media_scheduler = Arc::clone(&coordinator.setup_teardown_scheduler);
        let task_scheduler = Arc::clone(&media_scheduler);
        let (media_started_tx, media_started_rx) = tokio::sync::oneshot::channel();
        let (media_result_tx, mut media_result_rx) = tokio::sync::oneshot::channel();
        assert!(media_scheduler.spawn_lifecycle_task(async move {
            let _ = media_started_tx.send(());
            let expired = task_scheduler
                .sleep_or_closed(Duration::from_secs(60))
                .await;
            let _ = media_result_tx.send(expired);
        }));
        media_started_rx.await.expect("media waiter started");

        let early = SessionId::new();
        store
            .create_session(early.clone(), Role::UAC, false)
            .await
            .expect("create early-deadline session");
        let early_entered_at = Instant::now();
        store
            .update_session_with(&early, |session| {
                session.call_state = crate::types::CallState::Initiating;
                session.entered_state_at = early_entered_at;
            })
            .await
            .expect("arm early-deadline state");
        let early_handle = store
            .lifecycle_handle(&early)
            .expect("early-deadline exact handle");
        let mut early_lifecycle = coordinator.lifecycle_watcher_exact(&early_handle);
        assert!(coordinator.setup_teardown_scheduler.schedule(
            Instant::now() + Duration::from_millis(50),
            early_handle.clone(),
            early_entered_at,
            SetupTeardownWatchdogKind::OutboundSetup,
        ));

        tokio::time::timeout(Duration::from_secs(2), early_lifecycle.changed())
            .await
            .expect("earlier deadline fired while runner had a later timer")
            .expect("early lifecycle remained observable");
        let completion = match coordinator
            .app_event_publisher
            .claim_exact_terminal(&early_handle)
        {
            ExactTerminalClaim::Observer(observer) => observer.wait().await,
            ExactTerminalClaim::Owner(_) => {
                panic!("earlier deadline must already own exact terminal release")
            }
        };
        exact_terminal_completion_result(completion)
            .expect("earlier deadline exact release completed");
        assert!(matches!(
            media_result_rx.try_recv(),
            Err(tokio::sync::oneshot::error::TryRecvError::Empty)
        ));

        coordinator
            .shutdown_gracefully(Some(Duration::ZERO))
            .await
            .expect("split-notify coordinator shut down");
        assert!(!media_result_rx.await.expect("media waiter observed close"));
        assert!(
            store.lifecycle_handle(&late).is_some(),
            "later deadline must be drained rather than fired"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn shared_setup_teardown_scheduler_fires_disarms_and_drains_exactly() {
        let coordinator = UnifiedCoordinator::new(
            Config::local("shared-watchdog-scheduler", 0).with_setup_teardown_timeout_secs(1),
        )
        .await
        .expect("start watchdog test coordinator");
        let store = &coordinator.helpers.state_machine.store;

        let firing = SessionId::new();
        store
            .create_session(firing.clone(), Role::UAC, false)
            .await
            .expect("create firing session");
        store
            .update_session_with(&firing, |session| {
                session.call_state = crate::types::CallState::Initiating;
                session.entered_state_at = Instant::now();
            })
            .await
            .expect("arm firing state");
        let firing_handle = store
            .lifecycle_handle(&firing)
            .expect("firing fixture handle");
        let mut firing_lifecycle = coordinator.lifecycle_watcher_exact(&firing_handle);
        coordinator
            .schedule_setup_teardown_timeout_if_current(
                &firing,
                SetupTeardownWatchdogKind::OutboundSetup,
            )
            .await;

        let changed = SessionId::new();
        store
            .create_session(changed.clone(), Role::UAC, false)
            .await
            .expect("create changed-state session");
        store
            .update_session_with(&changed, |session| {
                session.call_state = crate::types::CallState::Initiating;
                session.entered_state_at = Instant::now();
            })
            .await
            .expect("arm changed-state session");
        coordinator
            .schedule_setup_teardown_timeout_if_current(
                &changed,
                SetupTeardownWatchdogKind::OutboundSetup,
            )
            .await;
        store
            .update_session_with(&changed, |session| {
                session.call_state = crate::types::CallState::Active;
                session.entered_state_at = Instant::now();
            })
            .await
            .expect("advance changed-state session");

        let stale = SessionId::new();
        store
            .create_session(stale.clone(), Role::UAC, false)
            .await
            .expect("create stale-handle session");
        let stale_handle = store
            .lifecycle_handle(&stale)
            .expect("stale fixture current handle")
            .with_next_slot_revision_for_test();
        assert!(
            !coordinator.setup_teardown_scheduler.schedule(
                Instant::now() + Duration::from_millis(100),
                stale_handle,
                Instant::now(),
                SetupTeardownWatchdogKind::OutboundSetup,
            ),
            "stale exact lifetime must be rejected at deadline admission"
        );

        tokio::time::timeout(Duration::from_secs(4), firing_lifecycle.changed())
            .await
            .expect("firing watchdog lifecycle deadline")
            .expect("firing watchdog lifecycle remains observable");
        let completion = match coordinator
            .app_event_publisher
            .claim_exact_terminal(&firing_handle)
        {
            ExactTerminalClaim::Observer(observer) => {
                tokio::time::timeout(Duration::from_secs(4), observer.wait())
                    .await
                    .expect("firing watchdog exact release deadline")
            }
            ExactTerminalClaim::Owner(_) => {
                panic!("terminal lifecycle path must already own the exact release")
            }
        };
        exact_terminal_completion_result(completion)
            .expect("firing watchdog exact release must complete");
        assert_eq!(coordinator.setup_teardown_scheduler.len(), 0);
        assert!(
            store.lifecycle_handle(&firing).is_none(),
            "the one current deadline must fire and release its exact lifetime"
        );
        assert!(
            store.lifecycle_handle(&changed).is_some(),
            "a state/revision change must disarm instead of firing"
        );
        assert!(
            store.lifecycle_handle(&stale).is_some(),
            "a stale exact handle must not target the current lifetime"
        );

        let shutdown = SessionId::new();
        store
            .create_session(shutdown.clone(), Role::UAC, false)
            .await
            .expect("create shutdown session");
        let shutdown_handle = store
            .lifecycle_handle(&shutdown)
            .expect("shutdown fixture handle");
        assert!(coordinator.setup_teardown_scheduler.schedule(
            Instant::now() + Duration::from_secs(60),
            shutdown_handle,
            Instant::now(),
            SetupTeardownWatchdogKind::OutboundSetup,
        ));
        coordinator.shutdown();
        let shutdown_deadline = tokio::time::Instant::now() + Duration::from_secs(2);
        while coordinator.setup_teardown_scheduler.len() != 0
            && tokio::time::Instant::now() < shutdown_deadline
        {
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        assert_eq!(coordinator.setup_teardown_scheduler.len(), 0);
        assert!(
            store.lifecycle_handle(&shutdown).is_some(),
            "shutdown must drain a future deadline without firing it"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn graceful_shutdown_joins_claimed_watchdog_before_stopping_dependencies() {
        let coordinator = UnifiedCoordinator::new(Config::local("watchdog-drain-join", 0))
            .await
            .expect("start watchdog drain coordinator");
        let store = &coordinator.helpers.state_machine.store;
        let session_id = SessionId::new();
        store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("create firing session");
        let entered_state_at = Instant::now();
        store
            .update_session_with(&session_id, |session| {
                session.call_state = crate::types::CallState::Initiating;
                session.entered_state_at = entered_state_at;
            })
            .await
            .expect("arm firing state");
        let handle = store
            .lifecycle_handle(&session_id)
            .expect("firing session exact handle");

        coordinator
            .setup_teardown_scheduler
            .pause_next_fire_for_test();
        assert!(coordinator.setup_teardown_scheduler.schedule(
            Instant::now(),
            handle,
            entered_state_at,
            SetupTeardownWatchdogKind::OutboundSetup,
        ));
        tokio::time::timeout(
            Duration::from_secs(2),
            coordinator
                .setup_teardown_scheduler
                .wait_for_paused_fire_for_test(),
        )
        .await
        .expect("watchdog fire reached deterministic pause");

        let first_coordinator = Arc::clone(&coordinator);
        let first_shutdown = tokio::spawn(async move {
            first_coordinator
                .shutdown_gracefully(Some(Duration::ZERO))
                .await
        });
        let second_coordinator = Arc::clone(&coordinator);
        let second_shutdown = tokio::spawn(async move {
            second_coordinator
                .shutdown_gracefully(Some(Duration::ZERO))
                .await
        });
        tokio::time::timeout(Duration::from_secs(2), async {
            while coordinator.setup_teardown_scheduler.is_accepting_for_test() {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("shutdown established scheduler close boundary");
        assert!(!first_shutdown.is_finished());
        assert!(!second_shutdown.is_finished());

        coordinator
            .setup_teardown_scheduler
            .resume_paused_fire_for_test();
        tokio::time::timeout(Duration::from_secs(4), first_shutdown)
            .await
            .expect("first graceful shutdown joined watchdog")
            .expect("first shutdown task joined")
            .expect("first graceful shutdown succeeded");
        tokio::time::timeout(Duration::from_secs(4), second_shutdown)
            .await
            .expect("second graceful shutdown joined shared attempt")
            .expect("second shutdown task joined")
            .expect("second graceful shutdown succeeded");
        assert!(
            store.lifecycle_handle(&session_id).is_none(),
            "graceful shutdown must wait through exact terminal release"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn graceful_shutdown_drains_future_deadline_and_rejects_new_schedule() {
        let coordinator = UnifiedCoordinator::new(Config::local("watchdog-future-drain", 0))
            .await
            .expect("start future-drain coordinator");
        let store = &coordinator.helpers.state_machine.store;
        let session_id = SessionId::new();
        store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("create future-deadline session");
        let handle = store
            .lifecycle_handle(&session_id)
            .expect("future-deadline exact handle");
        assert!(coordinator.setup_teardown_scheduler.schedule(
            Instant::now() + Duration::from_secs(60),
            handle.clone(),
            Instant::now(),
            SetupTeardownWatchdogKind::OutboundSetup,
        ));

        coordinator
            .shutdown_gracefully(Some(Duration::ZERO))
            .await
            .expect("graceful shutdown drained future deadline");
        assert_eq!(coordinator.setup_teardown_scheduler.len(), 0);
        assert!(
            store.lifecycle_handle(&session_id).is_some(),
            "a future deadline must be disarmed without firing"
        );
        assert!(!coordinator.setup_teardown_scheduler.schedule(
            Instant::now(),
            handle,
            Instant::now(),
            SetupTeardownWatchdogKind::OutboundSetup,
        ));
        assert_eq!(coordinator.setup_teardown_scheduler.len(), 0);
    }

    #[tokio::test]
    async fn hangup_without_exact_lifetime_fails_before_raw_id_reuse() {
        let coordinator = UnifiedCoordinator::new(Config::local("hangup-reuse-fence", 0))
            .await
            .expect("start hangup reuse coordinator");
        let reused = SessionId("hangup-reuse-fence-session".to_string());
        assert!(matches!(
            coordinator.hangup(&reused).await,
            Err(SessionError::SessionNotFound(_))
        ));

        coordinator
            .helpers
            .state_machine
            .store
            .create_session(reused.clone(), Role::UAC, false)
            .await
            .expect("reuse raw id after rejected hangup");
        tokio::task::yield_now().await;
        assert!(
            coordinator
                .helpers
                .state_machine
                .store
                .lifecycle_handle(&reused)
                .is_some(),
            "rejected raw-id hangup must not leave detached work targeting a later lifetime"
        );
        coordinator
            .shutdown_gracefully(Some(Duration::ZERO))
            .await
            .expect("hangup reuse coordinator shut down");
    }

    #[test]
    fn coordinator_in_dialog_builder_facades_capture_at_construction() {
        let source = include_str!("unified.rs");
        for (method, builder) in [
            ("bye", "ByeBuilder"),
            ("cancel", "CancelBuilder"),
            ("refer", "ReferBuilder"),
            ("notify", "NotifyBuilder"),
            ("info", "InfoBuilder"),
            ("update", "UpdateBuilder"),
            ("reinvite", "ReInviteBuilder"),
        ] {
            let start = format!("    pub fn {method}(");
            let body = source
                .split(&start)
                .nth(1)
                .and_then(|tail| tail.split("\n    /// Begin building").next())
                .unwrap_or_else(|| panic!("missing UnifiedCoordinator::{method} source"));
            assert!(
                body.contains("store.lifecycle_handle(session)"),
                "UnifiedCoordinator::{method} did not capture the exact lifetime at builder construction"
            );
            assert!(
                body.contains(&format!("{builder}::new_captured")),
                "UnifiedCoordinator::{method} did not pass captured authority to {builder}"
            );
        }
    }

    #[tokio::test]
    async fn coordinator_in_dialog_builders_cannot_target_a_reused_generation() {
        fn assert_generation_unchanged(
            store: &SessionStore,
            handle: &crate::session_registry::SessionRegistryHandle,
            expected_state: CallState,
            expected_revision: u64,
            label: &str,
        ) {
            let snapshot = store
                .get_session_snapshot_exact(handle)
                .unwrap_or_else(|_| panic!("generation B disappeared after stale {label}"));
            assert_eq!(
                snapshot.call_state, expected_state,
                "generation-A {label} builder changed generation B state"
            );
            assert_eq!(
                snapshot.revision(),
                expected_revision,
                "generation-A {label} builder committed against generation B"
            );
        }

        let coordinator = UnifiedCoordinator::new(Config::local("builder-reuse-fence", 0))
            .await
            .expect("start builder reuse coordinator");
        let store = Arc::clone(&coordinator.helpers.state_machine.store);
        let call_id = CallId::from("coordinator-builder-reused-id");
        store
            .create_session(call_id.clone(), Role::UAC, false)
            .await
            .expect("create generation A");
        let generation_a = store
            .lifecycle_handle(&call_id)
            .expect("capture generation A");

        // Every facade is intentionally deferred here. The exact authority
        // must be captured now, before application option staging and await.
        let bye = coordinator.bye(&call_id);
        let cancel = coordinator.cancel(&call_id);
        let refer = coordinator.refer(&call_id, "sip:transfer@example.test");
        let notify = coordinator.notify(&call_id, "refer");
        let info = coordinator.info(&call_id, "application/dtmf-relay");
        let update = coordinator.update(&call_id);
        let reinvite = coordinator.reinvite(&call_id);

        store
            .remove_session_exact(&generation_a)
            .await
            .expect("retire generation A");
        assert!(
            store.authority().elapse_reuse_horizon_for_test(&call_id),
            "expire the raw-id reuse horizon"
        );
        store
            .create_session(call_id.clone(), Role::UAC, false)
            .await
            .expect("create generation B");
        let generation_b = store
            .lifecycle_handle(&call_id)
            .expect("capture generation B");
        assert_ne!(generation_a, generation_b);

        store
            .update_session_exact_with(&generation_b, None, |session| {
                session.call_state = CallState::Initiating;
            })
            .expect("make generation B eligible for CANCEL");
        let before_cancel = store
            .get_session_snapshot_exact(&generation_b)
            .expect("generation B before stale CANCEL")
            .revision();
        assert!(cancel.send().await.is_err());
        assert_generation_unchanged(
            store.as_ref(),
            &generation_b,
            CallState::Initiating,
            before_cancel,
            "CANCEL",
        );

        store
            .update_session_exact_with(&generation_b, None, |session| {
                session.call_state = CallState::Active;
            })
            .expect("make generation B eligible for confirmed in-dialog methods");

        let before_bye = store
            .get_session_snapshot_exact(&generation_b)
            .expect("generation B before stale BYE")
            .revision();
        assert!(bye.send().await.is_err());
        assert_generation_unchanged(
            store.as_ref(),
            &generation_b,
            CallState::Active,
            before_bye,
            "BYE",
        );

        let before_refer = store
            .get_session_snapshot_exact(&generation_b)
            .expect("generation B before stale REFER")
            .revision();
        assert!(refer.send().await.is_err());
        assert_generation_unchanged(
            store.as_ref(),
            &generation_b,
            CallState::Active,
            before_refer,
            "REFER",
        );

        let before_notify = store
            .get_session_snapshot_exact(&generation_b)
            .expect("generation B before stale NOTIFY")
            .revision();
        assert!(notify.send().await.is_err());
        assert_generation_unchanged(
            store.as_ref(),
            &generation_b,
            CallState::Active,
            before_notify,
            "NOTIFY",
        );

        let before_info = store
            .get_session_snapshot_exact(&generation_b)
            .expect("generation B before stale INFO")
            .revision();
        assert!(info.send().await.is_err());
        assert_generation_unchanged(
            store.as_ref(),
            &generation_b,
            CallState::Active,
            before_info,
            "INFO",
        );

        let before_update = store
            .get_session_snapshot_exact(&generation_b)
            .expect("generation B before stale UPDATE")
            .revision();
        assert!(update.send().await.is_err());
        assert_generation_unchanged(
            store.as_ref(),
            &generation_b,
            CallState::Active,
            before_update,
            "UPDATE",
        );

        let before_reinvite = store
            .get_session_snapshot_exact(&generation_b)
            .expect("generation B before stale re-INVITE")
            .revision();
        assert!(reinvite.send().await.is_err());
        assert_generation_unchanged(
            store.as_ref(),
            &generation_b,
            CallState::Active,
            before_reinvite,
            "re-INVITE",
        );

        coordinator
            .shutdown_gracefully(Some(Duration::ZERO))
            .await
            .expect("builder reuse coordinator shut down");
    }

    impl std::fmt::Debug for CanaryTracePolicy {
        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            formatter
                .debug_tuple("CanaryTracePolicy")
                .field(&self.0)
                .finish()
        }
    }

    impl TraceRedactor for CanaryTracePolicy {
        fn redact(&self, _header: &HeaderName, _value: &str) -> RedactionDecision {
            RedactionDecision::Keep
        }
    }

    #[test]
    fn transaction_command_channel_default_is_small_and_configurable() {
        assert_eq!(Config::DEFAULT_SIP_TRANSACTION_COMMAND_CHANNEL_CAPACITY, 32);
        let config =
            Config::local("alice", 5060).with_sip_transaction_command_channel_capacity(256);
        assert_eq!(config.sip_transaction_command_channel_capacity, Some(256));
        config.validate().expect("valid command channel capacity");
    }

    #[test]
    fn inbound_tls_client_auth_is_disabled_by_default_and_validated_when_enabled() {
        use rvoip_sip_transport::transport::tls::{TlsClientAuthMode, TlsServerClientAuthConfig};

        let default = Config::local("alice", 5060);
        assert_eq!(
            default.tls_server_client_auth.mode,
            TlsClientAuthMode::Disabled
        );

        let no_listener = Config::local("alice", 5060)
            .require_tls_client_certificate("client-ca.pem")
            .validate()
            .expect_err("client auth without a TLS listener must fail");
        assert!(matches!(
            no_listener,
            SessionError::ConfigError(ref detail) if detail.contains("requires a SIP TLS listener")
        ));

        let missing_ca = Config::local("alice", 5060)
            .tls_reachable_contact(
                "127.0.0.1:5061".parse().unwrap(),
                "server.pem",
                "server-key.pem",
            )
            .with_tls_server_client_auth(TlsServerClientAuthConfig {
                mode: TlsClientAuthMode::Required,
                client_ca_path: None,
            })
            .validate()
            .expect_err("enabled client auth without a CA must fail");
        assert!(matches!(
            missing_ca,
            SessionError::ConfigError(ref detail) if detail.contains("client CA bundle")
        ));

        let valid = Config::local("alice", 5060)
            .tls_reachable_contact(
                "127.0.0.1:5061".parse().unwrap(),
                "server.pem",
                "server-key.pem",
            )
            .verify_optional_tls_client_certificate("client-ca.pem");
        valid.validate().expect("complete inbound client auth");
        assert_eq!(
            valid.tls_server_client_auth.mode,
            TlsClientAuthMode::Optional
        );
    }

    #[test]
    fn transaction_command_channel_capacity_rejects_zero() {
        let error = Config::local("alice", 5060)
            .with_sip_transaction_command_channel_capacity(0)
            .validate()
            .expect_err("zero transaction command channel capacity should fail");
        assert!(matches!(
            error,
            SessionError::ConfigError(ref detail)
                if detail.contains("sip_transaction_command_channel_capacity")
        ));
    }

    #[test]
    fn high_cps_profile_sets_tunable_transaction_command_capacity() {
        let config = Config::local("alice", 5060).with_high_cps_udp_auto_answer(8000);
        assert_eq!(config.sip_transaction_command_channel_capacity, Some(1000));

        let overridden = Config::local("alice", 5060)
            .with_sip_transaction_command_channel_capacity(64)
            .with_high_cps_udp_auto_answer(8000);
        assert_eq!(
            overridden.sip_transaction_command_channel_capacity,
            Some(64)
        );
    }

    #[test]
    fn g729_annex_b_defaults_enabled_and_is_configurable() {
        let config = Config::local("alice", 5060);
        assert!(config.g729_annex_b);

        let config = Config::local("alice", 5060).with_g729_annex_b(false);
        assert!(!config.g729_annex_b);
    }

    #[cfg(feature = "g729")]
    #[test]
    fn g729_payload_is_valid_when_feature_enabled() {
        let mut config = Config::local("alice", 5060);
        config.offered_codecs = vec![18, 101];
        config.validate().expect("g729 feature should allow PT18");
    }

    #[cfg(not(feature = "g729"))]
    #[test]
    fn g729_payload_requires_feature() {
        let mut config = Config::local("alice", 5060);
        config.offered_codecs = vec![18, 101];
        let error = config
            .validate()
            .expect_err("PT18 should require the g729 feature");
        assert!(matches!(
            error,
            SessionError::ConfigError(ref detail) if detail.contains("`g729` feature")
        ));
    }

    #[cfg(feature = "opus")]
    #[test]
    fn opus_payload_is_valid_when_feature_enabled() {
        let mut config = Config::local("alice", 5060);
        config.offered_codecs = vec![111, 101];
        config.validate().expect("opus feature should allow PT111");
    }

    #[cfg(not(feature = "opus"))]
    #[test]
    fn opus_payload_requires_feature() {
        let mut config = Config::local("alice", 5060);
        config.offered_codecs = vec![111, 101];
        let error = config
            .validate()
            .expect_err("PT111 should require the opus feature");
        assert!(matches!(
            error,
            SessionError::ConfigError(ref detail) if detail.contains("`opus` feature")
        ));
    }

    #[test]
    fn active_call_media_watchdogs_are_disabled_by_default_and_configurable() {
        let config = Config::local("alice", 5060);
        assert_eq!(config.active_call_no_media_timeout_secs, 0);
        assert_eq!(config.active_call_media_idle_timeout_secs, 0);

        let config = config
            .with_active_call_no_media_timeout_secs(60)
            .with_active_call_media_idle_timeout_secs(90);
        assert_eq!(config.active_call_no_media_timeout_secs, 60);
        assert_eq!(config.active_call_media_idle_timeout_secs, 90);
        config.validate().expect("valid media watchdog timeouts");
    }

    #[test]
    fn diagnostic_debug_omits_config_auth_routing_and_registration_secrets() {
        let mut config = Config::local("local-name-secret", 5060);
        config.local_uri = "sip:local-uri-secret@example.invalid".into();
        config.state_table_path = Some("state-table-secret".into());
        config.credentials = Some(crate::types::Credentials::new(
            "credential-user-secret",
            "credential-password-secret",
        ));
        config.auth = Some(crate::auth::SipClientAuth::bearer_token(
            "bearer-policy-secret",
        ));
        config.pai_uri = Some("sip:pai-secret@example.invalid".into());
        config.outbound_proxy_uri = Some("sip:proxy-secret@example.invalid".into());
        config.sip_instance = Some("instance-secret".into());
        config.contact_uri = Some("sip:contact-secret@example.invalid".into());
        config.tls_cert_path = Some("/cert/path-secret.pem".into());
        config.tls_key_path = Some("/key/path-secret.pem".into());
        config.tls_client_cert_path = Some("/client-cert/path-secret.pem".into());
        config.tls_client_key_path = Some("/client-key/path-secret.pem".into());
        config.tls_extra_ca_path = Some("/ca/path-secret.pem".into());
        config.tls_server_client_auth =
            rvoip_sip_transport::transport::tls::TlsServerClientAuthConfig::required(
                "/client-ca/path-secret.pem",
            );
        config.stun_server = Some("stun-secret.example.invalid".into());
        config.trace_redaction = Some(Arc::new(CanaryTracePolicy("trace-policy-secret")));

        let config_debug = format!("{config:?}");
        for secret in [
            "local-name-secret",
            "local-uri-secret",
            "state-table-secret",
            "credential-user-secret",
            "credential-password-secret",
            "bearer-policy-secret",
            "pai-secret",
            "proxy-secret",
            "instance-secret",
            "contact-secret",
            "path-secret",
            "stun-secret",
            "trace-policy-secret",
        ] {
            assert!(
                !config_debug.contains(secret),
                "Config Debug leaked {secret}"
            );
        }
        assert!(config_debug.contains("credentials_configured: true"));
        assert!(config_debug.contains("auth_configured: true"));
        assert!(config_debug.contains("outbound_proxy_configured: true"));
        assert!(config_debug.contains("tls_key_configured: true"));
        assert!(config_debug.contains("tls_server_client_auth_mode: Required"));

        let retry = OobAuthRetry {
            header_name: "Authorization-secret".into(),
            header_value: "header-value-secret".into(),
            cseq: 7,
            call_id: Some("call-routing-secret".into()),
            from_tag: Some("from-tag-secret".into()),
            nonce: "nonce-secret".into(),
            stale: true,
        };
        let retry_debug = format!("{retry:?}");
        for secret in [
            "Authorization-secret",
            "header-value-secret",
            "call-routing-secret",
            "from-tag-secret",
            "nonce-secret",
        ] {
            assert!(!retry_debug.contains(secret), "retry Debug leaked {secret}");
        }
        assert!(retry_debug.contains("nonce_configured: true"));
        assert!(retry_debug.contains("stale: true"));

        let registration = Registration::new(
            "sip:registrar-secret@example.invalid",
            "registration-user-secret",
            "registration-password-secret",
        )
        .from_uri("sip:from-secret@example.invalid")
        .contact_uri("sip:registration-contact-secret@example.invalid");
        let registration_debug = format!("{registration:?}");
        for secret in [
            "registrar-secret",
            "registration-user-secret",
            "registration-password-secret",
            "from-secret",
            "registration-contact-secret",
        ] {
            assert!(
                !registration_debug.contains(secret),
                "Registration Debug leaked {secret}"
            );
        }
        assert!(registration_debug.contains("password_configured: true"));

        let session_id = crate::state_table::types::SessionId::new();
        let session_secret = session_id.to_string();
        let handle = RegistrationHandle {
            session_id: session_id.clone(),
        };
        assert!(!format!("{handle:?}").contains(&session_secret));
        let info = RegistrationInfo {
            session_id,
            status: RegistrationStatus::Failed,
            registrar: Some("info-registrar-secret".into()),
            contact: Some("info-contact-secret".into()),
            expires_secs: Some(300),
            next_refresh_in: Some(Duration::from_secs(60)),
            retry_count: 2,
            last_failure: Some("failure-detail-secret".into()),
            accepted_expires_secs: Some(300),
            registered_at: Some(Instant::now()),
            next_refresh_at: Some(Instant::now()),
            service_route: Some(vec!["sip:service-route-secret@example.invalid".into()]),
            pub_gruu: Some("pub-gruu-secret".into()),
            temp_gruu: Some("temp-gruu-secret".into()),
            outbound_flow_active: true,
        };
        let info_debug = format!("{info:?}");
        for secret in [
            &session_secret,
            "info-registrar-secret",
            "info-contact-secret",
            "failure-detail-secret",
            "service-route-secret",
            "pub-gruu-secret",
            "temp-gruu-secret",
        ] {
            assert!(
                !info_debug.contains(secret),
                "RegistrationInfo Debug leaked {secret}"
            );
        }
        assert!(info_debug.contains("status: Failed"));
        assert!(info_debug.contains("service_route_count: 1"));
    }
}

#[cfg(all(test, feature = "perf-tests"))]
mod perf_config_tests {
    use super::{dialog_manager_retention_snapshot, Config};
    use crate::errors::SessionError;
    use rvoip_sip_dialog::manager::core::DialogManagerRetentionCounts;

    #[test]
    fn perf_rss_growth_default_is_ten_mb_per_hour() {
        assert_eq!(Config::DEFAULT_PERF_MAX_RSS_GROWTH_MB_PER_HR, 10.0);
        assert_eq!(
            Config::local("alice", 5060).perf_max_rss_growth_mb_per_hr,
            None
        );
    }

    #[test]
    fn perf_rss_growth_override_validates() {
        let config = Config::local("alice", 5060).with_perf_max_rss_growth_mb_per_hr(2.5);
        assert_eq!(config.perf_max_rss_growth_mb_per_hr, Some(2.5));
        config.validate().expect("valid perf rss threshold");
    }

    #[test]
    fn perf_rss_growth_rejects_invalid_values() {
        let expected_detail = "perf_max_rss_growth_mb_per_hr must be finite and greater than 0";
        for limit in [0.0, -1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            let config = Config::local("alice", 5060).with_perf_max_rss_growth_mb_per_hr(limit);
            let error = config
                .validate()
                .expect_err("invalid perf rss threshold should fail");
            assert!(
                matches!(
                    &error,
                    SessionError::ConfigError(detail)
                        if detail == expected_detail
                ),
                "unexpected error variant: {error:?}"
            );
            assert_eq!(
                error.to_string(),
                format!("Config error: redacted(bytes={})", expected_detail.len())
            );
        }
    }

    #[test]
    fn perf_dialog_snapshot_exposes_invite_failover_retention_counts() {
        let snapshot = dialog_manager_retention_snapshot(DialogManagerRetentionCounts {
            invite_failover_plans: 2,
            active_invite_failover_by_dialog: 3,
            invite_failover_plans_by_dialog: 4,
            invite_failover_attempts: 5,
            invite_failover_attempts_by_dialog: 6,
            invite_failover_plan_reservations: 7,
            invite_failover_attempt_reservations: 11,
            ..DialogManagerRetentionCounts::default()
        });

        assert_eq!(
            snapshot
                .pointer("/invite_failover_plans")
                .and_then(serde_json::Value::as_u64),
            Some(2)
        );
        assert_eq!(
            snapshot
                .pointer("/active_invite_failover_by_dialog")
                .and_then(serde_json::Value::as_u64),
            Some(3)
        );
        assert_eq!(
            snapshot
                .pointer("/invite_failover_plans_by_dialog")
                .and_then(serde_json::Value::as_u64),
            Some(4)
        );
        assert_eq!(
            snapshot
                .pointer("/invite_failover_attempts")
                .and_then(serde_json::Value::as_u64),
            Some(5)
        );
        assert_eq!(
            snapshot
                .pointer("/invite_failover_attempts_by_dialog")
                .and_then(serde_json::Value::as_u64),
            Some(6)
        );
        assert_eq!(
            snapshot
                .pointer("/invite_failover_plan_reservations")
                .and_then(serde_json::Value::as_u64),
            Some(7)
        );
        assert_eq!(
            snapshot
                .pointer("/invite_failover_attempt_reservations")
                .and_then(serde_json::Value::as_u64),
            Some(11)
        );
    }
}

#[cfg(feature = "perf-tests")]
fn dialog_manager_retention_snapshot(
    counts: rvoip_sip_dialog::manager::core::DialogManagerRetentionCounts,
) -> serde_json::Value {
    serde_json::json!({
        "dialogs": counts.dialogs,
        "dialog_lookup": counts.dialog_lookup,
        "early_dialog_lookup": counts.early_dialog_lookup,
        "terminated_bye_lookup": counts.terminated_bye_lookup,
        "terminated_bye_deadlines": counts.terminated_bye_deadlines,
        "transaction_to_dialog": counts.transaction_to_dialog,
        "transaction_dialog_route_hash": counts.transaction_dialog_route_hash,
        "dialog_invite_transactions": counts.dialog_invite_transactions,
        "invite_failover_plans": counts.invite_failover_plans,
        "active_invite_failover_by_dialog": counts.active_invite_failover_by_dialog,
        "invite_failover_plans_by_dialog": counts.invite_failover_plans_by_dialog,
        "invite_failover_attempts": counts.invite_failover_attempts,
        "invite_failover_attempts_by_dialog": counts.invite_failover_attempts_by_dialog,
        "invite_failover_plan_reservations": counts.invite_failover_plan_reservations,
        "invite_failover_attempt_reservations": counts.invite_failover_attempt_reservations,
        "dialog_server_transactions": counts.dialog_server_transactions,
        "pending_response_transaction_by_dialog": counts.pending_response_transaction_by_dialog,
        "session_to_dialog": counts.session_to_dialog,
        "dialog_to_session": counts.dialog_to_session,
        "reliable_provisional_tasks": counts.reliable_provisional_tasks,
        "session_refresh_tasks": counts.session_refresh_tasks,
        "outbound_flows": counts.outbound_flows,
        "outbound_flow_tasks": counts.outbound_flow_tasks,
        "flow_by_destination": counts.flow_by_destination,
        "flow_by_aor": counts.flow_by_aor,
    })
}

fn default_session_event_dispatcher_workers() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4)
        .clamp(1, 16)
}

/// Lower-level coordinator for SIP sessions, registrations, media, and events.
///
/// `UnifiedCoordinator` is intentionally explicit: most methods take or return
/// a [`SessionId`], and event consumers choose whether to subscribe to all
/// events or filter by session. This makes it suitable for applications that
/// manage more than one call leg at a time.
///
/// Use higher-level wrappers when possible:
///
/// - [`StreamPeer`](crate::api::stream_peer::StreamPeer) for sequential clients
///   and tests.
/// - [`CallbackPeer`](crate::api::callback_peer::CallbackPeer) for reactive
///   servers.
#[allow(dead_code)]
pub struct UnifiedCoordinator {
    /// State machine helpers
    pub(crate) helpers: Arc<StateMachineHelpers>,

    /// Media adapter for audio operations
    media_adapter: Arc<MediaAdapter>,

    /// Dialog adapter for SIP operations
    dialog_adapter: Arc<DialogAdapter>,

    /// Incoming call receiver
    incoming_rx: Arc<RwLock<mpsc::Receiver<IncomingCallInfo>>>,

    /// Global event coordinator — used to publish and subscribe to session API events.
    /// Events are published to the "session_to_app" channel.
    pub(crate) global_coordinator: Arc<GlobalEventCoordinator>,

    /// Single response owner for application-controlled inbound requests.
    session_control_rx:
        tokio::sync::Mutex<Option<mpsc::UnboundedReceiver<crate::adapters::SessionControlEvent>>>,

    /// Becomes true only after a public peer surface claims the control queue.
    session_control_claimed: Arc<AtomicBool>,

    /// Configuration
    config: Config,

    /// Shutdown signal — send `true` to stop all background tasks.
    shutdown_tx: tokio::sync::watch::Sender<bool>,

    /// Cancellation-safe singleflight for ordered dependency shutdown.
    shutdown_flights: CoordinatorShutdownFlights,

    /// Per-call lifecycle index for deterministic late waiters.
    lifecycle: LifecycleIndex,

    /// App event publisher that updates lifecycle before global bus delivery.
    app_event_publisher: SessionEventPublisher,

    /// One compact deadline queue shared by every setup/teardown watchdog.
    /// The scheduler task itself retains only a weak coordinator reference.
    setup_teardown_scheduler: Arc<SetupTeardownDeadlineScheduler>,

    /// Strong ownership and one shared deadline queue for application-owned
    /// exact INFO and REGISTER responses. Session-scoped entries carry an
    /// exact generation; standalone REGISTER entries carry only their server
    /// transaction. This keeps an unanswered request resolvable even if every
    /// application clone is dropped off-runtime.
    pending_exact_responses: Arc<PendingExactResponseRegistry>,

    /// SIP_API_DESIGN_2 Phase A: shared session registry so the four
    /// public surfaces can fetch the parsed inbound `Arc<Request>` when
    /// constructing an `IncomingCall`.
    pub(crate) session_registry: Arc<SessionRegistry>,

    /// Synchronous adapter observers for parsed inbound INVITEs. Observers run
    /// before the corresponding public `IncomingCall` event is published so
    /// an adapter can bind context without a cross-channel ordering race.
    inbound_invite_observers: StdMutex<HashMap<u64, InboundInviteObserver>>,
    next_inbound_invite_observer_id: AtomicU64,

    /// Default UAC Digest credentials adopted from the most recent REGISTER
    /// when the application did not configure [`Config::credentials`] /
    /// [`Config::auth`]. This lets a registered client authenticate challenged
    /// in-account requests (INVITE, re-INVITE, BYE, REFER) out of the box —
    /// most PBXes (Asterisk, FreeSWITCH) challenge those as well as REGISTER.
    /// A plain `std::sync::Mutex` because it is only ever locked briefly and
    /// synchronously (no `.await` held); [`config_credentials`](Self::config_credentials)
    /// reads it.
    registered_credentials: std::sync::Mutex<Option<crate::types::Credentials>>,

    /// Cancellation-safe hangup tasks upgrade this weak self-reference before
    /// detaching. The retained task then owns one strong coordinator reference
    /// through dispatch, final-response confirmation, and exact finalization.
    self_weak: OnceLock<Weak<UnifiedCoordinator>>,
}

async fn run_setup_teardown_deadline_scheduler(
    coordinator: Weak<UnifiedCoordinator>,
    scheduler: Arc<SetupTeardownDeadlineScheduler>,
    mut shutdown: tokio::sync::watch::Receiver<bool>,
) {
    'scheduler: loop {
        if *shutdown.borrow() {
            break;
        }

        // Register the notification waiter before reading the queue. This
        // closes the insertion-between-peek-and-wait race without retaining a
        // coordinator reference while the scheduler is idle.
        let changed = scheduler.changed.notified();
        tokio::pin!(changed);
        changed.as_mut().enable();

        match scheduler.next_deadline_if_accepting() {
            None => break,
            Some(Some(deadline)) => {
                #[cfg(test)]
                scheduler.record_runner_waiting_for_test(deadline);
                let sleep = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline));
                tokio::pin!(sleep);
                tokio::select! {
                    _ = &mut changed => {}
                    _ = &mut sleep => {}
                    result = shutdown.changed() => {
                        if result.is_err() || *shutdown.borrow() {
                            break;
                        }
                    }
                }
            }
            Some(None) => {
                tokio::select! {
                    _ = &mut changed => {}
                    result = shutdown.changed() => {
                        if result.is_err() || *shutdown.borrow() {
                            break;
                        }
                    }
                }
            }
        }

        let Some(due) =
            scheduler.take_due_if_accepting(Instant::now(), SETUP_TEARDOWN_DEADLINE_BATCH)
        else {
            break;
        };
        if due.is_empty() {
            continue;
        }
        let Some(coordinator) = coordinator.upgrade() else {
            for _ in due {
                crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
            }
            break;
        };
        let full_batch = due.len() == SETUP_TEARDOWN_DEADLINE_BATCH;
        let mut due = due.into_iter();
        while let Some(deadline) = due.next() {
            if !coordinator.setup_teardown_deadline_is_current(&deadline) {
                crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
                continue;
            }
            let permit = loop {
                let changed = scheduler.changed.notified();
                tokio::pin!(changed);
                changed.as_mut().enable();
                if scheduler.next_deadline_if_accepting().is_none() {
                    crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
                    for _ in due {
                        crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
                    }
                    break 'scheduler;
                }
                tokio::select! {
                    permit = Arc::clone(&scheduler.fire_slots).acquire_owned() => {
                        match permit {
                            Ok(permit) => break permit,
                            Err(_) => {
                                crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
                                for _ in due {
                                    crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
                                }
                                break 'scheduler;
                            }
                        }
                    }
                    _ = &mut changed => {}
                    result = shutdown.changed() => {
                        if result.is_err() || *shutdown.borrow() {
                            crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
                            for _ in due {
                                crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
                            }
                            break 'scheduler;
                        }
                    }
                }
            };
            if !coordinator.dispatch_setup_teardown_deadline(deadline, permit) {
                crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
                for _ in due {
                    crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
                }
                break 'scheduler;
            }
        }
        drop(coordinator);
        if full_batch {
            tokio::task::yield_now().await;
        }
    }

    scheduler.begin_close();

    // Explicit shutdown and an ungraceful last-owner drop both retire every
    // armed record. This keeps watchdog accounting convergent and releases all
    // generation-qualified identifiers without waiting for their deadlines.
    for _ in scheduler.drain_queued() {
        crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
    }
}

async fn run_exact_response_deadline_scheduler(
    coordinator: Weak<UnifiedCoordinator>,
    registry: Arc<PendingExactResponseRegistry>,
    mut shutdown: tokio::sync::watch::Receiver<bool>,
) {
    loop {
        if *shutdown.borrow() {
            break;
        }
        let changed = registry.changed.notified();
        tokio::pin!(changed);
        changed.as_mut().enable();
        match registry.next_deadline_if_accepting() {
            None => break,
            Some(Some(deadline)) => {
                let sleep = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline));
                tokio::pin!(sleep);
                tokio::select! {
                    _ = &mut changed => {}
                    _ = &mut sleep => {}
                    result = shutdown.changed() => {
                        if result.is_err() || *shutdown.borrow() {
                            break;
                        }
                    }
                }
            }
            Some(None) => {
                tokio::select! {
                    _ = &mut changed => {}
                    result = shutdown.changed() => {
                        if result.is_err() || *shutdown.borrow() {
                            break;
                        }
                    }
                }
            }
        }

        let Some(due) =
            registry.take_due_if_accepting(Instant::now(), EXACT_RESPONSE_DEADLINE_BATCH)
        else {
            break;
        };
        if due.is_empty() {
            continue;
        }
        let Some(coordinator) = coordinator.upgrade() else {
            break;
        };
        let full_batch = due.len() == EXACT_RESPONSE_DEADLINE_BATCH;
        run_bounded_exact_response_batch(
            due,
            EXACT_RESPONSE_DEADLINE_CONCURRENCY,
            |transaction| {
                let coordinator = Arc::clone(&coordinator);
                let registry = Arc::clone(&registry);
                async move {
                    let _fire = registry.begin_fire();
                    let Some(obligation) = registry.obligation(&transaction) else {
                        return;
                    };
                    let fallback_status = obligation.fallback_status();
                    let outcome = tokio::time::timeout(
                        EXACT_RESPONSE_SEND_ATTEMPT_TIMEOUT,
                        coordinator
                            .author_pending_exact_response(obligation, fallback_status),
                    )
                    .await;
                    let cause = match outcome {
                        Ok(ManagedExactResponseOutcome::Completed) => return,
                        Ok(ManagedExactResponseOutcome::ZeroWireRetryable) => {
                            ExactResponseRetryCause::ZeroWire
                        }
                        Ok(ManagedExactResponseOutcome::Busy) | Err(_) => {
                            ExactResponseRetryCause::BusyOrTimeout
                        }
                    };
                    let plan = registry.retry_plan(&transaction, cause);
                    if plan.slow_path {
                        tracing::warn!(
                            method = %crate::api::incoming::safe_incoming_method_debug_label(transaction.method()),
                            retry_delay_ms = plan.delay.as_millis(),
                            "Exact response fast retry budget exhausted; retaining the obligation on slow retry"
                        );
                    }
                    registry.reschedule(&transaction, plan.delay);
                }
            },
        )
        .await;
        drop(coordinator);
        if full_batch {
            tokio::task::yield_now().await;
        }
    }
}

async fn run_bounded_exact_response_batch<T, F, Fut>(
    items: Vec<T>,
    concurrency: usize,
    operation: F,
) where
    F: FnMut(T) -> Fut,
    Fut: std::future::Future<Output = ()>,
{
    use futures::StreamExt;

    futures::stream::iter(items)
        .for_each_concurrent(concurrency, operation)
        .await;
}

async fn author_pending_exact_response_with_adapter(
    dialog_adapter: &DialogAdapter,
    obligation: Arc<crate::api::incoming::ExactResponseObligation>,
    status: u16,
) -> ManagedExactResponseOutcome {
    let Ok(claim) = obligation.claim() else {
        return ManagedExactResponseOutcome::Busy;
    };
    let retire_dialog_pending_index = obligation.lifecycle_handle().is_some();
    let transaction = obligation.transaction().clone();
    let Ok(status_code) = rvoip_sip_core::StatusCode::from_u16(status) else {
        claim.release_after_failure();
        return ManagedExactResponseOutcome::ZeroWireRetryable;
    };
    let result = dialog_adapter
        .dialog_api
        .send_status_response_classified(&transaction, status_code, None)
        .await;
    match result {
        Ok(rvoip_sip_dialog::FinalResponseCompletionDisposition::WrittenSuccessTerminal)
        | Ok(rvoip_sip_dialog::FinalResponseCompletionDisposition::WireUnknownErrorTerminal) => {
            if retire_dialog_pending_index {
                let _ = dialog_adapter
                    .dialog_api
                    .retire_terminal_response_pending_index(&transaction);
            }
            claim.complete();
            ManagedExactResponseOutcome::Completed
        }
        Ok(rvoip_sip_dialog::FinalResponseCompletionDisposition::ZeroWireRetryable) => {
            claim.release_after_failure();
            ManagedExactResponseOutcome::ZeroWireRetryable
        }
        Err(error)
            if error.disposition
                == rvoip_sip_dialog::FinalResponseCompletionDisposition::ZeroWireRetryable =>
        {
            tracing::warn!(
                method = %crate::api::incoming::safe_incoming_method_debug_label(transaction.method()),
                status_code = status,
                "Managed exact final response failed before transport write: {}",
                error.source
            );
            claim.release_after_failure();
            ManagedExactResponseOutcome::ZeroWireRetryable
        }
        Err(error) => {
            if retire_dialog_pending_index {
                let _ = dialog_adapter
                    .dialog_api
                    .retire_terminal_response_pending_index(&transaction);
            }
            tracing::warn!(
                method = %crate::api::incoming::safe_incoming_method_debug_label(transaction.method()),
                status_code = status,
                "Managed exact final response became wire-unknown and will not be retried: {}",
                error.source
            );
            claim.complete();
            ManagedExactResponseOutcome::Completed
        }
    }
}

/// Quiesce one exact lifetime, release its lower resources, and remove only
/// the registry/store slot captured by the caller. Every delayed terminal
/// path uses this helper so a reused raw SessionId can never redirect cleanup.
pub(crate) async fn release_exact_local_resources(
    session_store: Arc<SessionStore>,
    helpers: Arc<StateMachineHelpers>,
    dialog_adapter: Arc<DialogAdapter>,
    media_adapter: Arc<MediaAdapter>,
    pending_exact_responses: Option<Arc<PendingExactResponseRegistry>>,
    setup_teardown_deadlines: Option<SetupTeardownDeadlineCancellation>,
    handle: SessionRegistryHandle,
) -> Result<()> {
    if let Some(deadlines) = setup_teardown_deadlines.as_ref() {
        // Fence the exact generation before any asynchronous drain or store
        // cleanup. A racing scheduler either admits before this lock and is
        // cancelled here, or observes the closing generation and rejects it.
        deadlines.begin_lifetime_close(&handle);
    }
    if let Some(pending) = pending_exact_responses.as_ref() {
        // Close admission under the same lock used by registration before
        // looking at the pending set. Once this returns, no request from this
        // exact generation can appear behind terminal cleanup.
        pending.begin_lifetime_close(&handle);
        pending
            .drain_lifetime(&handle, dialog_adapter.as_ref())
            .await?;
    }
    // A racing exact owner may already have completed removal. Treat absence
    // of this generation as idempotent success; never redirect cleanup to a
    // newer lifetime that reused the raw SessionId.
    if session_store
        .get_session_retained_snapshot_exact(&handle)
        .is_err()
    {
        if let Some(pending) = pending_exact_responses.as_ref() {
            pending.finish_lifetime_close(&handle);
        }
        if let Some(deadlines) = setup_teardown_deadlines.as_ref() {
            deadlines.finish_lifetime_close(&handle);
        }
        return Ok(());
    }
    let teardown = match session_store.quiesce_session_exact(&handle).await {
        Ok(teardown) => teardown,
        Err(_)
            if session_store
                .get_session_retained_snapshot_exact(&handle)
                .is_err() =>
        {
            if let Some(pending) = pending_exact_responses.as_ref() {
                pending.finish_lifetime_close(&handle);
            }
            if let Some(deadlines) = setup_teardown_deadlines.as_ref() {
                deadlines.finish_lifetime_close(&handle);
            }
            return Ok(());
        }
        Err(error) => {
            return Err(SessionError::InternalError(format!(
                "exact session quiesce failed (class=lifecycle): {error}"
            )));
        }
    };
    if let TeardownOutcome::Quarantined { reason, .. } = teardown {
        // `quiesce_session_exact` also joins the retained teardown supervisor.
        // A recoverable deadline can therefore remain as sticky diagnostic
        // evidence after the authority has reached Retired. Let exact removal
        // verify the final phase instead of stranding a reclaimable session.
        tracing::warn!(
            session = %handle.session_id(),
            ?reason,
            "exact teardown reported quarantine; attempting final exact reclamation"
        );
    }

    let dialog_result = dialog_adapter.cleanup_session_exact(&handle).await;
    let media_result = media_adapter.cleanup_session_exact(&handle).await;
    helpers.cleanup_session(handle.session_id()).await;
    dialog_result?;
    media_result?;
    let removal = match session_store.remove_quiesced_session_exact(&handle) {
        Ok(()) => Ok(()),
        Err(_)
            if session_store
                .get_session_retained_snapshot_exact(&handle)
                .is_err() =>
        {
            Ok(())
        }
        Err(error) => Err(SessionError::InternalError(format!(
            "exact session removal failed (class=lifecycle): {error}"
        ))),
    };
    if removal.is_ok() {
        if let Some(pending) = pending_exact_responses.as_ref() {
            pending.finish_lifetime_close(&handle);
        }
        if let Some(deadlines) = setup_teardown_deadlines.as_ref() {
            deadlines.finish_lifetime_close(&handle);
        }
    }
    removal
}

/// Retry one exact terminal release after a cooperative scheduling turn.
///
/// Lower dialog/media cleanup is idempotent and the store slot is retained
/// until both complete, so a transient lower-layer failure remains safely
/// retryable without ever targeting a reused raw session identifier.
pub(crate) async fn release_exact_local_resources_with_retry(
    session_store: Arc<SessionStore>,
    helpers: Arc<StateMachineHelpers>,
    dialog_adapter: Arc<DialogAdapter>,
    media_adapter: Arc<MediaAdapter>,
    pending_exact_responses: Option<Arc<PendingExactResponseRegistry>>,
    setup_teardown_deadlines: Option<SetupTeardownDeadlineCancellation>,
    handle: SessionRegistryHandle,
) -> Result<()> {
    let first = release_exact_local_resources(
        Arc::clone(&session_store),
        Arc::clone(&helpers),
        Arc::clone(&dialog_adapter),
        Arc::clone(&media_adapter),
        pending_exact_responses.as_ref().map(Arc::clone),
        setup_teardown_deadlines.clone(),
        handle.clone(),
    )
    .await;
    if first.is_ok() {
        return first;
    }
    tracing::warn!(
        session = %handle.session_id(),
        "exact terminal release failed; retrying the same retained lifetime"
    );
    tokio::task::yield_now().await;
    release_exact_local_resources(
        session_store,
        helpers,
        dialog_adapter,
        media_adapter,
        pending_exact_responses,
        setup_teardown_deadlines,
        handle,
    )
    .await
}

/// Best-effort lower-resource cleanup remaining after authoritative session
/// ownership has already been reclaimed.
pub(crate) struct ForcedLocalSessionCleanup {
    handle: Option<SessionRegistryHandle>,
    helpers: Arc<StateMachineHelpers>,
    dialog_adapter: Arc<DialogAdapter>,
    media_adapter: Arc<MediaAdapter>,
    pending_exact_responses: Arc<PendingExactResponseRegistry>,
    setup_teardown_deadlines: SetupTeardownDeadlineCancellation,
    session_store: Arc<SessionStore>,
}

impl ForcedLocalSessionCleanup {
    /// Finish helper, dialog, and media cleanup without relaying lower errors.
    pub(crate) async fn finish(self) {
        let Some(handle) = self.handle else {
            tracing::debug!("forced local reclaim had no exact session owner");
            return;
        };
        if release_exact_local_resources(
            self.session_store,
            self.helpers,
            self.dialog_adapter,
            self.media_adapter,
            Some(self.pending_exact_responses),
            Some(self.setup_teardown_deadlines),
            handle,
        )
        .await
        .is_err()
        {
            tracing::debug!("forced exact local reclaim reported incomplete cleanup");
        }
    }
}

impl UnifiedCoordinator {
    pub(crate) fn add_inbound_invite_observer(
        &self,
        observer: InboundInviteObserver,
    ) -> Result<u64> {
        let mut observers = self
            .inbound_invite_observers
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if observers.len() >= MAX_INBOUND_INVITE_OBSERVERS {
            return Err(SessionError::ConfigurationError(
                "inbound INVITE observer capacity reached".to_string(),
            ));
        }
        let observer_id = self
            .next_inbound_invite_observer_id
            .fetch_add(1, Ordering::Relaxed);
        observers.insert(observer_id, observer);
        Ok(observer_id)
    }

    pub(crate) fn remove_inbound_invite_observer(&self, observer_id: u64) {
        self.inbound_invite_observers
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .remove(&observer_id);
    }

    #[cfg(test)]
    pub(crate) fn inbound_invite_observer_count(&self) -> usize {
        self.inbound_invite_observers
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .len()
    }

    pub(crate) fn notify_inbound_invite_observers(&self, observation: InboundInviteObservation) {
        let observers = self
            .inbound_invite_observers
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .values()
            .cloned()
            .collect::<Vec<_>>();
        for observer in observers {
            let observation = observation.clone();
            if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                observer(observation);
            }))
            .is_err()
            {
                tracing::warn!("inbound INVITE observer panicked; ignoring observer failure");
            }
        }
    }

    /// SIP_API_DESIGN_2 Phase C — read-only access to
    /// [`Config::local_uri`] for builder surfaces that need to
    /// pre-populate the `From` URI when the caller passes `None`.
    /// Kept inherent-impl so the surface adapter doesn't need access
    /// to the private `config` field.
    pub fn config_local_uri(&self) -> String {
        self.config.local_uri.clone()
    }

    /// The `Contact` URI to advertise on REGISTER for `user`: the explicit
    /// [`Config::contact_uri`] when set, otherwise the actual bound/advertised
    /// transport address as `sip:{user}@{host}:{port}`.
    ///
    /// A `Contact`'s purpose is to be the reachable transport address the
    /// registrar routes inbound calls to, so this deliberately uses the bound
    /// address — never the port-less AOR ([`Config::local_uri`]), which would
    /// misroute incoming calls to the default SIP port.
    pub fn config_contact_uri(&self, user: &str) -> String {
        if let Some(contact) = &self.config.contact_uri {
            return contact.clone();
        }
        let host = self
            .config
            .sip_advertised_addr
            .unwrap_or(self.config.bind_addr);
        let scheme = if self.config.local_uri.starts_with("sips:") {
            "sips"
        } else {
            "sip"
        };
        format!("{scheme}:{user}@{host}")
    }

    /// SIP_API_DESIGN_2 §7.1 — read-only access to
    /// [`Config::pai_uri`] for outbound builders that need to resolve
    /// the per-call `P-Asserted-Identity` against
    /// [`PaiOverride::Default`](crate::api::send::PaiOverride::Default).
    pub fn config_pai_uri(&self) -> Option<String> {
        self.config.pai_uri.clone()
    }

    /// Read-only access to the peer-level default Digest credentials so
    /// outbound builders can fall back when the application did not stage
    /// per-call credentials via `with_credentials(..)`.
    ///
    /// Precedence: explicit [`Config::credentials`] first, then credentials
    /// adopted from a prior REGISTER (see `registered_credentials`). The latter
    /// makes a registered client able to place calls without separately
    /// populating `Config.credentials`.
    pub fn config_credentials(&self) -> Option<crate::types::Credentials> {
        self.config.credentials.clone().or_else(|| {
            self.registered_credentials
                .lock()
                .ok()
                .and_then(|slot| slot.clone())
        })
    }

    /// Read-only access to [`Config::auth`] so outbound builders can fall
    /// back to peer-level full-auth configuration.
    pub fn config_auth(&self) -> Option<crate::auth::SipClientAuth> {
        self.config
            .auth
            .clone()
            .or_else(|| self.config.credentials.clone().map(Into::into))
    }

    /// Feature-gated retained-object counts for perf leak investigations.
    ///
    /// This is intentionally not a stable application API. It exists so
    /// release-gate tests can prove that completed call churn is not retaining
    /// per-call state.
    #[cfg(feature = "perf-tests")]
    #[doc(hidden)]
    pub async fn perf_diagnostic_snapshot(&self) -> serde_json::Value {
        let session_stats = self.helpers.state_machine.store.get_stats().await;
        let helper_counts = self.helpers.perf_diagnostic_counts().await;
        let registry_sessions = self.session_registry.session_count().await;
        let registry_retention = self.session_registry.perf_retention_counts();
        let setup_teardown = self.setup_teardown_scheduler.perf_diagnostic_counts();
        let exact_responses = self.pending_exact_responses.perf_diagnostic_counts();
        let dialog_adapter_counts = self.dialog_adapter.perf_diagnostic_counts();
        let inbound_invite_observers = self
            .inbound_invite_observers
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .len();
        let cleanup = crate::cleanup_diag::snapshot();
        let admission = crate::admission_diag::snapshot();
        let dialog_diag = rvoip_sip_dialog::diagnostics::snapshot();
        let dialog_core = self.dialog_adapter.dialog_api.dialog_manager().core();
        let transaction_manager = dialog_core.transaction_manager();
        let transaction_counts = transaction_manager.retention_counts();
        let transaction_breakdown = transaction_manager.retention_breakdown();
        let dialog_counts = dialog_core.retention_counts();
        let dialog_breakdown = dialog_core.retention_breakdown();
        #[cfg(feature = "perf-infra-memory-diagnostics")]
        let memory_diagnostics = rvoip_infra_common::memory_diagnostics::snapshot();
        #[cfg(not(feature = "perf-infra-memory-diagnostics"))]
        let memory_diagnostics = serde_json::json!({
            "enabled": false,
            "compiled": false,
            "feature": "perf-infra-memory-diagnostics",
        });
        #[cfg(feature = "perf-infra-memory-diagnostics")]
        let allocator_diagnostics = rvoip_infra_common::memory_diagnostics::allocator_snapshot();
        #[cfg(not(feature = "perf-infra-memory-diagnostics"))]
        let allocator_diagnostics = serde_json::json!({
            "enabled": false,
            "compiled": false,
            "feature": "perf-infra-memory-diagnostics",
        });

        serde_json::json!({
            "config": {
                "sip_transaction_command_channel_capacity": self
                    .config
                    .sip_transaction_command_channel_capacity
                    .unwrap_or(Config::DEFAULT_SIP_TRANSACTION_COMMAND_CHANNEL_CAPACITY),
                "server_call_capacity": self.config.server_call_capacity,
                "server_retained_lifecycle_capacity": self.config.server_retained_lifecycle_capacity,
                "server_call_admission_limit": self.config.server_call_admission_limit,
                "server_call_admission_soft_limit": self.config.server_call_admission_soft_limit,
                "server_call_admission_pacing_delay_ms": self.config.server_call_admission_pacing_delay_ms,
                "server_overload_retry_after_secs": self.config.server_overload_retry_after_secs,
            },
            "session_store": {
                "total": session_stats.total,
                "idle": session_stats.idle,
                "initiating": session_stats.initiating,
                "ringing": session_stats.ringing,
                "active": session_stats.active,
                "on_hold": session_stats.on_hold,
                "terminating": session_stats.terminating,
                "terminated": session_stats.terminated,
                "failed": session_stats.failed,
                "lifecycle": self.helpers.state_machine.store.perf_lifecycle_counts(),
            },
            "session_registry": {
                "sessions": registry_sessions,
                "entries": registry_retention["entries"].clone(),
                "dialog_mappings": registry_retention["dialog_mappings"].clone(),
                "media_mappings": registry_retention["media_mappings"].clone(),
                "lock_poisoned": registry_retention["lock_poisoned"].clone(),
                "lifecycle": self.session_registry.perf_lifecycle_counts(),
            },
            "lifecycle": self.lifecycle.perf_diagnostic_counts(),
            "app_event_publisher": self.app_event_publisher.perf_diagnostic_counts(),
            "global_event_bus": self.global_coordinator.event_bus_diagnostic_snapshot(),
            "coordinator_observers": {
                "inbound_invite": inbound_invite_observers,
                "session_control_claimed": self.session_control_claimed.load(Ordering::Acquire),
            },
            "state_machine_helpers": helper_counts,
            "exact_response_supervisor": exact_responses,
            "retained_tasks": {
                "coordinator_runtime": setup_teardown["retained_tasks"].clone(),
                "coordinator_runtime_panicked": setup_teardown["retained_task_panicked"].clone(),
                "registration_refresh": dialog_adapter_counts["registration_refresh_retained_tasks"].clone(),
            },
            "transaction_manager": {
                "client_transactions": transaction_counts.client_transactions,
                "server_transactions": transaction_counts.server_transactions,
                "total": transaction_counts.active_transactions_total,
                "terminated_transactions": transaction_counts.terminated_transactions,
                "server_invite_dialog_index": transaction_counts.server_invite_dialog_index,
                "server_invite_dialog_keys_by_tx": transaction_counts.server_invite_dialog_keys_by_tx,
                "invite_2xx_response_cache": transaction_counts.invite_2xx_response_cache,
                "invite_2xx_response_due_queue": transaction_counts.invite_2xx_response_due_queue,
                "transaction_destinations": transaction_counts.transaction_destinations,
                "orphaned_transaction_destinations": transaction_manager.orphaned_transaction_destination_count(),
                "retired_client_transactions": transaction_manager.retired_client_transaction_count(),
                "event_subscribers": transaction_counts.event_subscribers,
                "subscriber_to_transactions": transaction_counts.subscriber_to_transactions,
                "transaction_to_subscribers": transaction_counts.transaction_to_subscribers,
                "pending_inbound_bytes": transaction_counts.pending_inbound_bytes,
                "pending_inbound_timing": transaction_counts.pending_inbound_timing,
                "breakdown": transaction_breakdown,
            },
            "dialog_manager": dialog_manager_retention_snapshot(dialog_counts),
            "dialog_manager_storage": dialog_breakdown,
            "dialog_adapter": dialog_adapter_counts,
            "media_adapter": self.media_adapter.perf_diagnostic_counts(),
            "memory_diagnostics": memory_diagnostics,
            "allocator_diagnostics": allocator_diagnostics,
            "server_call_admission": admission,
            "sip_dialog_diagnostics": {
                "transaction_runner": {
                    "started": dialog_diag.transaction_runner_started,
                    "exited": dialog_diag.transaction_runner_exited,
                    "active": dialog_diag.transaction_runner_active,
                    "active_max": dialog_diag.transaction_runner_active_max,
                    "destroy_wake_sent": dialog_diag.transaction_runner_destroy_wake_sent,
                    "destroy_wake_failed": dialog_diag.transaction_runner_destroy_wake_failed,
                },
                "transaction_cleanup": {
                    "enqueued": dialog_diag.termination_cleanup_enqueued,
                    "queue_full": dialog_diag.termination_cleanup_queue_full,
                    "in_flight": dialog_diag.termination_cleanup_in_flight,
                    "max_in_flight": dialog_diag.termination_cleanup_max_in_flight,
                    "removed": dialog_diag.termination_cleanup_removed,
                    "poll_attempts": dialog_diag.termination_cleanup_poll_attempts,
                },
                "invite_2xx_cache": {
                    "insert": dialog_diag.invite_2xx_cache_insert,
                    "expired": dialog_diag.invite_2xx_cache_expired,
                    "ack_removed": dialog_diag.invite_2xx_ack_removed,
                    "maintenance_cache_len_max": dialog_diag.invite_2xx_maintenance_cache_len_max,
                    "maintenance_due_queue_len_max": dialog_diag.invite_2xx_maintenance_due_queue_len_max,
                    "maintenance_due": dialog_diag.invite_2xx_maintenance_due,
                    "maintenance_expired": dialog_diag.invite_2xx_maintenance_expired,
                    "maintenance_capped_ticks": dialog_diag.invite_2xx_maintenance_capped_ticks,
                },
                "bye_tombstone": {
                    "hit": dialog_diag.duplicate_bye_tombstone_hit,
                    "miss": dialog_diag.duplicate_bye_tombstone_miss,
                    "table_size_max": dialog_diag.bye_tombstone_table_size_max,
                },
            },
            "cleanup": {
                "enabled": cleanup.enabled,
                "active_total": cleanup.active_total,
                "setup_teardown_watchdog": {
                    "armed": cleanup.setup_teardown_watchdog_armed,
                    "disarmed": cleanup.setup_teardown_watchdog_disarmed,
                    "fired": cleanup.setup_teardown_watchdog_fired,
                    "transition_failed": cleanup.setup_teardown_watchdog_transition_failed,
                    "release_completed": cleanup.setup_teardown_watchdog_release_completed,
                    "release_failed": cleanup.setup_teardown_watchdog_release_failed,
                    "pending_deadlines": setup_teardown["pending_deadlines"].clone(),
                    "fire_in_flight": setup_teardown["fire_in_flight"].clone(),
                    "retained_tasks": setup_teardown["retained_tasks"].clone(),
                    "retained_task_panicked": setup_teardown["retained_task_panicked"].clone(),
                    "accepting": setup_teardown["accepting"].clone(),
                    "fire_concurrency_limit": setup_teardown["fire_concurrency_limit"].clone(),
                    "deadline_record_bytes": setup_teardown["deadline_record_bytes"].clone(),
                    "pending_by_owner": setup_teardown["pending_by_owner"].clone(),
                },
                "session_event_dispatch": {
                    "saturated": cleanup.session_event_dispatch_saturated,
                    "dropped": cleanup.session_event_dispatch_dropped,
                    "closed": cleanup.session_event_dispatch_closed,
                    "publication_failed": cleanup.session_event_publication_failed,
                    "publication_timed_out": cleanup.session_event_publication_timed_out,
                    "shutdown_timeouts": cleanup.session_event_dispatch_shutdown_timeouts,
                    "aborted_workers": cleanup.session_event_dispatch_aborted_workers,
                },
            },
        })
    }

    /// SIP_API_DESIGN_2 Phase C — internal accessor to the
    /// [`DialogAdapter`] so send/respond builders can route their
    /// dispatch through the same translation layer used by the legacy
    /// flat methods. Crate-private so the builders are the only
    /// external consumers.
    pub(crate) fn dialog_adapter(&self) -> &Arc<DialogAdapter> {
        &self.dialog_adapter
    }

    /// Send out-of-dialog MESSAGE and retry when a configured UAC auth option
    /// can answer a 401/407 challenge.
    pub(crate) async fn send_message_oob_with_optional_auth(
        &self,
        opts: rvoip_sip_dialog::api::unified::MessageRequestOptions,
        auth: Option<SipClientAuth>,
    ) -> Result<Response> {
        self.send_standalone_oob_with_optional_auth(StandaloneRequestOptions::Message(opts), auth)
            .await
    }

    /// Send out-of-dialog OPTIONS and retry when a configured UAC auth option
    /// can answer a 401/407 challenge.
    pub(crate) async fn send_options_oob_with_optional_auth(
        &self,
        opts: rvoip_sip_dialog::api::unified::OptionsRequestOptions,
        auth: Option<SipClientAuth>,
    ) -> Result<Response> {
        self.send_standalone_oob_with_optional_auth(StandaloneRequestOptions::Options(opts), auth)
            .await
    }

    /// Send out-of-dialog SUBSCRIBE and retry when a configured UAC auth option
    /// can answer a 401/407 challenge.
    pub(crate) async fn send_subscribe_oob_with_optional_auth(
        &self,
        target: &str,
        opts: rvoip_sip_dialog::api::unified::SubscribeRequestOptions,
        auth: Option<SipClientAuth>,
    ) -> Result<Response> {
        self.send_standalone_oob_with_optional_auth(
            StandaloneRequestOptions::Subscribe {
                target: target.to_string(),
                options: opts,
            },
            auth,
        )
        .await
    }

    /// Send a standalone request and perform the bounded 401/407 retry flow
    /// from one immutable request snapshot.
    async fn send_standalone_oob_with_optional_auth(
        &self,
        request: StandaloneRequestOptions,
        auth: Option<SipClientAuth>,
    ) -> Result<Response> {
        let response = self
            .dialog_adapter
            .send_standalone_request(request.clone(), None)
            .await?;
        let method = request.method();
        let request_uri = request.request_uri().to_string();
        let body = request.body();
        let Some(retry) = self.build_oob_auth_retry_header(
            method.clone(),
            &response,
            &request_uri,
            body,
            auth.as_ref(),
        )?
        else {
            return Ok(response);
        };

        let retry_request = request.clone().with_request_identity(
            retry.cseq,
            retry.call_id.clone(),
            retry.from_tag.clone(),
        );
        let retry_response = self
            .dialog_adapter
            .send_standalone_request(
                retry_request,
                Some((&retry.header_name, retry.header_value.clone())),
            )
            .await?;
        if retry_response.status_code() != 401 && retry_response.status_code() != 407 {
            return Ok(retry_response);
        }

        let Some(stale_retry) = self.build_oob_auth_retry_header(
            method.clone(),
            &retry_response,
            &request_uri,
            body,
            auth.as_ref(),
        )?
        else {
            ensure_retry_not_challenged(method, &retry_response)?;
            return Ok(retry_response);
        };

        if !stale_retry.stale || stale_retry.nonce == retry.nonce {
            ensure_retry_not_challenged(method, &retry_response)?;
            return Ok(retry_response);
        }

        let stale_request = request.with_request_identity(
            stale_retry.cseq,
            stale_retry.call_id.clone(),
            stale_retry.from_tag.clone(),
        );
        let stale_response = self
            .dialog_adapter
            .send_standalone_request(
                stale_request,
                Some((&stale_retry.header_name, stale_retry.header_value)),
            )
            .await?;
        ensure_retry_not_challenged(method, &stale_response)?;
        Ok(stale_response)
    }

    fn build_oob_auth_retry_header(
        &self,
        method: Method,
        response: &Response,
        request_uri: &str,
        body: Option<&[u8]>,
        auth: Option<&SipClientAuth>,
    ) -> Result<Option<OobAuthRetry>> {
        let status = response.status_code();
        if status != 401 && status != 407 {
            return Ok(None);
        }
        let Some(auth) = auth else {
            return Ok(None);
        };

        let (challenge_header_name, auth_header_name) = if status == 407 {
            (HeaderName::ProxyAuthenticate, "Proxy-Authorization")
        } else {
            (HeaderName::WwwAuthenticate, "Authorization")
        };
        let challenge_values = response
            .raw_headers(&challenge_header_name)
            .into_iter()
            .filter_map(|bytes| String::from_utf8(bytes).ok())
            .collect::<Vec<_>>();
        if challenge_values.is_empty() {
            return Err(SessionError::AuthError(format!(
                "{} challenge response missing {}",
                method,
                challenge_header_name.as_str()
            )));
        }
        let challenge_value = challenge_values.join(", ");
        if challenge_value.trim().is_empty() {
            return Err(SessionError::AuthError(format!(
                "{} challenge response missing {}",
                method,
                challenge_header_name.as_str()
            )));
        }
        let transport = self
            .dialog_adapter
            .outbound_transport_context_for_response(response, request_uri);
        let selected = auth
            .authorization_for_challenge_with_transport_context(
                &challenge_value,
                method.as_str(),
                request_uri,
                1,
                body,
                &transport,
            )
            .map_err(|error| {
                crate::errors::redacted_outbound_auth_error(
                    crate::errors::OutboundAuthOperation::Request,
                    error,
                )
            })?;
        let nonce = selected
            .digest_challenge
            .as_ref()
            .map(|challenge| challenge.nonce.clone())
            .unwrap_or_default();
        let cseq = response
            .cseq()
            .map(|cseq| cseq.sequence().saturating_add(1))
            .unwrap_or(2);
        let call_id = response.call_id().map(|call_id| call_id.value());
        let from_tag = response
            .from()
            .and_then(|from| from.tag().map(str::to_string));
        Ok(Some(OobAuthRetry {
            header_name: auth_header_name.to_string(),
            header_value: selected.value,
            cseq,
            call_id,
            from_tag,
            nonce,
            stale: selected.stale,
        }))
    }

    // ──────────────────────────────────────────────────────────────────
    // SIP_API_DESIGN_2 Phase C — builder entry points.
    //
    // One verb-named entry per outbound method. Each returns a typed
    // builder implementing
    // [`SipRequestOptions`](crate::api::headers::SipRequestOptions),
    // so applications get a uniform `with_header / with_credentials /
    // with_headers_from / strip_header / .send()` shape.
    // ──────────────────────────────────────────────────────────────────

    /// Begin building an outbound INVITE.
    pub fn invite(
        self: &Arc<Self>,
        from: Option<String>,
        to: impl Into<String>,
    ) -> crate::api::send::OutboundCallBuilder {
        crate::api::send::OutboundCallBuilder::new(self.clone(), from, to)
    }

    /// Begin building an outbound BYE.
    pub fn bye(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
    ) -> crate::api::send::ByeBuilder {
        let lifecycle_handle = self.helpers.state_machine.store.lifecycle_handle(session);
        crate::api::send::ByeBuilder::new_captured(self.clone(), session.clone(), lifecycle_handle)
    }

    /// Begin building an outbound CANCEL.
    pub fn cancel(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
    ) -> crate::api::send::CancelBuilder {
        let lifecycle_handle = self.helpers.state_machine.store.lifecycle_handle(session);
        crate::api::send::CancelBuilder::new_captured(
            self.clone(),
            session.clone(),
            lifecycle_handle,
        )
    }

    /// Begin building an outbound REFER.
    pub fn refer(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
        refer_to: impl Into<String>,
    ) -> crate::api::send::ReferBuilder {
        let lifecycle_handle = self.helpers.state_machine.store.lifecycle_handle(session);
        crate::api::send::ReferBuilder::new_captured(
            self.clone(),
            session.clone(),
            refer_to,
            lifecycle_handle,
        )
    }

    /// Begin building an outbound NOTIFY.
    pub fn notify(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
        event_package: impl Into<String>,
    ) -> crate::api::send::NotifyBuilder {
        let lifecycle_handle = self.helpers.state_machine.store.lifecycle_handle(session);
        crate::api::send::NotifyBuilder::new_captured(
            self.clone(),
            session.clone(),
            event_package,
            lifecycle_handle,
        )
    }

    /// Begin building an outbound INFO.
    pub fn info(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
        content_type: impl Into<String>,
    ) -> crate::api::send::InfoBuilder {
        let lifecycle_handle = self.helpers.state_machine.store.lifecycle_handle(session);
        crate::api::send::InfoBuilder::new_captured(
            self.clone(),
            session.clone(),
            content_type,
            lifecycle_handle,
        )
    }

    /// Begin building an outbound UPDATE.
    pub fn update(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
    ) -> crate::api::send::UpdateBuilder {
        let lifecycle_handle = self.helpers.state_machine.store.lifecycle_handle(session);
        crate::api::send::UpdateBuilder::new_captured(
            self.clone(),
            session.clone(),
            lifecycle_handle,
        )
    }

    /// Begin building an outbound re-INVITE.
    pub fn reinvite(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
    ) -> crate::api::send::ReInviteBuilder {
        let lifecycle_handle = self.helpers.state_machine.store.lifecycle_handle(session);
        crate::api::send::ReInviteBuilder::new_captured(
            self.clone(),
            session.clone(),
            lifecycle_handle,
        )
    }

    /// Begin building an out-of-dialog SUBSCRIBE.
    ///
    /// Canonical SUBSCRIBE-method verb-builder per SIP_API_DESIGN_2.md §3.3.
    /// The legacy state-machine-event observer that previously owned the
    /// bare name was renamed to [`on_session_events`](Self::on_session_events).
    pub fn subscribe(
        self: &Arc<Self>,
        target: impl Into<String>,
        event_package: impl Into<String>,
    ) -> crate::api::send::SubscribeBuilder {
        crate::api::send::SubscribeBuilder::new(self.clone(), target, event_package)
    }

    /// Begin building an out-of-dialog MESSAGE.
    pub fn message(
        self: &Arc<Self>,
        target: impl Into<String>,
    ) -> crate::api::send::MessageBuilder {
        crate::api::send::MessageBuilder::new(self.clone(), target)
    }

    /// Begin building an out-of-dialog OPTIONS.
    pub fn options(
        self: &Arc<Self>,
        target: impl Into<String>,
    ) -> crate::api::send::OptionsBuilder {
        crate::api::send::OptionsBuilder::new(self.clone(), target)
    }

    /// Begin building an accept response for an inbound INVITE.
    pub fn accept(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
    ) -> crate::api::respond::AcceptBuilder {
        crate::api::respond::AcceptBuilder::new(self.clone(), session.clone())
    }

    /// Begin building a reject response for an inbound INVITE.
    pub fn reject(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
    ) -> crate::api::respond::RejectBuilder {
        crate::api::respond::RejectBuilder::new(self.clone(), session.clone())
    }

    /// Begin building a redirect response for an inbound INVITE.
    pub fn redirect(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
    ) -> crate::api::respond::RedirectBuilder {
        crate::api::respond::RedirectBuilder::new(self.clone(), session.clone())
    }

    /// Begin building a UAS-side auth challenge (401 / 407).
    pub fn challenge(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
        scheme: crate::api::respond::AuthScheme,
    ) -> crate::api::respond::AuthChallengeBuilder {
        crate::api::respond::AuthChallengeBuilder::new(
            self.clone(),
            session.clone(),
            rvoip_sip_core::types::Method::Invite,
            scheme,
        )
    }

    /// Begin building an outbound REGISTER.
    ///
    /// Canonical REGISTER verb-builder per SIP_API_DESIGN_2.md §3.3. The
    /// legacy 6-arg `register(uri, from, contact, user, pw, exp)` method
    /// was deleted in Phase 12; use this builder entry with
    /// `.with_expires(...)`, `.with_extra_headers(...)`, etc. before
    /// terminating with `.send()`.
    pub fn register(
        self: &Arc<Self>,
        registrar: impl Into<String>,
        user: impl Into<String>,
        password: impl Into<String>,
    ) -> crate::api::send::RegisterBuilder {
        crate::api::send::RegisterBuilder::new(self.clone(), registrar, user, password)
    }

    /// Begin building a generic UAS response (3xx / 4xx / 5xx / 6xx)
    /// for the given session.
    pub fn respond(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
        status: u16,
    ) -> crate::errors::Result<crate::api::respond::GenericResponseBuilder> {
        // The coordinator-level `respond` entry is reachable from session
        // state where the inbound INVITE is the only outstanding UAS
        // request; pass `Method::Invite` so the policy classifier
        // matches the UAS context.
        crate::api::respond::GenericResponseBuilder::new(
            self.clone(),
            session.clone(),
            rvoip_sip_core::types::Method::Invite,
            status,
        )
    }

    /// Begin building a reliable 1xx provisional response.
    pub fn send_provisional(
        self: &Arc<Self>,
        session: &crate::api::handle::CallId,
        code: u16,
    ) -> crate::api::respond::ProvisionalBuilder {
        crate::api::respond::ProvisionalBuilder::new(self.clone(), session.clone(), code)
    }
}

#[derive(Clone)]
struct OobAuthRetry {
    header_name: String,
    header_value: String,
    cseq: u32,
    call_id: Option<String>,
    from_tag: Option<String>,
    nonce: String,
    stale: bool,
}

impl std::fmt::Debug for OobAuthRetry {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("OobAuthRetry")
            .field("header_configured", &!self.header_name.is_empty())
            .field("header_value_configured", &!self.header_value.is_empty())
            .field("cseq", &self.cseq)
            .field("call_id_configured", &self.call_id.is_some())
            .field("from_tag_configured", &self.from_tag.is_some())
            .field("nonce_configured", &!self.nonce.is_empty())
            .field("stale", &self.stale)
            .finish()
    }
}

fn ensure_retry_not_challenged(method: Method, response: &Response) -> Result<()> {
    let status = response.status_code();
    if status == 401 || status == 407 {
        return Err(SessionError::RequestAuthRetryExhausted { method });
    }
    Ok(())
}

impl UnifiedCoordinator {
    /// Create and start a new coordinator.
    ///
    /// This validates [`Config`], initializes dialog and media adapters,
    /// starts the central event handler, and returns a shared coordinator
    /// handle. Background tasks are stopped by calling [`shutdown`](Self::shutdown)
    /// or by dropping all coordinator owners.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example() -> rvoip_sip::Result<()> {
    /// use rvoip_sip::{Config, UnifiedCoordinator};
    ///
    /// let coordinator = UnifiedCoordinator::new(Config::local("alice", 5060)).await?;
    /// coordinator.shutdown_gracefully(None).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn new(config: Config) -> Result<Arc<Self>> {
        Self::new_with_listener_auth_and_runtime(
            config,
            crate::auth::SipListenerAuthPolicy::disabled(),
            SipRuntimeConfig::default(),
        )
        .await
    }

    /// Create a coordinator with explicit SIP/RTP NAT behavior.
    pub async fn new_with_nat(config: Config, nat: SipNatConfig) -> Result<Arc<Self>> {
        Self::new_with_listener_auth_and_runtime(
            config,
            crate::auth::SipListenerAuthPolicy::disabled(),
            SipRuntimeConfig::default().with_nat(nat),
        )
        .await
    }

    /// Create a coordinator with source-compatible construction-time options.
    pub async fn new_with_runtime(config: Config, runtime: SipRuntimeConfig) -> Result<Arc<Self>> {
        Self::new_with_listener_auth_and_runtime(
            config,
            crate::auth::SipListenerAuthPolicy::disabled(),
            runtime,
        )
        .await
    }

    /// Create a coordinator with listener authentication installed before the
    /// transaction receive loop starts.
    pub async fn new_with_listener_auth(
        config: Config,
        listener_auth_policy: crate::auth::SipListenerAuthPolicy,
    ) -> Result<Arc<Self>> {
        Self::new_with_listener_auth_and_runtime(
            config,
            listener_auth_policy,
            SipRuntimeConfig::default(),
        )
        .await
    }

    /// Create a coordinator with listener authentication and explicit NAT
    /// behavior installed before any signaling or media task starts.
    pub async fn new_with_listener_auth_and_nat(
        config: Config,
        listener_auth_policy: crate::auth::SipListenerAuthPolicy,
        nat: SipNatConfig,
    ) -> Result<Arc<Self>> {
        Self::new_with_listener_auth_and_runtime(
            config,
            listener_auth_policy,
            SipRuntimeConfig::default().with_nat(nat),
        )
        .await
    }

    /// Create a coordinator with listener authentication and source-compatible
    /// construction-time options installed before any signaling or media task
    /// starts.
    pub async fn new_with_listener_auth_and_runtime(
        mut config: Config,
        listener_auth_policy: crate::auth::SipListenerAuthPolicy,
        runtime: SipRuntimeConfig,
    ) -> Result<Arc<Self>> {
        let nat = runtime.nat();
        let sdes_base64_mode = runtime.sdes_base64_mode();
        // Treat an explicitly absent policy as the safe default too. Verbatim
        // tracing requires `trace_passthrough_for_development` or an explicit
        // `PassthroughRedactor`; absence is never a credential-leaking mode.
        if config.trace_redaction.is_none() {
            config.trace_redaction = Some(crate::api::trace_redactor::default_trace_redactor());
        }
        if config
            .trace_redaction
            .as_ref()
            .is_some_and(|redactor| redactor.allows_verbatim_trace())
        {
            // A verbatim trait policy is an explicit development/operator
            // decision. Mirror it into the transport policy so the lower
            // defense-in-depth sanitizer does not silently re-redact the trace.
            config.sip_trace = config.sip_trace.verbatim_for_development();
        }
        config.validate()?;
        nat.validate()?;
        listener_auth_policy.validate()?;
        if listener_auth_policy.has_verified_mtls_peers()
            && config.tls_server_client_auth.mode
                == rvoip_sip_transport::transport::tls::TlsClientAuthMode::Disabled
        {
            return Err(SessionError::ConfigError(
                "SIP listener mTLS fingerprint mappings require transport-level TLS client-certificate verification"
                    .to_string(),
            ));
        }
        rvoip_sip_transport::diagnostics::set_enabled(config.sip_udp_diagnostics);
        rvoip_sip_dialog::diagnostics::set_enabled(config.sip_udp_diagnostics);
        rvoip_sip_dialog::diagnostics::set_transaction_timing_enabled(
            config.sip_transaction_timing_diagnostics,
        );
        rvoip_sip_dialog::diagnostics::set_dialog_timing_enabled(
            config.sip_dialog_timing_diagnostics,
        );
        rvoip_media_core::diagnostics::set_enabled(config.media_setup_diagnostics);
        crate::cleanup_diag::set_enabled(config.cleanup_diagnostics);
        crate::cleanup_diag::set_event_logs_enabled(config.cleanup_diagnostic_events);
        #[cfg(feature = "perf-tests")]
        crate::admission_diag::set_enabled(
            config.cleanup_diagnostics
                || config.sip_transaction_timing_diagnostics
                || config.sip_dialog_timing_diagnostics,
        );
        crate::adapters::media_adapter::set_sdp_diagnostics(
            config.srtp_diagnostics,
            config.media_sdp_diagnostics,
        );
        rvoip_rtp_core::transport::set_udp_diagnostics(
            config.srtp_diagnostics,
            config.rtp_diagnostics,
        );

        let global_event_config = rvoip_infra_common::events::EventCoordinatorConfig::monolithic()
            .with_channel_capacity(config.global_event_channel_capacity);
        let global_coordinator = Arc::new(
            rvoip_infra_common::events::GlobalEventCoordinator::new(global_event_config)
                .await
                .map_err(|e| {
                    SessionError::InternalError(format!(
                        "Failed to create global event coordinator: {}",
                        e
                    ))
                })?,
        );
        // Register and acknowledge the stable causal ingress before transport
        // construction can bind a socket or accept a fast loopback packet.
        // The existing sharded session router is installed into this slot
        // later in the same constructor; early publishers wait without
        // falling through to the observational bus.
        let causal_dialog_ingress = CausalDialogToSessionIngress::new();
        global_coordinator
            .register_handler("dialog_to_session", causal_dialog_ingress.clone())
            .await
            .map_err(|error| {
                SessionError::InternalError(format!(
                    "Failed to register causal dialog ingress before transport startup: {error}"
                ))
            })?;
        let mut causal_ingress_guard =
            CausalIngressConstructionGuard::new(causal_dialog_ingress.clone());
        // Exact application authority uses one claimed, coordinator-owned
        // channel. It is deliberately independent of bounded observational
        // dispatch so a full/stalled event bus cannot drop a lifecycle handle.
        // The channel is closed and drained with this coordinator/peer.
        let (session_control_tx, session_control_rx) = mpsc::unbounded_channel();
        let session_control_claimed = Arc::new(AtomicBool::new(false));

        // Create core components
        let authority = match (
            config.server_call_capacity,
            config.server_retained_lifecycle_capacity,
        ) {
            (None, None) => SessionLeaseAuthority::new(),
            (Some(active_capacity), None) => SessionLeaseAuthority::with_capacity(active_capacity),
            (Some(active_capacity), Some(retained_capacity)) => {
                SessionLeaseAuthority::with_capacities(active_capacity, retained_capacity)
                    .map_err(|error| SessionError::ConfigError(error.to_string()))?
            }
            (None, Some(_)) => {
                return Err(SessionError::ConfigError(
                    "server_retained_lifecycle_capacity requires server_call_capacity".to_string(),
                ));
            }
        };
        let registry = Arc::new(SessionRegistry::with_authority(Arc::clone(&authority)));
        let store = Arc::new(SessionStore::with_lifecycle(
            authority,
            Arc::clone(&registry),
            config.server_call_capacity,
        ));

        let sip_trace_owner_id = config
            .sip_trace
            .enabled
            .then(|| format!("sip-trace-{}", uuid::Uuid::new_v4()));

        // Create adapters
        let dialog_api = Self::create_dialog_api(
            &config,
            global_coordinator.clone(),
            sip_trace_owner_id.clone(),
            listener_auth_policy,
        )
        .await?;

        // E4: parse the outbound proxy URI once up-front so a malformed
        // config fails loudly at coordinator boot, not per-call.
        let outbound_proxy_uri = if let Some(s) = config.outbound_proxy_uri.as_ref() {
            use std::str::FromStr;
            match rvoip_sip_core::types::uri::Uri::from_str(s) {
                Ok(u) => Some(u),
                Err(e) => {
                    return Err(crate::errors::SessionError::ConfigurationError(format!(
                        "Config.outbound_proxy_uri ({}) is not a valid SIP URI: {}",
                        s, e
                    )));
                }
            }
        } else {
            None
        };

        // Build RFC 5626 outbound Contact params from config. Require both
        // the outbound flag and a stable instance URN unless validation has
        // already made that mode mandatory.
        let outbound_contact_params = if config.sip_outbound_enabled
            || matches!(
                config.sip_contact_mode,
                SipContactMode::RegisteredFlowRfc5626
            ) {
            if let Some(instance) = config.sip_instance.as_ref() {
                Some(rvoip_sip_core::types::outbound::OutboundContactParams {
                    instance_urn: instance.clone(),
                    reg_id: 1,
                })
            } else {
                tracing::warn!(
                    "Config.sip_outbound_enabled is true but sip_instance is None; \
                     falling back to pre-5626 REGISTER Contact. Provide a stable \
                     urn:uuid:<uuid> in Config.sip_instance to enable RFC 5626."
                );
                None
            }
        } else {
            None
        };

        let symmetric_flow_params = if matches!(
            config.sip_contact_mode,
            SipContactMode::RegisteredFlowSymmetric
        ) {
            Some(rvoip_sip_core::types::outbound::OutboundContactParams {
                instance_urn: config
                    .sip_instance
                    .clone()
                    .unwrap_or_else(|| format!("symmetric:{}", config.local_uri)),
                reg_id: 1,
            })
        } else {
            None
        };

        // Thread the registered-flow keep-alive interval into the
        // DialogManager so REGISTER 2xx responses can spawn CRLFCRLF
        // ping tasks. RFC 5626 mode starts after outbound Contact echo;
        // symmetric mode starts after a successful REGISTER.
        if (outbound_contact_params.is_some() || symmetric_flow_params.is_some())
            && config.outbound_keepalive_interval_secs > 0
        {
            dialog_api
                .dialog_manager()
                .core()
                .set_outbound_keepalive_interval(Some(std::time::Duration::from_secs(
                    config.outbound_keepalive_interval_secs,
                )));
        }

        let dialog_adapter = Arc::new(DialogAdapter::new(
            dialog_api,
            store.clone(),
            global_coordinator.clone(),
            outbound_proxy_uri,
            outbound_contact_params,
            symmetric_flow_params,
            config.registration_auto_refresh,
            config.registration_refresh_jitter_percent,
            config.auto_emit_extra_headers.clone(),
            config.trace_redaction.clone(),
        ));

        let media_controller =
            Self::create_media_controller(&config, global_coordinator.clone(), nat.symmetric_rtp)
                .await?;
        let mut media_adapter_inner = MediaAdapter::new(
            media_controller,
            store.clone(),
            config.local_ip,
            config.media_port_start,
            config.media_port_end,
        );
        media_adapter_inner.set_media_mode(config.media_mode);
        // Apply RFC 4568 SDES-SRTP policy from Config (Step 2B.1).
        media_adapter_inner.set_srtp_policy(
            config.offer_srtp,
            config.srtp_required,
            config.srtp_offered_suites.clone(),
        );
        media_adapter_inner.set_sdes_base64_mode(sdes_base64_mode);
        // Sprint 3 C1 — propagate Comfort Noise opt-in.
        media_adapter_inner.set_comfort_noise(config.comfort_noise_enabled);
        // AMR discontinuous transmission — sender-side policy, nothing to
        // negotiate (RFC 4867 defines no fmtp for DTX).
        media_adapter_inner.set_amr_dtx(config.amr_dtx);
        media_adapter_inner.set_amr_auto_cmr(config.amr_auto_cmr);
        media_adapter_inner.set_amr_mode_set(config.amr_mode_set.clone());
        // Sprint 3.5 — propagate strict codec matching policy.
        media_adapter_inner.set_strict_codec_matching(config.strict_codec_matching);
        // NEXT_STEPS C2 — propagate the configured offered codec list.
        media_adapter_inner.set_offered_codecs(config.offered_codecs.clone());
        media_adapter_inner.set_g729_annex_b(config.g729_annex_b);
        let media_adapter = Arc::new(media_adapter_inner);

        // Sprint 3 A6 — resolve the public RTP address. Static
        // override wins over STUN; STUN failure is soft (warn + use
        // local IP). Probe runs once, here, before any session is
        // created.
        let pending_stun_probe = if let Some(static_addr) = config.media_public_addr {
            if config.stun_server.is_some() {
                tracing::warn!(
                    "Both Config::media_public_addr and Config::stun_server are set; \
                     using the static override and skipping the STUN probe"
                );
            }
            tracing::info!(
                "RTP public addr: {} (static override from Config::media_public_addr)",
                static_addr
            );
            media_adapter.set_public_rtp_addr(Some(static_addr));
            None
        } else {
            config.stun_server.clone()
        };
        // RFC 4733 DTMF bridge: adapter publishes `Event::DtmfReceived`
        // onto the API bus whenever media-core signals a DTMF event.
        media_adapter
            .set_global_coordinator(global_coordinator.clone())
            .await;

        // Load state table based on config
        let state_table = Arc::new(crate::state_table::load_state_table_with_config(
            config.state_table_path.as_deref(),
        ));

        let (state_event_tx, state_event_rx) = mpsc::channel::<
            crate::state_machine::executor::SessionEvent,
        >(config.state_event_channel_capacity);

        let state_machine = Arc::new(StateMachine::new_with_custom_table(
            state_table,
            store.clone(),
            dialog_adapter.clone(),
            media_adapter.clone(),
            state_event_tx,
            config.auto_180_ringing,
        ));

        // Wire the state machine into the dialog adapter (for REGISTER
        // response handling). The adapter holds an `Arc<OnceLock<_>>`
        // internally so this post-construction init is sound without
        // `unsafe`.
        let _ = dialog_adapter.init_state_machine(state_machine.clone());

        // Create helpers
        let helpers = Arc::new(StateMachineHelpers::new(state_machine.clone()));

        // Create incoming call channel
        let (incoming_tx, incoming_rx) = mpsc::channel(config.incoming_call_channel_capacity);
        let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
        let setup_teardown_shutdown_rx = shutdown_rx.clone();
        let exact_response_shutdown_rx = shutdown_rx.clone();
        let lifecycle = config
            .server_call_capacity
            .map(LifecycleIndex::with_capacity)
            .unwrap_or_default();
        let app_event_publisher = SessionEventPublisher::with_dispatcher(
            global_coordinator.clone(),
            lifecycle.clone(),
            config.session_event_dispatcher_workers,
            config.session_event_dispatcher_channel_capacity,
        )
        .with_control_sink(session_control_tx, Arc::clone(&session_control_claimed));
        state_machine.init_exact_api_event_publisher(app_event_publisher.clone());
        media_adapter
            .set_app_event_publisher(app_event_publisher.clone())
            .await;
        let fast_auto_accept_incoming_calls = config.fast_auto_accept_incoming_calls;
        let fast_auto_accept_queue_capacity = config.incoming_call_channel_capacity;
        let server_call_admission_limit = config.server_call_admission_limit;
        let server_call_admission_soft_limit = config.server_call_admission_soft_limit;
        let server_call_admission_pacing_delay_ms = config.server_call_admission_pacing_delay_ms;
        let server_overload_retry_after_secs = config.server_overload_retry_after_secs;
        let pending_exact_responses = Arc::new(PendingExactResponseRegistry::default());
        pending_exact_responses.attach_session_store(&store);

        let coordinator = Arc::new(Self {
            helpers,
            media_adapter: media_adapter.clone(),
            dialog_adapter: dialog_adapter.clone(),
            incoming_rx: Arc::new(RwLock::new(incoming_rx)),
            global_coordinator: global_coordinator.clone(),
            session_control_rx: tokio::sync::Mutex::new(Some(session_control_rx)),
            session_control_claimed,
            config,
            shutdown_tx,
            shutdown_flights: CoordinatorShutdownFlights::default(),
            lifecycle: lifecycle.clone(),
            app_event_publisher: app_event_publisher.clone(),
            setup_teardown_scheduler: Arc::new(SetupTeardownDeadlineScheduler::default()),
            pending_exact_responses,
            session_registry: registry.clone(),
            inbound_invite_observers: StdMutex::new(HashMap::new()),
            next_inbound_invite_observer_id: AtomicU64::new(1),
            registered_credentials: std::sync::Mutex::new(None),
            self_weak: OnceLock::new(),
        });
        coordinator
            .setup_teardown_scheduler
            .attach_session_store(&store);
        let _ = coordinator.self_weak.set(Arc::downgrade(&coordinator));
        let mut construction_guard = CoordinatorConstructionGuard::new(Arc::clone(&coordinator));
        let setup_teardown_scheduler = Arc::clone(&coordinator.setup_teardown_scheduler);
        let setup_teardown_tasks = Arc::clone(&setup_teardown_scheduler.tasks);
        let scheduler_started = setup_teardown_tasks.spawn(run_setup_teardown_deadline_scheduler(
            Arc::downgrade(&coordinator),
            setup_teardown_scheduler,
            setup_teardown_shutdown_rx,
        ));
        debug_assert!(scheduler_started);
        let exact_response_runner_started =
            setup_teardown_tasks.spawn(run_exact_response_deadline_scheduler(
                Arc::downgrade(&coordinator),
                Arc::clone(&coordinator.pending_exact_responses),
                exact_response_shutdown_rx,
            ));
        debug_assert!(exact_response_runner_started);
        if let Some(stun_target) = pending_stun_probe {
            // Keep boot nonblocking while making constructor cancellation and
            // graceful shutdown join the probe before media dependencies drop.
            let adapter_for_probe = media_adapter.clone();
            let probe_started =
                coordinator
                    .setup_teardown_scheduler
                    .spawn_lifecycle_task(async move {
                        if let Err(e) = run_stun_probe(adapter_for_probe, &stun_target).await {
                            tracing::warn!(
                                "STUN probe failed against '{}': {} — falling back to local IP",
                                stun_target,
                                e
                            );
                        }
                    });
            debug_assert!(probe_started);
        }

        // Start the dialog adapter. The scheduler runner is already retained;
        // join it explicitly on constructor failure rather than relying on a
        // later last-owner drop to wake and detach it.
        if let Err(start_error) = dialog_adapter.start().await {
            if coordinator.cleanup_failed_construction().await {
                construction_guard.disarm();
            }
            return Err(start_error);
        }

        // Create and start the centralized event handler.
        // Events are published to the global coordinator's "session_to_app" channel.
        let event_handler =
            crate::adapters::SessionCrossCrateEventHandler::with_event_broadcast_and_state_machine_events(
                state_machine.clone(),
                global_coordinator.clone(),
                dialog_adapter.clone(),
                media_adapter.clone(),
                registry.clone(),
                incoming_tx,
                state_event_rx,
                app_event_publisher.clone(),
                sip_trace_owner_id,
            )
            .with_runtime_owners(
                Arc::clone(&coordinator.helpers),
                Arc::clone(&setup_teardown_tasks),
            )
            .with_fast_auto_accept_incoming_calls(
                fast_auto_accept_incoming_calls,
                fast_auto_accept_queue_capacity,
            )
            .with_server_call_admission(
                server_call_admission_limit,
                server_call_admission_soft_limit,
                server_call_admission_pacing_delay_ms,
                server_overload_retry_after_secs,
            )
            .with_causal_dialog_ingress(causal_dialog_ingress);

        // SIP_API_DESIGN_2 Phase D — give the handler a weak handle
        // back to the coordinator so the typed `IncomingRegister`
        // branch can build a response-capable wrapper. Weak avoids
        // the circular ownership loop.
        event_handler.set_coordinator(&coordinator);

        // Start the event handler (sets up channels and subscriptions). Keep
        // the same bottom-up shutdown order if construction fails after the
        // dialog adapter and scheduler have started.
        if let Err(start_error) = event_handler.start(shutdown_rx).await {
            if coordinator.cleanup_failed_construction().await {
                construction_guard.disarm();
            }
            return Err(start_error);
        }

        causal_ingress_guard.disarm();
        construction_guard.disarm();
        Ok(coordinator)
    }

    pub(crate) fn fast_auto_accept_incoming_calls(&self) -> bool {
        self.config.fast_auto_accept_incoming_calls
    }

    pub(crate) async fn claim_session_control_events(
        &self,
    ) -> Result<mpsc::UnboundedReceiver<crate::adapters::SessionControlEvent>> {
        let mut receiver = self.session_control_rx.lock().await;
        let receiver = receiver.take().ok_or_else(|| {
            SessionError::InvalidInput(
                "application control-event receiver already has an owner".to_string(),
            )
        })?;
        self.session_control_claimed.store(true, Ordering::Release);
        Ok(receiver)
    }

    pub(crate) fn register_exact_response_obligation(
        &self,
        obligation: Arc<crate::api::incoming::ExactResponseObligation>,
    ) -> ExactResponseRegistration {
        self.pending_exact_responses.register(obligation)
    }

    pub(crate) fn pending_exact_response_registry(&self) -> Arc<PendingExactResponseRegistry> {
        Arc::clone(&self.pending_exact_responses)
    }

    /// Return the generation-scoped setup/teardown deadline cancellation
    /// capability used by exact terminal cleanup outside this module.
    pub(crate) fn setup_teardown_deadline_cancellation(&self) -> SetupTeardownDeadlineCancellation {
        SetupTeardownDeadlineCancellation {
            scheduler: Arc::clone(&self.setup_teardown_scheduler),
        }
    }

    pub(crate) fn complete_exact_response_obligation(
        &self,
        obligation: &crate::api::incoming::ExactResponseObligation,
    ) {
        self.pending_exact_responses.remove_owner(obligation);
    }

    async fn author_pending_exact_response(
        &self,
        obligation: Arc<crate::api::incoming::ExactResponseObligation>,
        status: u16,
    ) -> ManagedExactResponseOutcome {
        author_pending_exact_response_with_adapter(self.dialog_adapter(), obligation, status).await
    }

    async fn drain_exact_responses_for_shutdown(&self) -> Result<()> {
        self.pending_exact_responses.begin_close();
        let deadline = Instant::now() + EXACT_RESPONSE_SHUTDOWN_DRAIN_TIMEOUT;
        loop {
            let pending = self.pending_exact_responses.snapshot();
            if pending.is_empty() {
                return Ok(());
            }
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return Err(SessionError::InternalError(format!(
                    "exact response shutdown drain timed out with {} pending obligations",
                    self.pending_exact_responses.entries.len()
                )));
            }
            let attempt_timeout = remaining.min(EXACT_RESPONSE_SEND_ATTEMPT_TIMEOUT);
            let pending_registry = Arc::clone(&self.pending_exact_responses);
            let batch = run_bounded_exact_response_batch(
                pending,
                EXACT_RESPONSE_DEADLINE_CONCURRENCY,
                |obligation| {
                    let pending_registry = Arc::clone(&pending_registry);
                    async move {
                        let _fire = pending_registry.begin_fire();
                        let fallback_status = obligation.fallback_status();
                        let _ = tokio::time::timeout(
                            attempt_timeout,
                            self.author_pending_exact_response(obligation, fallback_status),
                        )
                        .await;
                    }
                },
            );
            let _ = tokio::time::timeout(remaining, batch).await;
            if self.pending_exact_responses.entries.is_empty() {
                return Ok(());
            }
            if Instant::now() >= deadline {
                return Err(SessionError::InternalError(format!(
                    "exact response shutdown drain timed out with {} pending obligations",
                    self.pending_exact_responses.entries.len()
                )));
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    }

    // ===== Shutdown =====

    async fn cleanup_failed_construction(&self) -> bool {
        if let Err(refresh_error) = self
            .dialog_adapter
            .abort_all_registration_refreshes_and_wait()
            .await
        {
            tracing::warn!(
                "Registration refresh tasks failed to join after coordinator construction failure; retaining dependencies: {}",
                refresh_error
            );
            return false;
        }
        self.pending_exact_responses.begin_close();
        let _ = self.shutdown_tx.send(true);
        if let Err(drain_error) = self.drain_exact_responses_for_shutdown().await {
            tracing::warn!(
                "Exact response obligations failed to drain after coordinator construction failure; retaining dependencies: {}",
                drain_error
            );
            return false;
        }
        if let Err(drain_error) = self
            .setup_teardown_scheduler
            .close_and_wait(SETUP_TEARDOWN_SCHEDULER_DRAIN_TIMEOUT)
            .await
        {
            tracing::warn!(
                "Setup/teardown scheduler failed to join after coordinator construction failure; retaining dependencies: {}",
                drain_error
            );
            return false;
        }
        let stop_succeeded = match self.dialog_adapter.stop().await {
            Ok(()) => true,
            Err(stop_error) => {
                tracing::warn!(
                    "Dialog adapter failed to stop after coordinator construction failure: {}",
                    stop_error
                );
                false
            }
        };
        if stop_succeeded {
            self.pending_exact_responses.clear();
            self.app_event_publisher.shutdown().await;
        }
        stop_succeeded
    }

    /// Shut down this coordinator and all its background tasks.
    ///
    /// This is a non-blocking best-effort shutdown. When
    /// [`Config::unregister_on_shutdown_timeout_secs`] is non-zero, active
    /// registrations are asked to unregister before the shutdown signal is
    /// sent. Use [`shutdown_gracefully`](Self::shutdown_gracefully) when the
    /// caller needs deterministic unregister completion.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>) {
    /// coordinator.shutdown();
    /// # }
    /// ```
    pub fn shutdown(&self) {
        let timeout = Duration::from_secs(self.config.unregister_on_shutdown_timeout_secs);
        let _ = self.begin_shutdown_attempt(timeout);
    }

    /// Gracefully unregister active registrations, then stop background tasks.
    ///
    /// The timeout applies per registration. Pass `None` to use
    /// [`Config::unregister_on_shutdown_timeout_secs`]. A zero timeout skips
    /// unregister and behaves like an immediate shutdown.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>) -> rvoip_sip::Result<()> {
    /// coordinator.shutdown_gracefully(Some(std::time::Duration::from_secs(2))).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn shutdown_gracefully(&self, timeout: Option<Duration>) -> Result<()> {
        let timeout = timeout.unwrap_or_else(|| {
            Duration::from_secs(self.config.unregister_on_shutdown_timeout_secs)
        });
        self.begin_shutdown_attempt(timeout)
            .wait()
            .await
            .into_result()
    }

    fn begin_shutdown_attempt(&self, timeout: Duration) -> Arc<CoordinatorShutdownAttempt> {
        let (attempt, should_start) = self.shutdown_flights.begin();
        if !should_start {
            return attempt;
        }

        let Some(coordinator) = self.self_weak.get().and_then(Weak::upgrade) else {
            attempt.finish(CoordinatorShutdownOutcome::DriverPanicked);
            return attempt;
        };
        let driver_attempt = Arc::clone(&attempt);
        tokio::spawn(async move {
            let outcome =
                match std::panic::AssertUnwindSafe(coordinator.run_shutdown_sequence(timeout))
                    .catch_unwind()
                    .await
                {
                    Ok(outcome) => outcome,
                    Err(_) => {
                        tracing::error!("Coordinator shutdown driver panicked");
                        CoordinatorShutdownOutcome::DriverPanicked
                    }
                };
            driver_attempt.finish(outcome);
        });
        attempt
    }

    async fn run_shutdown_sequence(&self, timeout: Duration) -> CoordinatorShutdownOutcome {
        if !timeout.is_zero() {
            self.unregister_registered_sessions(timeout).await;
        }
        if let Err(error) = self
            .dialog_adapter
            .abort_all_registration_refreshes_and_wait()
            .await
        {
            tracing::warn!(
                "Registration refresh tasks failed to drain during shutdown; retaining SIP dependencies for retry: {}",
                error
            );
            return CoordinatorShutdownOutcome::RegistrationRefreshDrainFailed;
        }
        // Stop admitting new application-control work while dialog/transport
        // resources are still available. The strong registry owns queued or
        // retained IncomingRequest values and authors an exact 503 for each
        // unclaimed obligation before the shared response supervisor closes.
        self.pending_exact_responses.begin_close();
        let _ = self.shutdown_tx.send(true);
        if let Err(error) = self.drain_exact_responses_for_shutdown().await {
            tracing::warn!(
                "Exact response obligations failed to drain during shutdown; retaining SIP dependencies for retry: {}",
                error
            );
            return CoordinatorShutdownOutcome::ExactResponseDrainFailed;
        }
        if let Err(error) = self
            .setup_teardown_scheduler
            .close_and_wait(SETUP_TEARDOWN_SCHEDULER_DRAIN_TIMEOUT)
            .await
        {
            tracing::warn!(
                "Setup/teardown scheduler failed to drain during shutdown; retaining SIP dependencies for retry: {}",
                error
            );
            return CoordinatorShutdownOutcome::SchedulerDrainFailed;
        }
        if let Err(error) = self.dialog_adapter.stop().await {
            tracing::warn!(
                "Dialog adapter stop failed during shutdown; retaining event routes for retry: {}",
                error
            );
            return CoordinatorShutdownOutcome::DialogStopFailed;
        }
        self.pending_exact_responses.clear();
        self.app_event_publisher.shutdown().await;
        CoordinatorShutdownOutcome::Succeeded
    }

    async fn unregister_registered_sessions(&self, timeout: Duration) {
        let sessions = self.helpers.state_machine.store.get_all_sessions().await;
        for session in sessions {
            if !session.is_registered {
                continue;
            }
            let handle = RegistrationHandle {
                session_id: session.session_id.clone(),
            };
            if let Err(e) = self.unregister_and_wait(&handle, Some(timeout)).await {
                tracing::warn!(
                    "Graceful shutdown unregister failed for session {}: {}",
                    session.session_id,
                    e
                );
            }
        }
    }

    /// Return a cloneable handle that can signal
    /// [`shutdown`](Self::shutdown) from another task. Mirrors
    /// [`CallbackPeer::shutdown_handle`].
    ///
    /// [`CallbackPeer::shutdown_handle`]: crate::api::callback_peer::CallbackPeer::shutdown_handle
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>) {
    /// let stop = coordinator.shutdown_handle();
    /// tokio::spawn(async move {
    ///     stop.shutdown();
    /// });
    /// # }
    /// ```
    pub fn shutdown_handle(&self) -> crate::api::callback_peer::ShutdownHandle {
        crate::api::callback_peer::ShutdownHandle::from_coordinator(
            self.self_weak.get().cloned().unwrap_or_else(Weak::new),
        )
    }

    // ===== Event Subscription =====

    /// Subscribe to the raw cross-crate session API event stream.
    ///
    /// Returns an independent `mpsc::Receiver` for events published by this
    /// coordinator on the internal `"session_to_app"` channel. Most
    /// application code should prefer [`events`](Self::events), which wraps
    /// this raw receiver and yields typed [`Event`](crate::api::events::Event)
    /// values.
    ///
    /// Use this method only when building a custom peer type or diagnostic
    /// tool that needs access to the raw event envelope.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>) -> rvoip_sip::Result<()> {
    /// let mut raw_events = coordinator.subscribe_events().await?;
    /// tokio::spawn(async move {
    ///     while let Some(_event) = raw_events.recv().await {
    ///         // Downcast to SessionApiCrossCrateEvent for diagnostics.
    ///     }
    /// });
    /// # Ok(())
    /// # }
    /// ```
    pub async fn subscribe_events(
        &self,
    ) -> crate::errors::Result<
        tokio::sync::mpsc::Receiver<
            std::sync::Arc<dyn rvoip_infra_common::events::cross_crate::CrossCrateEvent>,
        >,
    > {
        self.global_coordinator
            .subscribe(crate::adapters::SESSION_TO_APP_CHANNEL)
            .await
            .map_err(|e| {
                crate::errors::SessionError::InternalError(format!(
                    "Failed to subscribe to session events: {}",
                    e
                ))
            })
    }

    /// Subscribe to bounded, opt-in security and renegotiation diagnostics.
    ///
    /// This stream carries details that cannot be added to the exhaustive
    /// 0.3.x [`Event`](crate::api::events::Event) enum without breaking
    /// existing pattern matches. Lagging receivers may lose observations;
    /// diagnostics never block signaling or call-state transitions.
    pub fn subscribe_diagnostics(
        &self,
    ) -> tokio::sync::broadcast::Receiver<crate::api::events::DiagnosticEvent> {
        self.app_event_publisher.subscribe_diagnostics()
    }

    /// Return a typed, unfiltered [`EventReceiver`](crate::api::stream_peer::EventReceiver) that yields
    /// [`crate::api::events::Event`] values across all sessions and
    /// registration lifecycles owned by this coordinator.
    ///
    /// Use when a single consumer needs every session API event, for example
    /// a b2bua coordinator, activity log, or registration monitor. For
    /// per-leg call logic prefer [`events_for_session`][Self::events_for_session].
    ///
    /// The returned receiver already handles the downcast from the raw
    /// cross-crate broadcast and exposes filtering helpers like
    /// [`EventReceiver::next_dtmf`](crate::api::stream_peer::EventReceiver::next_dtmf),
    /// [`EventReceiver::next_incoming`](crate::api::stream_peer::EventReceiver::next_incoming),
    /// and
    /// [`EventReceiver::next_transfer`](crate::api::stream_peer::EventReceiver::next_transfer).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>) -> rvoip_sip::Result<()> {
    /// use rvoip_sip::Event;
    ///
    /// let mut events = coordinator.events().await?;
    /// if let Some(Event::RegistrationSuccess { registrar, .. }) = events.next().await {
    ///     println!("registered with {registrar}");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn events(&self) -> Result<crate::api::stream_peer::EventReceiver> {
        let rx = self.subscribe_events().await?;
        Ok(crate::api::stream_peer::EventReceiver::new(rx))
    }

    /// Claim the coordinator's single response-capable control stream and
    /// merge it with the ordinary public observations.
    ///
    /// Only one control owner may exist. Response-bearing inbound requests
    /// such as SIP INFO and exact session handles are yielded once through the
    /// private stream. All public observational copies are sanitized and
    /// suppressed by this owner. Further calls return an error. Libraries
    /// that only monitor calls should continue to use [`events`](Self::events).
    pub async fn events_with_control(
        self: &Arc<Self>,
    ) -> Result<crate::api::stream_peer::EventReceiver> {
        let observations = self.subscribe_events().await?;
        let control = self.claim_session_control_events().await?;
        Ok(crate::api::stream_peer::EventReceiver::with_control(
            observations,
            control,
            Arc::clone(self),
        ))
    }

    /// Return an [`EventReceiver`](crate::api::stream_peer::EventReceiver) that only yields events whose
    /// `call_id` matches `id`. Per-session filtering happens in the
    /// receiver's `next()` loop.
    ///
    /// Registration lifecycle events do not carry a call id, so they are only
    /// visible on [`events`](Self::events), not on per-session receivers.
    ///
    /// Intended for b2bua-style consumers that need to watch both legs of
    /// a bridged call independently:
    ///
    /// ```no_run
    /// # use rvoip_sip::{Event, SessionId, UnifiedCoordinator};
    /// # async fn example(coord: &UnifiedCoordinator, inbound: &SessionId, outbound: &SessionId) {
    /// let mut inbound_events = coord.events_for_session(inbound).await.unwrap();
    /// let mut outbound_events = coord.events_for_session(outbound).await.unwrap();
    /// tokio::select! {
    ///     Some(Event::CallEnded { .. }) = inbound_events.next() => {
    ///         // inbound leg ended — tear down the outbound leg
    ///     }
    ///     Some(Event::CallEnded { .. }) = outbound_events.next() => {
    ///         // outbound leg ended — tear down the inbound leg
    ///     }
    /// }
    /// # }
    /// ```
    ///
    /// **Caller contract:** open the receiver *before* any event of
    /// interest fires. Events are lost if no subscriber is attached at
    /// publish time. For incoming calls the safe pattern is:
    /// 1. Wait for an `IncomingCall` event on the unfiltered
    ///    [`events()`][Self::events] receiver.
    /// 2. Open `events_for_session(&id)` with the new `SessionId`.
    /// 3. Call `accept_call_with_sdp()` (post-acceptance events then
    ///    reach the filtered receiver).
    ///
    /// # Examples
    ///
    /// See the b2bua-style event split above for a complete `tokio::select!`
    /// example.
    pub async fn events_for_session(
        &self,
        id: &SessionId,
    ) -> Result<crate::api::stream_peer::EventReceiver> {
        let rx = self.subscribe_events().await?;
        let mut receiver = crate::api::stream_peer::EventReceiver::filtered(rx, id.clone());

        // Race repair: SESSION_TO_APP_CHANNEL is broadcast — a subscriber
        // added here cannot observe events that fired before this call
        // returned. On a fast loopback, `invite → 200 OK → CallAnswered`
        // can complete in well under a millisecond, so callers that follow
        // the documented `invite().send() → events_for_session → wait for
        // CallAnswered` pattern would otherwise deadlock. Inspect the
        // session's *current* state and synthesize the events the caller
        // would have observed had they been subscribed earlier.
        if let Ok(state) = self.helpers.get_state(id).await {
            use crate::types::CallState;
            match state {
                CallState::Active
                | CallState::Bridged
                | CallState::OnHold
                | CallState::HoldPending
                | CallState::EarlyMedia
                | CallState::Resuming
                | CallState::Muted => {
                    receiver.prime(crate::api::events::Event::CallAnswered {
                        call_id: id.clone(),
                        sdp: None,
                    });
                }
                CallState::Failed(reason) => {
                    receiver.prime(crate::api::events::Event::CallFailed {
                        call_id: id.clone(),
                        reason: reason.to_string(),
                        status_code: 500,
                    });
                }
                CallState::Terminated | CallState::Cancelled => {
                    receiver.prime(crate::api::events::Event::CallEnded {
                        call_id: id.clone(),
                        reason: format!("session in state {state:?}"),
                    });
                }
                _ => {}
            }
        }

        Ok(receiver)
    }

    pub(crate) async fn lifecycle_snapshot(&self, id: &SessionId) -> CallLifecycleSnapshot {
        let (state, media_security) = self
            .helpers
            .state_machine
            .store
            .with_session(id, |session| {
                (Some(session.call_state), session.media_security.clone())
            })
            .unwrap_or((None, None));
        let mut snapshot = self.lifecycle.snapshot(id, state);
        if snapshot.media_security.is_none() {
            snapshot.media_security = media_security;
        }
        snapshot
    }

    pub(crate) fn lifecycle_index(&self) -> LifecycleIndex {
        self.lifecycle.clone()
    }

    pub(crate) async fn lifecycle_snapshot_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Result<CallLifecycleSnapshot> {
        let current = self
            .helpers
            .state_machine
            .store
            .get_session_snapshot_exact(handle)
            .ok();
        let state = current.as_ref().map(|session| session.call_state);
        let media_security = current
            .as_ref()
            .and_then(|session| session.media_security.clone());
        let mut snapshot = self.lifecycle.snapshot_exact(handle, state);
        if snapshot.media_security.is_none() {
            snapshot.media_security = media_security;
        }
        let has_exact_evidence = current.is_some()
            || !snapshot.progress.is_empty()
            || snapshot.answered.is_some()
            || snapshot.media_security.is_some()
            || snapshot.terminal.is_some()
            || snapshot.latest_transfer_outcome.is_some();
        has_exact_evidence.then_some(snapshot).ok_or_else(|| {
            SessionError::SessionNotFound(format!(
                "Session {} exact lifecycle is unavailable",
                handle.session_id()
            ))
        })
    }

    pub(crate) fn lifecycle_watcher_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> tokio::sync::watch::Receiver<u64> {
        self.lifecycle.watcher_exact(handle)
    }

    #[doc(hidden)]
    pub async fn publish_app_event_for_test(&self, event: crate::api::events::Event) -> Result<()> {
        self.app_event_publisher.publish_now(event).await
    }

    #[cfg(test)]
    pub(crate) fn publish_app_event_exact_for_test(
        &self,
        handle: &SessionRegistryHandle,
        event: crate::api::events::Event,
    ) -> Result<()> {
        self.helpers
            .state_machine
            .store
            .get_session_snapshot_exact(handle)
            .map_err(|_| SessionError::SessionNotFound(handle.session_id().to_string()))?;
        self.app_event_publisher.publish_exact(handle, event);
        Ok(())
    }

    // ===== Simple Call Operations =====

    /// Spawn an outbound leg linked to a transferor session for RFC 3515
    /// §2.4.5 progress reporting. The new leg's `SessionState` carries
    /// `transferor_session_id = Some(..)` before the state machine
    /// dispatches `MakeCall`, so every subsequent `Dialog180Ringing` /
    /// `Dialog200OK` / failure fires a progress NOTIFY back on the
    /// transferor's REFER subscription. This is the b2bua wrapper crate's
    /// primary REFER-forwarding entry point.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, transferor: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// let new_leg = coordinator.make_transfer_leg(
    ///     "sip:service@127.0.0.1:5060",
    ///     "sip:target@example.com",
    ///     &transferor,
    /// ).await?;
    /// # let _ = new_leg;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn make_transfer_leg(
        &self,
        from: &str,
        to: &str,
        transferor_session_id: &SessionId,
    ) -> Result<SessionId> {
        self.helpers
            .make_transfer_leg(from, to, transferor_session_id)
            .await
    }

    /// Retroactively link an existing session as a transfer leg of
    /// `transferor_session_id`. Prefer [`make_transfer_leg`](Self::make_transfer_leg) — this
    /// lower-level primitive accepts a race window in which dialog
    /// events fired before the linkage is set silently drop their
    /// corresponding progress NOTIFY.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, leg: rvoip_sip::SessionId, transferor: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.set_transferor_session(&leg, &transferor).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn set_transferor_session(
        &self,
        leg_session_id: &SessionId,
        transferor_session_id: &SessionId,
    ) -> Result<()> {
        self.helpers
            .set_transferor_session(leg_session_id, transferor_session_id)
            .await
    }

    /// Accept an incoming call.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, incoming: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.accept_call(&incoming).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn accept_call(&self, session_id: &SessionId) -> Result<()> {
        let result = self.helpers.accept_call(session_id).await;
        self.schedule_setup_teardown_timeout_if_current(
            session_id,
            SetupTeardownWatchdogKind::AcceptedCall,
        )
        .await;
        result
    }

    /// Accept an incoming call with a caller-supplied SDP answer. Bypasses
    /// local media negotiation — intended for b2bua flows where the answer
    /// body comes from the outbound leg's 200 OK. See
    /// [`StateMachineHelpers::accept_call_with_sdp`] for the mechanism.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, incoming: rvoip_sip::SessionId, answer_sdp: String) -> rvoip_sip::Result<()> {
    /// coordinator.accept_call_with_sdp(&incoming, answer_sdp).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn accept_call_with_sdp(&self, session_id: &SessionId, sdp: String) -> Result<()> {
        let result = self.helpers.accept_call_with_sdp(session_id, sdp).await;
        self.schedule_setup_teardown_timeout_if_current(
            session_id,
            SetupTeardownWatchdogKind::AcceptedCallWithSdp,
        )
        .await;
        result
    }

    /// Internal exact-lifetime accept path used by `AcceptBuilder` after its
    /// complete response envelope has been frozen.
    pub(crate) async fn accept_call_with_response(
        &self,
        session_id: &SessionId,
        lifecycle_handle: &SessionRegistryHandle,
        sdp: Option<String>,
        extras: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<()> {
        let watchdog_kind = if sdp.is_some() {
            SetupTeardownWatchdogKind::AcceptedCallWithSdp
        } else {
            SetupTeardownWatchdogKind::AcceptedCall
        };
        let result = self
            .helpers
            .accept_call_with_response(session_id, lifecycle_handle, sdp, extras)
            .await;
        self.schedule_setup_teardown_timeout_exact_if_current(lifecycle_handle, watchdog_kind)
            .await;
        result
    }

    /// Hang up or cancel a call.
    ///
    /// Established calls send BYE. Ringing or early-media outbound calls send
    /// CANCEL and do not publish `CallCancelled` until the INVITE reaches a
    /// terminal outcome. If the outbound INVITE has not received a provisional
    /// response yet, cancel intent is recorded and CANCEL is sent only if it
    /// later becomes legal; a fast 200 OK is ACKed and immediately BYE-cleaned.
    /// Use [`SessionHandle::hangup_and_wait`](crate::api::handle::SessionHandle::hangup_and_wait)
    /// when the caller needs to wait for the terminal API event.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// let mut events = coordinator.events_for_session(&call_id).await?;
    /// coordinator.hangup(&call_id).await?;
    /// // Wait for Event::CallEnded / CallFailed / CallCancelled if needed.
    /// # let _ = events.next().await;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn hangup(&self, session_id: &SessionId) -> Result<()> {
        let handle = self
            .helpers
            .state_machine
            .store
            .lifecycle_handle(session_id)
            .ok_or_else(|| {
                SessionError::SessionNotFound(format!(
                    "Session {} has no current exact hangup lifetime",
                    session_id.0
                ))
            })?;
        self.hangup_exact(&handle).await
    }

    pub(crate) async fn hangup_exact(&self, handle: &SessionRegistryHandle) -> Result<()> {
        self.hangup_exact_with_reason(handle, "Local hangup").await
    }

    /// Join the one exact hangup authority while supplying the terminal reason
    /// used by its eventual committed release. Automatic lifecycle owners use
    /// this same path as public hangup so BYE dispatch, final-response
    /// confirmation, lifecycle commit, and resource release cannot diverge.
    async fn hangup_exact_with_reason(
        &self,
        handle: &SessionRegistryHandle,
        reason: impl Into<String>,
    ) -> Result<()> {
        let reason = reason.into();
        // One exact SessionStateCell owns one retained hangup operation. The
        // public caller is only a waiter: dropping it cannot cancel dispatch,
        // wire confirmation, or finalization, and another caller joins the
        // same completion instead of crossing a shared generation fence.
        let Some(control) = self
            .helpers
            .state_machine
            .store
            .hangup_control_exact(handle)
        else {
            return Err(SessionError::SessionNotFound(format!(
                "Session {} has no current exact hangup lifetime",
                handle.session_id().0
            )));
        };
        let coordinator = self
            .self_weak
            .get()
            .and_then(Weak::upgrade)
            .ok_or_else(|| {
                SessionError::InternalError("exact hangup supervisor is unavailable".to_string())
            })?;
        if !control.try_start() {
            drop(coordinator);
            return shared_hangup_completion_result(control.wait_for_completion().await);
        }

        let retained_control = Arc::clone(&control);
        let retained_handle = handle.clone();
        let (result_tx, result_rx) = tokio::sync::oneshot::channel();
        let completion_guard = RetainedHangupTaskCompletion::new(retained_control);
        let hangup_scheduler = Arc::clone(&self.setup_teardown_scheduler);
        let spawned = hangup_scheduler.spawn_lifecycle_task(async move {
            let mut completion_guard = completion_guard;
            let result = match std::panic::AssertUnwindSafe(
                coordinator.hangup_serialized_exact(&retained_handle, reason),
            )
            .catch_unwind()
            .await
            {
                Ok(result) => result,
                Err(_) => Err(SessionError::InternalError(
                    "exact hangup operation stopped unexpectedly".to_string(),
                )),
            };
            completion_guard.finish(result.is_ok());
            let _ = result_tx.send(result);
        });
        if !spawned {
            return shared_hangup_completion_result(control.wait_for_completion().await);
        }

        match result_rx.await {
            Ok(result) => result,
            Err(_) => shared_hangup_completion_result(control.wait_for_completion().await),
        }
    }

    async fn hangup_serialized_exact(
        &self,
        handle: &SessionRegistryHandle,
        reason: String,
    ) -> Result<()> {
        let _bye_wait_owner = self.dialog_adapter.begin_outgoing_bye_wait_exact(handle)?;
        let initial_state = self
            .helpers
            .state_machine
            .store
            .get_session_snapshot_exact(handle)
            .ok()
            .map(|session| session.call_state);
        // Fence the per-session retained transaction before dispatch. A BYE
        // send can complete and retain its exact transaction, then lose the
        // final state-store revision race to a synchronous peer response. In
        // that case dispatch reports a bookkeeping error even though the wire
        // operation must still be joined and reclaimed below.
        let bye_generation_before_dispatch = self
            .dialog_adapter
            .outgoing_bye_generation_exact(handle)
            .unwrap_or(0);
        let dispatch = self.helpers.hangup_exact(handle).await;
        let retained_new_bye = matches!(initial_state, Some(CallState::Active))
            && self
                .dialog_adapter
                .has_outgoing_bye_after_exact(handle, bye_generation_before_dispatch);

        if dispatch.is_ok() || retained_new_bye {
            // The coordinator/state machine is now the sole protocol teardown
            // authority for this exact call. It may send CANCEL immediately,
            // defer it until a provisional response makes it legal, or ACK+BYE
            // a racing 2xx. Managed initial-INVITE release must therefore
            // retire local ownership without starting a competing CANCEL/BYE
            // loop.
            self.dialog_adapter
                .mark_initial_invite_protocol_teardown_exact(handle);
        }
        // An established local hangup is not acknowledged merely because a
        // concurrent dialog event has already published terminal lifecycle
        // evidence. Join this exact BYE transaction before the generic
        // observed-terminal shortcut can convert teardown into success. A
        // 2xx confirms receipt; RFC 3261 §15.1.1 also makes an exact 481 a
        // graceful terminal result because it proves the peer no longer has
        // the dialog (the ordinary simultaneous-BYE race). The confirmation
        // helper always performs exact local reclamation on any other
        // timeout/non-2xx while preserving that wire failure for the caller.
        if matches!(initial_state, Some(CallState::Active)) {
            return complete_established_bye_dispatch(
                dispatch,
                retained_new_bye,
                self.finalize_confirmed_local_bye_exact(handle, reason),
            )
            .await;
        }
        dispatch?;
        if self
            .lifecycle_snapshot_exact(handle)
            .await
            .is_ok_and(|snapshot| snapshot.terminal.is_some())
        {
            self.release_after_observed_terminal_exact(handle).await;
            return Ok(());
        }
        self.schedule_setup_teardown_timeout_exact_if_current(
            handle,
            SetupTeardownWatchdogKind::Cancellation,
        )
        .await;
        Ok(())
    }

    async fn release_after_observed_terminal(&self, session_id: &SessionId) {
        let Some(handle) = self
            .helpers
            .state_machine
            .store
            .lifecycle_handle(session_id)
        else {
            return;
        };
        self.release_after_observed_terminal_exact(&handle).await;
    }

    async fn release_after_observed_terminal_exact(&self, handle: &SessionRegistryHandle) {
        let session_id = handle.session_id();
        let release_guard = crate::cleanup_diag::stage_guard(
            crate::cleanup_diag::CleanupStage::TerminalRelease,
            &session_id.0,
        );
        match release_exact_local_resources(
            Arc::clone(&self.helpers.state_machine.store),
            Arc::clone(&self.helpers),
            Arc::clone(&self.dialog_adapter),
            Arc::clone(&self.media_adapter),
            Some(Arc::clone(&self.pending_exact_responses)),
            Some(self.setup_teardown_deadline_cancellation()),
            handle.clone(),
        )
        .await
        {
            Ok(()) => release_guard.finish_success(),
            Err(error) => {
                tracing::debug!(%error, "exact release after observed terminal was incomplete");
                release_guard.finish_failure();
            }
        }
    }

    /// Compensate an outbound setup that failed after session allocation but
    /// before `OutboundCallBuilder::send` could return a usable call id.
    /// Cleanup is deliberately best-effort and idempotent; the original
    /// dispatch error remains the public result.
    pub(crate) async fn rollback_outbound_setup(&self, session_id: &SessionId) {
        tracing::debug!(
            session_id = %session_id,
            "rolling back partially allocated outbound setup"
        );
        self.release_after_observed_terminal(session_id).await;
    }

    pub(crate) async fn schedule_outbound_setup_timeout(&self, session_id: &SessionId) {
        self.schedule_setup_teardown_timeout_if_current(
            session_id,
            SetupTeardownWatchdogKind::OutboundSetup,
        )
        .await;
    }

    pub(crate) async fn schedule_inbound_setup_timeout(&self, session_id: &SessionId) {
        self.schedule_setup_teardown_timeout_if_current(
            session_id,
            SetupTeardownWatchdogKind::InboundSetup,
        )
        .await;
    }

    pub(crate) async fn schedule_active_call_media_timeout_if_current(
        &self,
        session_id: &SessionId,
    ) {
        let no_media_timeout = Duration::from_secs(self.config.active_call_no_media_timeout_secs);
        let media_idle_timeout =
            Duration::from_secs(self.config.active_call_media_idle_timeout_secs);
        if no_media_timeout.is_zero() && media_idle_timeout.is_zero() {
            return;
        }

        let Ok((role, call_state, handle, entered_state_at)) = self
            .helpers
            .state_machine
            .store
            .with_session(session_id, |session| {
                (
                    session.role,
                    session.call_state,
                    session.lifecycle_handle.clone(),
                    session.entered_state_at,
                )
            })
        else {
            return;
        };
        if role != Role::UAS || call_state != CallState::Active {
            return;
        }
        let Some(handle) = handle else {
            return;
        };

        let session_id = session_id.clone();
        let state_machine = Arc::clone(&self.helpers.state_machine);
        let media_adapter = Arc::clone(&self.media_adapter);
        let coordinator = self.self_weak.get().cloned();
        let watchdog_scheduler = Arc::clone(&self.setup_teardown_scheduler);
        let task_scheduler = Arc::clone(&watchdog_scheduler);
        let _ = watchdog_scheduler.spawn_lifecycle_task(async move {
            let Some(initial_packets_received) =
                media_adapter.rtp_packets_received(&session_id).await
            else {
                return;
            };
            let mut last_packets_received = initial_packets_received;
            let mut saw_media = initial_packets_received > 0;
            loop {
                let timeout = if saw_media {
                    media_idle_timeout
                } else if !no_media_timeout.is_zero() {
                    no_media_timeout
                } else {
                    media_idle_timeout
                };
                if timeout.is_zero() {
                    return;
                }

                if !task_scheduler.sleep_or_closed(timeout).await
                    || !task_scheduler.is_accepting()
                {
                    return;
                }

                let Ok(current) = state_machine.store.get_session_snapshot_exact(&handle) else {
                    return;
                };
                let current = current.state();
                if current.role != Role::UAS
                    || current.call_state != CallState::Active
                    || current.entered_state_at != entered_state_at
                {
                    return;
                }

                let Some(packets_received) = media_adapter.rtp_packets_received(&session_id).await
                else {
                    return;
                };

                if packets_received > last_packets_received {
                    saw_media = true;
                    last_packets_received = packets_received;
                    continue;
                }

                let reason = if saw_media {
                    format!(
                        "Active call released after RTP was idle for {}s",
                        timeout.as_secs()
                    )
                } else {
                    format!(
                        "Active call released after no RTP was received within {}s after answer",
                        timeout.as_secs()
                    )
                };

                tracing::warn!(
                    "active call media watchdog firing for session {} after {:?}: last_packets_received={}, saw_media={}",
                    session_id,
                    timeout,
                    last_packets_received,
                    saw_media
                );

                let Some(coordinator) = coordinator.as_ref().and_then(Weak::upgrade) else {
                    return;
                };
                if let Err(err) = coordinator
                    .hangup_exact_with_reason(&handle, reason)
                    .await
                {
                    tracing::warn!(
                        "active call media watchdog failed exact confirmed hangup for {} in state {:?}: {}",
                        session_id,
                        current.call_state,
                        err
                    );
                }
                return;
            }
        });
    }

    pub(crate) fn setup_teardown_timeout_duration(&self) -> Duration {
        Duration::from_secs(self.config.setup_teardown_timeout_secs)
    }

    async fn schedule_setup_teardown_timeout_if_current(
        &self,
        session_id: &SessionId,
        kind: SetupTeardownWatchdogKind,
    ) {
        let timeout = Duration::from_secs(self.config.setup_teardown_timeout_secs);
        if timeout.is_zero() {
            return;
        }

        let Ok((call_state, handle, entered_state_at)) = self
            .helpers
            .state_machine
            .store
            .with_session(session_id, |session| {
                (
                    session.call_state,
                    session.lifecycle_handle.clone(),
                    session.entered_state_at,
                )
            })
        else {
            return;
        };
        if !kind.watched_states().contains(&call_state) {
            return;
        }
        let Some(handle) = handle else {
            return;
        };
        let Some(deadline) = Instant::now().checked_add(timeout) else {
            tracing::error!(
                timeout_secs = self.config.setup_teardown_timeout_secs,
                "setup teardown watchdog deadline overflow"
            );
            return;
        };

        let _ = self
            .setup_teardown_scheduler
            .schedule(deadline, handle, entered_state_at, kind);
    }

    async fn schedule_setup_teardown_timeout_exact_if_current(
        &self,
        handle: &SessionRegistryHandle,
        kind: SetupTeardownWatchdogKind,
    ) {
        let timeout = Duration::from_secs(self.config.setup_teardown_timeout_secs);
        if timeout.is_zero() {
            return;
        }

        let Ok(current) = self
            .helpers
            .state_machine
            .store
            .get_session_snapshot_exact(handle)
        else {
            return;
        };
        if !kind.watched_states().contains(&current.call_state) {
            return;
        }
        let Some(deadline) = Instant::now().checked_add(timeout) else {
            tracing::error!(
                timeout_secs = self.config.setup_teardown_timeout_secs,
                "setup teardown watchdog deadline overflow"
            );
            return;
        };

        let _ = self.setup_teardown_scheduler.schedule(
            deadline,
            handle.clone(),
            current.entered_state_at,
            kind,
        );
    }

    fn setup_teardown_deadline_is_current(&self, deadline: &SetupTeardownDeadline) -> bool {
        self.helpers
            .state_machine
            .store
            .get_session_snapshot_exact(&deadline.handle)
            .is_ok_and(|current| {
                deadline
                    .kind
                    .watched_states()
                    .contains(&current.state().call_state)
                    && current.state().entered_state_at == deadline.entered_state_at
            })
    }

    fn dispatch_setup_teardown_deadline(
        self: &Arc<Self>,
        deadline: SetupTeardownDeadline,
        fire_permit: tokio::sync::OwnedSemaphorePermit,
    ) -> bool {
        let coordinator = Arc::clone(self);
        self.setup_teardown_scheduler
            .spawn_deadline_fire(async move {
                let _fire_permit = fire_permit;
                coordinator.fire_setup_teardown_deadline(deadline).await;
            })
    }

    async fn fire_setup_teardown_deadline(&self, deadline: SetupTeardownDeadline) {
        // Revalidate after task admission. The session can complete between
        // the scheduler's cheap preflight and this cold handler starting.
        let Ok(current) = self
            .helpers
            .state_machine
            .store
            .get_session_snapshot_exact(&deadline.handle)
        else {
            crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
            return;
        };
        let current_state = current.state().call_state;
        if !deadline.kind.watched_states().contains(&current_state)
            || current.state().entered_state_at != deadline.entered_state_at
        {
            crate::cleanup_diag::record_setup_teardown_watchdog_disarmed();
            return;
        }

        #[cfg(test)]
        self.setup_teardown_scheduler
            .pause_if_requested_for_test()
            .await;

        crate::cleanup_diag::record_setup_teardown_watchdog_fired();
        let session_id = deadline.handle.session_id().clone();
        let reason = deadline.kind.reason();
        tracing::warn!(
            "setup teardown watchdog firing for session {} in state {:?}: {}",
            session_id,
            current_state,
            reason
        );

        let state_machine = Arc::clone(&self.helpers.state_machine);
        let helpers = Arc::clone(&self.helpers);
        let dialog_adapter = Arc::clone(&self.dialog_adapter);
        let media_adapter = Arc::clone(&self.media_adapter);
        let pending_exact_responses = Arc::clone(&self.pending_exact_responses);
        let publisher = self.app_event_publisher.clone();
        if let Err(err) = state_machine
            .process_event_exact(&deadline.handle, EventType::DialogTimeout)
            .await
        {
            tracing::warn!(
                "setup teardown watchdog failed for session {} in state {:?}: {}",
                session_id,
                current_state,
                err
            );
            crate::cleanup_diag::record_setup_teardown_watchdog_transition_failed();
            return;
        }

        let Ok(after) = state_machine
            .store
            .get_session_snapshot_exact(&deadline.handle)
        else {
            crate::cleanup_diag::record_setup_teardown_watchdog_transition_failed();
            return;
        };
        if !after.state().call_state.is_final() {
            crate::cleanup_diag::record_setup_teardown_watchdog_transition_failed();
            return;
        }

        let release_guard = crate::cleanup_diag::stage_guard(
            crate::cleanup_diag::CleanupStage::TerminalRelease,
            &session_id.0,
        );
        let claim_owner = match publisher.claim_exact_terminal(&deadline.handle) {
            ExactTerminalClaim::Owner(owner) => owner,
            ExactTerminalClaim::Observer(_) => {
                release_guard.finish_success();
                crate::cleanup_diag::record_setup_teardown_watchdog_release_completed();
                return;
            }
        };
        let api_event = match deadline.kind.terminal() {
            SetupTeardownTimeoutTerminal::Cancelled => crate::api::events::Event::CallCancelled {
                call_id: session_id.clone(),
            },
            SetupTeardownTimeoutTerminal::Failed => crate::api::events::Event::CallFailed {
                call_id: session_id.clone(),
                status_code: 408,
                reason: reason.to_string(),
            },
        };
        if let Err(err) = publisher.publish_terminal_best_effort_exact(&deadline.handle, api_event)
        {
            tracing::warn!(
                "setup teardown watchdog failed to publish terminal event for {}: {}",
                session_id,
                err
            );
        }
        if let Err(error) = release_exact_local_resources(
            Arc::clone(&state_machine.store),
            helpers,
            dialog_adapter,
            media_adapter,
            Some(pending_exact_responses),
            Some(self.setup_teardown_deadline_cancellation()),
            deadline.handle,
        )
        .await
        {
            tracing::debug!(%error, "setup watchdog exact release was incomplete");
            release_guard.finish_failure();
            crate::cleanup_diag::record_setup_teardown_watchdog_release_failed();
            claim_owner.finish(ExactTerminalCompletion::ReleaseFailed);
            return;
        }
        release_guard.finish_success();
        crate::cleanup_diag::record_setup_teardown_watchdog_release_completed();
        claim_owner.finish(ExactTerminalCompletion::Released);
    }

    /// Complete the retained publication/release phase for one exact local
    /// teardown lifetime.
    pub(crate) async fn finalize_local_bye_exact(
        &self,
        handle: &SessionRegistryHandle,
        reason: impl Into<String>,
    ) -> Result<()> {
        let api_event = crate::api::events::Event::CallEnded {
            call_id: handle.session_id().clone(),
            reason: reason.into(),
        };
        self.finalize_local_terminal_exact(handle, api_event).await
    }

    async fn finalize_local_terminal_exact(
        &self,
        handle: &SessionRegistryHandle,
        api_event: crate::api::events::Event,
    ) -> Result<()> {
        let session_id = handle.session_id();
        let release_timeout = self.dialog_adapter.non_invite_transaction_timeout();

        let claim_owner = match self.app_event_publisher.claim_exact_terminal(handle) {
            ExactTerminalClaim::Owner(owner) => {
                tracing::debug!(session = %session_id, "local BYE finalizer owns exact terminal release");
                owner
            }
            ExactTerminalClaim::Observer(observer) => {
                tracing::debug!(session = %session_id, "local BYE finalizer is joining exact terminal release");
                match tokio::time::timeout(release_timeout, observer.wait()).await {
                    Ok(ExactTerminalCompletion::Released) => return Ok(()),
                    Ok(completion) => {
                        tracing::warn!(
                            session = %session_id,
                            ?completion,
                            "local BYE terminal owner did not release exact resources; taking over cleanup"
                        );
                    }
                    Err(_) => {
                        tracing::warn!(
                            session = %session_id,
                            timeout_ms = release_timeout.as_millis(),
                            "local BYE terminal owner exceeded its deadline; taking over exact cleanup"
                        );
                    }
                }
                let release_guard = crate::cleanup_diag::stage_guard(
                    crate::cleanup_diag::CleanupStage::TerminalRelease,
                    &session_id.0,
                );
                let release = release_exact_local_resources_with_retry(
                    Arc::clone(&self.helpers.state_machine.store),
                    Arc::clone(&self.helpers),
                    Arc::clone(&self.dialog_adapter),
                    Arc::clone(&self.media_adapter),
                    Some(Arc::clone(&self.pending_exact_responses)),
                    Some(self.setup_teardown_deadline_cancellation()),
                    handle.clone(),
                )
                .await;
                match release {
                    Ok(()) => release_guard.finish_success(),
                    Err(_) => release_guard.finish_failure(),
                }
                return release;
            }
        };

        let release_guard = crate::cleanup_diag::stage_guard(
            crate::cleanup_diag::CleanupStage::TerminalRelease,
            &session_id.0,
        );

        if let Err(err) = self
            .app_event_publisher
            .publish_terminal_best_effort_exact(handle, api_event)
        {
            tracing::warn!(
                error_class = "app-event-publication",
                "Local BYE terminal event publication failed after lifecycle admission: {}",
                err
            );
        }
        if let Err(error) = release_exact_local_resources_with_retry(
            Arc::clone(&self.helpers.state_machine.store),
            Arc::clone(&self.helpers),
            Arc::clone(&self.dialog_adapter),
            Arc::clone(&self.media_adapter),
            Some(Arc::clone(&self.pending_exact_responses)),
            Some(self.setup_teardown_deadline_cancellation()),
            handle.clone(),
        )
        .await
        {
            release_guard.finish_failure();
            claim_owner.finish(ExactTerminalCompletion::ReleaseFailed);
            return Err(error);
        }
        release_guard.finish_success();
        claim_owner.finish(ExactTerminalCompletion::Released);
        Ok(())
    }

    /// Await the exact peer response before acknowledging local BYE teardown.
    /// A 2xx is confirmed receipt and an exact 481 is graceful
    /// already-terminated completion under RFC 3261 §15.1.1. Local resources
    /// are reclaimed on every outcome, but any other timeout or non-2xx
    /// remains visible to the caller as wire failure.
    pub(crate) async fn finalize_confirmed_local_bye_exact(
        &self,
        handle: &SessionRegistryHandle,
        reason: impl Into<String>,
    ) -> Result<()> {
        let reason = reason.into();
        let confirmation = self
            .dialog_adapter
            .wait_for_outgoing_bye_final_response_exact(handle)
            .await;
        let lifecycle_commit =
            commit_local_bye_lifecycle_exact(Arc::clone(&self.helpers.state_machine), handle).await;
        let finalization = match lifecycle_commit {
            Ok(LocalByeLifecycleCommit::Ended | LocalByeLifecycleCommit::AlreadyReleased) => {
                self.finalize_local_bye_exact(handle, reason).await
            }
            Ok(LocalByeLifecycleCommit::Cancelled) => {
                self.finalize_local_terminal_exact(
                    handle,
                    crate::api::events::Event::CallCancelled {
                        call_id: handle.session_id().clone(),
                    },
                )
                .await
            }
            Err(lifecycle_error) => {
                if let Err(cleanup_error) = self.finalize_local_bye_exact(handle, reason).await {
                    tracing::debug!(
                        %cleanup_error,
                        "local SIP cleanup was incomplete after BYE lifecycle failure"
                    );
                }
                Err(lifecycle_error)
            }
        };
        match confirmation {
            Ok(()) => finalization,
            Err(error) => {
                if let Err(cleanup_error) = finalization {
                    tracing::debug!(
                        %cleanup_error,
                        "local SIP cleanup was incomplete after BYE confirmation failure"
                    );
                }
                Err(error)
            }
        }
    }

    /// Dispatch a builder-owned established BYE and join the exact wire
    /// confirmation even when a synchronous response wins the state-store
    /// bookkeeping race. The wait owner makes cancellation between dispatch
    /// and confirmation reclaim the retained receipt synchronously.
    pub(crate) async fn dispatch_confirmed_outbound_bye(
        &self,
        session_id: &SessionId,
        slot: crate::state_machine::executor::PendingOptionsSlot,
    ) -> Result<()> {
        let handle = self
            .helpers
            .state_machine
            .store
            .lifecycle_handle(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.to_string()))?;
        self.dispatch_confirmed_outbound_bye_exact(&handle, slot)
            .await
    }

    pub(crate) async fn dispatch_confirmed_outbound_bye_exact(
        &self,
        handle: &SessionRegistryHandle,
        slot: crate::state_machine::executor::PendingOptionsSlot,
    ) -> Result<()> {
        // The state-machine task retains this same logical wait owner until
        // it has either stopped before claim or completed the claimed
        // wire-to-receipt handoff. If the public builder is cancelled after
        // claim, its alias disappears but the detached task's alias prevents
        // the last-owner cleanup from running just before a late receipt is
        // published.
        let bye_wait_owner = Arc::new(self.dialog_adapter.begin_outgoing_bye_wait_exact(handle)?);
        let generation_before_dispatch = self
            .dialog_adapter
            .outgoing_bye_generation_exact(handle)
            .unwrap_or(0);
        let dispatch = self
            .dispatch_outbound_with_options_and_input_exact(
                handle,
                EventType::SendOutboundBye,
                slot,
                None,
                Some(Arc::clone(&bye_wait_owner)),
            )
            .await
            .map(|_| ());
        let retained_new_bye = self
            .dialog_adapter
            .has_outgoing_bye_after_exact(handle, generation_before_dispatch);
        complete_established_bye_dispatch(
            dispatch,
            retained_new_bye,
            self.finalize_confirmed_local_bye_exact(handle, "Local BYE"),
        )
        .await
    }

    /// Begin authoritative local reclamation without publishing an app event.
    ///
    /// Capture forced reclamation for one already-qualified lifetime.
    ///
    /// Retained adapter cleanup must use this entry point: resolving a raw
    /// identifier after a timeout could otherwise select a replacement
    /// lifetime admitted while the old cleanup was delayed.
    pub(crate) async fn begin_force_reclaim_local_session_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> ForcedLocalSessionCleanup {
        let release_guard = crate::cleanup_diag::stage_guard(
            crate::cleanup_diag::CleanupStage::TerminalRelease,
            &handle.session_id().0,
        );

        let session_store = Arc::clone(&self.helpers.state_machine.store);
        release_guard.finish_success();
        ForcedLocalSessionCleanup {
            handle: Some(handle.clone()),
            helpers: Arc::clone(&self.helpers),
            dialog_adapter: Arc::clone(&self.dialog_adapter),
            media_adapter: Arc::clone(&self.media_adapter),
            pending_exact_responses: Arc::clone(&self.pending_exact_responses),
            setup_teardown_deadlines: self.setup_teardown_deadline_cancellation(),
            session_store,
        }
    }

    /// Bridge the RTP streams of two active sessions at the media layer.
    ///
    /// Transparent packet-level relay: inbound RTP from session A is
    /// forwarded as outbound RTP on session B and vice versa, without
    /// transcoding. Intended for b2bua-style consumers that need to connect
    /// two SIP legs without shuffling AudioFrames through app code.
    ///
    /// # Preconditions
    ///
    /// - Both sessions must exist and be in `CallState::Active` (i.e. have
    ///   a negotiated remote RTP address).
    /// - Both sessions must have negotiated the same codec payload type.
    ///   Codec mismatch returns [`BridgeError::CodecMismatch`].
    /// - Neither session may already be bridged.
    ///
    /// Dropping the returned [`BridgeHandle`] tears the bridge down. DTMF
    /// (RFC 2833) rides the RTP stream and is forwarded transparently;
    /// RTCP is not bridged — each leg keeps generating its own reports.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, a: rvoip_sip::SessionId, b: rvoip_sip::SessionId) -> Result<(), rvoip_sip::BridgeError> {
    /// let bridge = coordinator.bridge(&a, &b).await?;
    /// // Keep `bridge` alive for as long as the RTP relay should run.
    /// drop(bridge);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn bridge(
        &self,
        session_a: &SessionId,
        session_b: &SessionId,
    ) -> std::result::Result<BridgeHandle, BridgeError> {
        self.media_adapter
            .bridge_rtp_sessions(session_a, session_b)
            .await
    }

    /// Ask the peer of `session` to change the codec mode it transmits.
    ///
    /// AMR only for now: this emits a Codec Mode Request (RFC 4867 §3.4.1) on
    /// the next outgoing payload, asking the peer to switch to `mode_index`.
    /// The peer may decline. Returns `Ok(false)` when the session has no
    /// active media; other codecs accept the call and no-op.
    ///
    /// Confirm the peer honoured it with [`peer_codec_mode`](Self::peer_codec_mode).
    pub async fn request_peer_codec_mode(
        &self,
        session: &SessionId,
        mode_index: u8,
    ) -> std::result::Result<bool, SessionError> {
        self.media_adapter
            .request_peer_codec_mode(session, mode_index)
            .await
    }

    /// The codec mode of the last speech frame decoded from `session`'s peer,
    /// or `None` when there is no media or the codec tracks no mode. For AMR
    /// this is how a caller sees whether a
    /// [`request_peer_codec_mode`](Self::request_peer_codec_mode) took effect.
    pub async fn peer_codec_mode(&self, session: &SessionId) -> Option<u8> {
        self.media_adapter.peer_codec_mode(session).await
    }

    /// Send a reliable 183 Session Progress with early-media SDP (RFC 3262).
    ///
    /// - `sdp: Some(body)` sends the supplied SDP verbatim.
    /// - `sdp: None` generates an answer from the stored remote offer via
    ///   `MediaAdapter::negotiate_sdp_as_uas` (same path as `accept_call`).
    ///
    /// Fails fast with `UnreliableProvisionalsNotSupported` when the peer
    /// did not advertise `Supported: 100rel` on the INVITE. Transitions the
    /// session to `CallState::EarlyMedia`. Valid from `Ringing` and
    /// `EarlyMedia` (re-emission updates the SDP and bumps `RSeq`).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, incoming: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.send_early_media(&incoming, None).await?;
    /// coordinator.accept_call(&incoming).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn send_early_media(
        &self,
        session_id: &SessionId,
        sdp: Option<String>,
    ) -> Result<()> {
        if !self.dialog_adapter.peer_supports_100rel(session_id).await? {
            return Err(SessionError::UnreliableProvisionalsNotSupported);
        }
        self.helpers.send_early_media(session_id, sdp).await
    }

    /// Swap the audio source on the running transmitter for a session.
    ///
    /// Typical use: after [`send_early_media`][Self::send_early_media] has
    /// put the session into `EarlyMedia` (which starts a pass-through
    /// transmitter by default), call this to replace silence with a
    /// ringback tone, a "please hold" WAV, or any other
    /// [`AudioSource`] variant.
    ///
    /// On transition to `Active` (after `accept_call`), the state machine
    /// automatically swaps the transmitter back to `AudioSource::PassThrough`
    /// so bidirectional audio flows without further action from the app.
    /// Apps that want a *different* source after answer (e.g., continued
    /// announcement playback over an active call) should call this method
    /// again *after* the `CallEstablished` event fires.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// use rvoip_sip::AudioSource;
    ///
    /// coordinator.set_audio_source(
    ///     &call_id,
    ///     AudioSource::Tone { frequency: 440.0, amplitude: 0.4 },
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn set_audio_source(
        &self,
        session_id: &SessionId,
        source: AudioSource,
    ) -> Result<()> {
        self.media_adapter
            .set_audio_source(session_id, source)
            .await
    }

    /// Put a call on hold.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.hold(&call_id).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn hold(&self, session_id: &SessionId) -> Result<()> {
        self.helpers
            .state_machine
            .process_event(session_id, EventType::HoldCall)
            .await?;
        Ok(())
    }

    pub(crate) async fn hold_exact(&self, handle: &SessionRegistryHandle) -> Result<()> {
        self.helpers
            .state_machine
            .process_event_exact(handle, EventType::HoldCall)
            .await?;
        Ok(())
    }

    /// Resume a call from hold.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.resume(&call_id).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn resume(&self, session_id: &SessionId) -> Result<()> {
        self.helpers
            .state_machine
            .process_event(session_id, EventType::ResumeCall)
            .await?;
        Ok(())
    }

    pub(crate) async fn resume_exact(&self, handle: &SessionRegistryHandle) -> Result<()> {
        self.helpers
            .state_machine
            .process_event_exact(handle, EventType::ResumeCall)
            .await?;
        Ok(())
    }

    // ===== Conference Operations =====

    /// Create a conference from an active call.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, host: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.create_conference(&host, "support-bridge").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn create_conference(&self, session_id: &SessionId, name: &str) -> Result<()> {
        self.helpers.create_conference(session_id, name).await
    }

    /// Add a participant to a conference hosted by another active session.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, host: rvoip_sip::SessionId, participant: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.add_to_conference(&host, &participant).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn add_to_conference(
        &self,
        host_session_id: &SessionId,
        participant_session_id: &SessionId,
    ) -> Result<()> {
        self.helpers
            .add_to_conference(host_session_id, participant_session_id)
            .await
    }

    /// Join an existing conference by conference id.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.join_conference(&call_id, "support-bridge").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn join_conference(&self, session_id: &SessionId, conference_id: &str) -> Result<()> {
        self.helpers
            .state_machine
            .process_event(
                session_id,
                EventType::JoinConference {
                    conference_id: conference_id.to_string(),
                },
            )
            .await?;
        Ok(())
    }

    // ===== Event System Integration =====
    // Callback registry removed - using event-driven approach via SimplePeer

    /// Materialize a [`SessionHandle`](crate::api::handle::SessionHandle)
    /// for an existing call_id.
    ///
    /// Returns a handle for invoking control APIs (hangup, hold, resume,
    /// DTMF, …) on a session created via the canonical builder chain
    /// (`coord.invite(...).send()` returns a [`CallId`](crate::api::handle::CallId);
    /// pair it with this helper to get the rich `SessionHandle` for
    /// in-call control).
    pub fn session(
        self: &Arc<Self>,
        call_id: &crate::api::handle::CallId,
    ) -> crate::api::handle::SessionHandle {
        crate::api::handle::SessionHandle::new(call_id.clone(), self.clone())
    }

    /// Terminate the current session tracked by the session store.
    ///
    /// This is an advanced compatibility helper for single-session flows. New
    /// code should usually hold the specific [`SessionId`] and call
    /// [`hangup`](Self::hangup).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>) -> rvoip_sip::Result<()> {
    /// coordinator.terminate_current_session().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn terminate_current_session(&self) -> Result<()> {
        // Get the current session ID
        if let Some(session_id) = self
            .helpers
            .state_machine
            .store
            .get_current_session_id()
            .await
        {
            self.hangup(&session_id).await
        } else {
            Ok(()) // No session to terminate
        }
    }

    /// Accept a pending inbound REFER request and send RFC 3515 acceptance
    /// responses/NOTIFYs through the state machine.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// // Call this after receiving Event::ReferReceived for `call_id`.
    /// coordinator.accept_refer(&call_id).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn accept_refer(&self, session_id: &SessionId) -> Result<()> {
        let handle = self
            .helpers
            .state_machine
            .store
            .lifecycle_handle(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.to_string()))?;
        self.accept_refer_exact(&handle).await
    }

    pub(crate) async fn accept_refer_exact(&self, handle: &SessionRegistryHandle) -> Result<()> {
        let session_id = handle.session_id();
        let (refer_to, transaction_id) = self
            .helpers
            .state_machine
            .store
            .get_session_snapshot_exact(handle)
            .map(|session| {
                let refer_to = session.transfer_target.clone().ok_or_else(|| {
                    SessionError::Other(format!(
                        "No pending REFER target for session {}",
                        session_id
                    ))
                })?;
                let transaction_id = session.refer_transaction_id.clone().ok_or_else(|| {
                    SessionError::Other(format!(
                        "No pending REFER transaction for session {}",
                        session_id
                    ))
                })?;
                Ok::<_, SessionError>((refer_to, transaction_id))
            })??;

        self.helpers
            .state_machine
            .process_event_exact(
                handle,
                EventType::TransferRequested {
                    refer_to,
                    transfer_type: "blind".to_string(),
                    transaction_id: transaction_id.clone(),
                },
            )
            .await?;

        Ok(())
    }

    /// Reject a pending inbound REFER request with a final response.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.reject_refer(&call_id, 603, "Decline").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn reject_refer(
        &self,
        session_id: &SessionId,
        status_code: u16,
        reason: &str,
    ) -> Result<()> {
        let _reason_present = !reason.is_empty();
        self.helpers
            .state_machine
            .reject_refer(session_id, status_code)
            .await
            .map_err(|error| {
                if let Ok(typed) = error.downcast::<SessionError>() {
                    *typed
                } else {
                    SessionError::InternalError(
                        "failed to reject pending REFER transaction".to_string(),
                    )
                }
            })
    }

    pub(crate) async fn reject_refer_exact(
        &self,
        handle: &SessionRegistryHandle,
        status_code: u16,
        reason: &str,
    ) -> Result<()> {
        let _reason_present = !reason.is_empty();
        self.helpers
            .state_machine
            .reject_refer_exact(handle, status_code)
            .await
            .map_err(|error| {
                if let Ok(typed) = error.downcast::<SessionError>() {
                    *typed
                } else {
                    SessionError::InternalError(
                        "failed to reject pending REFER transaction".to_string(),
                    )
                }
            })
    }

    /// Send a REFER progress NOTIFY with a SIP status code and reason.
    ///
    /// This is the low-level helper for custom REFER orchestration. Transfer
    /// legs created with [`make_transfer_leg`](Self::make_transfer_leg)
    /// emit ordinary REFER progress automatically.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.send_refer_notify(&call_id, 180, "Ringing").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn send_refer_notify(
        &self,
        session_id: &SessionId,
        status_code: u16,
        reason: &str,
    ) -> Result<()> {
        self.dialog_adapter
            .send_refer_notify(session_id, status_code, reason)
            .await
    }

    /// Fetch the SIP-level identity (`Call-ID`, local/remote tags) of a
    /// session's dialog. Returns `None` if the dialog isn't established
    /// yet or has already been cleaned up.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// if let Some(identity) = coordinator.dialog_identity(&call_id).await? {
    ///     if let Some(replaces) = identity.to_replaces_value() {
    ///         println!("Replaces value: {replaces}");
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn dialog_identity(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<crate::api::types::DialogIdentity>> {
        self.dialog_adapter.dialog_identity(session_id).await
    }

    pub(crate) async fn dialog_identity_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Result<Option<crate::api::types::DialogIdentity>> {
        self.dialog_adapter.dialog_identity_exact(handle).await
    }

    // ===== DTMF Operations =====

    /// Send a single RFC 4733 DTMF digit over the active media session
    /// at a 100 ms default duration (suitable for interactive softphone
    /// use).
    ///
    /// Goes directly through [`MediaAdapter::send_dtmf_rfc4733`] rather
    /// than the state machine: DTMF is an in-call side-effect, not a
    /// state transition, and the state table does not (intentionally)
    /// enumerate a SendDTMF transition. The media adapter resolves
    /// `session_id → dialog_id`, encodes the RFC 4733 telephone-event
    /// payload, and transmits with PT 101 over the existing RTP
    /// session.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.send_dtmf(&call_id, '5').await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn send_dtmf(&self, session_id: &SessionId, digit: char) -> Result<()> {
        self.media_adapter
            .send_dtmf_rfc4733(session_id, digit, 100)
            .await
    }

    pub(crate) async fn send_dtmf_exact(
        &self,
        handle: &SessionRegistryHandle,
        digit: char,
    ) -> Result<()> {
        self.media_adapter
            .send_dtmf_rfc4733_exact(handle, digit, 100)
            .await
    }

    /// Send a bounded RFC 4733 sequence with caller-selected tone duration
    /// and quiet time between digits.
    ///
    /// The complete sequence is validated before any RTP is emitted. This is
    /// the transport-specific primitive used by the generic connection
    /// adapter; single-digit callers may continue using [`Self::send_dtmf`].
    pub async fn send_dtmf_sequence(
        &self,
        session_id: &SessionId,
        digits: &str,
        duration_ms: u32,
        inter_digit_ms: u32,
    ) -> Result<()> {
        self.media_adapter
            .send_dtmf_sequence_rfc4733(session_id, digits, duration_ms, inter_digit_ms)
            .await
    }

    // ===== Recording Operations =====

    /// Start recording a call.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.start_recording(&call_id).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn start_recording(&self, session_id: &SessionId) -> Result<()> {
        self.helpers
            .state_machine
            .process_event(session_id, EventType::StartRecording)
            .await?;
        Ok(())
    }

    /// Stop recording a call.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// coordinator.stop_recording(&call_id).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn stop_recording(&self, session_id: &SessionId) -> Result<()> {
        self.helpers
            .state_machine
            .process_event(session_id, EventType::StopRecording)
            .await?;
        Ok(())
    }

    // ===== Query Operations =====

    /// Get detailed session information.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// let info = coordinator.get_session_info(&call_id).await?;
    /// println!("session state: {:?}", info.state);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_session_info(&self, session_id: &SessionId) -> Result<SessionInfo> {
        self.helpers.get_session_info(session_id).await
    }

    pub(crate) async fn get_session_info_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Result<SessionInfo> {
        self.helpers.get_session_info_exact(handle).await
    }

    /// List all active sessions.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>) {
    /// let sessions = coordinator.list_sessions().await;
    /// println!("active sessions: {}", sessions.len());
    /// # }
    /// ```
    pub async fn list_sessions(&self) -> Vec<SessionInfo> {
        self.helpers.list_sessions().await
    }

    /// Get the current state of a session.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// let state = coordinator.get_state(&call_id).await?;
    /// println!("call state: {state:?}");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_state(&self, session_id: &SessionId) -> Result<CallState> {
        self.helpers.get_state(session_id).await
    }

    pub(crate) async fn get_state_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Result<CallState> {
        self.helpers.get_state_exact(handle).await
    }

    /// Check whether a session is in a conference.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// if coordinator.is_in_conference(&call_id).await? {
    ///     println!("call is in a conference");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn is_in_conference(&self, session_id: &SessionId) -> Result<bool> {
        self.helpers.is_in_conference(session_id).await
    }

    // ===== Audio Operations =====

    /// Subscribe to decoded audio frames for a session.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// let mut audio = coordinator.subscribe_to_audio(&call_id).await?;
    /// tokio::spawn(async move {
    ///     while let Some(frame) = audio.receiver.recv().await {
    ///         println!("received {} samples", frame.samples.len());
    ///     }
    /// });
    /// # Ok(())
    /// # }
    /// ```
    pub async fn subscribe_to_audio(
        &self,
        session_id: &SessionId,
    ) -> Result<crate::types::AudioFrameSubscriber> {
        self.media_adapter
            .subscribe_to_audio_frames(session_id)
            .await
    }

    pub(crate) async fn subscribe_to_audio_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Result<crate::types::AudioFrameSubscriber> {
        self.media_adapter
            .subscribe_to_audio_frames_exact(handle)
            .await
    }

    /// Send an encoded/decoded audio frame to a session's media path.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) -> rvoip_sip::Result<()> {
    /// let frame = rvoip_media_core::types::AudioFrame::new(vec![0i16; 160], 8000, 1, 0);
    /// coordinator.send_audio(&call_id, frame).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn send_audio(&self, session_id: &SessionId, frame: AudioFrame) -> Result<()> {
        self.media_adapter.send_audio_frame(session_id, frame).await
    }

    pub(crate) async fn send_audio_exact(
        &self,
        handle: &SessionRegistryHandle,
        frame: AudioFrame,
    ) -> Result<()> {
        self.media_adapter
            .send_audio_frame_exact(handle, frame)
            .await
    }

    pub(crate) async fn set_audio_source_exact(
        &self,
        handle: &SessionRegistryHandle,
        source: AudioSource,
    ) -> Result<()> {
        self.media_adapter
            .set_audio_source_exact(handle, source)
            .await
    }

    /// Resolve the exact SDP-negotiated media format for a live session.
    ///
    /// This is crate-private because transport-neutral callers consume the
    /// resulting [`crate::media_stream::SipMediaStream`] codec descriptor.
    pub(crate) async fn negotiated_media_config(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<(crate::session_store::state::NegotiatedConfig, u8)>> {
        self.helpers.negotiated_media_config(session_id).await
    }

    // ===== Event Subscriptions =====

    /// Subscribe a callback to low-level state-machine session events.
    ///
    /// This is an advanced compatibility hook. New application code should
    /// prefer [`events`](Self::events) or [`events_for_session`](Self::events_for_session).
    ///
    /// Renamed from `subscribe(...)` per SIP_API_DESIGN_2.md Phase 12: the
    /// bare `subscribe` entry now names the SUBSCRIBE-method verb-builder.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) {
    /// coordinator.on_session_events(call_id, |_event| {
    ///     // Observe low-level state-machine events.
    /// }).await;
    /// # }
    /// ```
    pub async fn on_session_events<F>(&self, session_id: SessionId, callback: F)
    where
        F: Fn(crate::state_machine::helpers::SessionEvent) + Send + Sync + 'static,
    {
        self.helpers.subscribe(session_id, callback).await
    }

    /// Unsubscribe from low-level state-machine events for a session.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, call_id: rvoip_sip::SessionId) {
    /// coordinator.unsubscribe(&call_id).await;
    /// # }
    /// ```
    pub async fn unsubscribe(&self, session_id: &SessionId) {
        self.helpers.unsubscribe(session_id).await
    }

    // ===== Incoming Call Handling =====

    /// Get the next low-level incoming call notification.
    ///
    /// This is the coordinator primitive underneath
    /// [`StreamPeer::wait_for_incoming`](crate::api::stream_peer::StreamPeer::wait_for_incoming).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>) {
    /// if let Some(incoming) = coordinator.get_incoming_call().await {
    ///     println!("incoming call from {}", incoming.from);
    /// }
    /// # }
    /// ```
    pub async fn get_incoming_call(&self) -> Option<IncomingCallInfo> {
        self.incoming_rx.write().await.recv().await
    }

    /// Wait for the next incoming INVITE and return the controllable
    /// [`IncomingCall`](crate::IncomingCall) wrapper.
    ///
    /// Open this wait before the caller sends the INVITE. Like
    /// [`events`](Self::events), incoming-call notifications are broadcast
    /// events and are not replayed to late subscribers.
    ///
    /// This is the UnifiedCoordinator equivalent of
    /// [`StreamPeer::wait_for_incoming`](crate::StreamPeer::wait_for_incoming)
    /// for applications that want direct coordinator control plus inbound auth
    /// helpers such as
    /// [`IncomingCall::authenticate_with`](crate::IncomingCall::authenticate_with).
    pub async fn wait_for_incoming_call(
        self: &Arc<Self>,
    ) -> Result<crate::api::incoming::IncomingCall> {
        let mut events = self.events().await?;
        self.next_incoming_call(&mut events)
            .await?
            .ok_or_else(|| SessionError::Other("Event channel closed".to_string()))
    }

    /// Return the next incoming INVITE from an existing event receiver.
    ///
    /// Use this when a server may challenge a request and then receive an
    /// immediate retry. Keeping one receiver open avoids missing the retry
    /// event between separate subscriptions.
    pub async fn next_incoming_call(
        self: &Arc<Self>,
        events: &mut crate::api::stream_peer::EventReceiver,
    ) -> Result<Option<crate::api::incoming::IncomingCall>> {
        // `events()` is intentionally observation-only for monitoring callers,
        // but this control-producing primitive needs the exact private stream
        // to preserve the inbound lifecycle authority and request bundle.
        events.ensure_control(self).await?;
        let Some((call_id, from, to, sdp, lifecycle_handle)) = events.next_incoming_exact().await
        else {
            return Ok(None);
        };

        let pending = lifecycle_handle
            .as_ref()
            .and_then(|handle| self.pending_incoming_bundle_for_handle_exact(handle));
        let parsed = pending.as_ref().and_then(|bundle| bundle.request.clone());
        let transport = pending.and_then(|bundle| bundle.transport);
        let incoming = match parsed {
            Some(req) => crate::api::incoming::IncomingCall::with_request_captured(
                call_id,
                from,
                to,
                sdp,
                self.clone(),
                req,
                lifecycle_handle,
            ),
            None => crate::api::incoming::IncomingCall::new_captured(
                call_id,
                from,
                to,
                sdp,
                self.clone(),
                lifecycle_handle,
            ),
        }
        .with_transport_context(
            transport
                .as_deref()
                .cloned()
                .unwrap_or_else(crate::auth::SipTransportSecurityContext::unknown),
        );
        Ok(Some(incoming))
    }

    pub(crate) fn pending_incoming_bundle_for_handle_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Option<PendingInboundBundle> {
        self.session_registry
            .pending_bundle_exact(handle.key(), handle.slot_revision())
            .ok()
    }

    // ===== Auto-Transfer Handling =====

    /// Enable automatic blind transfer handling - DISABLED
    /// Auto-transfer now handled in SessionEventHandler to avoid event stealing
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>) {
    /// coordinator.enable_auto_transfer();
    /// # }
    /// ```
    pub fn enable_auto_transfer(self: &Arc<Self>) {
        tracing::info!("🔄 Auto-transfer: handled by SessionEventHandler");
    }

    // extract_field method removed - no longer needed without transfer coordinator

    // ===== Server-Side Registration =====

    /// Start server-side registration handling
    ///
    /// This creates and starts a RegistrationAdapter that handles incoming REGISTER
    /// requests on the authoritative typed dialog-to-session route. The registrar
    /// service authenticates users and manages registrations.
    ///
    /// # Arguments
    /// * `realm` - The SIP realm for digest authentication (e.g., "example.com")
    /// * `users` - Map of username -> password for authentication
    ///
    /// # Returns
    ///
    /// `Arc<RegistrarService>` for inspecting and managing registrations.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>) -> rvoip_sip::Result<()> {
    /// let users = std::collections::HashMap::from([
    ///     ("alice".to_string(), "secret".to_string()),
    /// ]);
    /// let registrar = coordinator.start_registration_server("example.com", users).await?;
    /// # let _ = registrar;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn start_registration_server(
        &self,
        realm: &str,
        users: std::collections::HashMap<String, String>,
    ) -> Result<Arc<rvoip_sip_registrar::RegistrarService>> {
        use crate::adapters::RegistrationAdapter;
        use rvoip_sip_registrar::{api::ServiceMode, types::RegistrarConfig, RegistrarService};

        tracing::info!(
            "🔐 Starting server-side registration handler with realm: {}",
            realm
        );

        // Create registrar service with authentication
        let registrar =
            RegistrarService::with_auth(ServiceMode::B2BUA, RegistrarConfig::default(), realm)
                .await
                .map_err(|e| {
                    SessionError::InternalError(format!("Failed to create registrar: {}", e))
                })?;

        // Add users to the registrar
        if let Some(user_store) = registrar.user_store() {
            for (username, password) in users {
                user_store.add_user(&username, &password).map_err(|e| {
                    SessionError::InternalError(format!("Failed to add user: {}", e))
                })?;
                tracing::debug!("Added user: {}", username);
            }
        }

        let registrar = Arc::new(registrar);

        // Install the registration adapter through THIS coordinator's one
        // authoritative dialog-to-session handler. The private installation
        // event is never copied to the observational bus.
        let global_coordinator = self.global_coordinator.clone();

        // Create and start the registration adapter
        let adapter = Arc::new(RegistrationAdapter::with_dialog_adapter(
            registrar.clone(),
            global_coordinator,
            Arc::clone(&self.dialog_adapter),
        ));

        adapter.start().await.map_err(|e| {
            SessionError::InternalError(format!("Failed to start registration adapter: {}", e))
        })?;

        tracing::info!("✅ Server-side registration handler started");

        Ok(registrar)
    }

    pub(crate) async fn send_register_response_fields(
        &self,
        fields: &crate::api::respond::register_response::RegisterResponseEventFields,
    ) -> Result<()> {
        self.dialog_adapter
            .send_register_response_fields(fields)
            .await
    }

    // ===== Internal Helpers =====

    async fn create_dialog_api(
        config: &Config,
        global_coordinator: Arc<GlobalEventCoordinator>,
        sip_trace_owner_id: Option<String>,
        listener_auth_policy: crate::auth::SipListenerAuthPolicy,
    ) -> Result<Arc<rvoip_sip_dialog::api::unified::UnifiedDialogApi>> {
        use rvoip_sip_dialog::api::unified::UnifiedDialogApi;
        use rvoip_sip_dialog::config::DialogManagerConfig;
        use rvoip_sip_dialog::transaction::{
            transport::{TransportManager, TransportManagerConfig},
            TransactionManager,
        };

        // Create transport manager first (rvoip-sip-dialog's own transport manager).
        //
        // TCP is enabled by default — the URI-aware
        // `MultiplexedTransport` (`crates/sip/rvoip-sip-dialog/src/transaction/transport/multiplexed.rs`)
        // routes outbound INVITEs to the right flavour based on the
        // Request-URI's scheme + `;transport=` parameter.
        //
        let effective_tls_mode = config.effective_tls_mode();
        let enable_tls = effective_tls_mode != SipTlsMode::Disabled;
        if config.tls_cert_path.is_some() ^ config.tls_key_path.is_some() {
            tracing::warn!(
                "rvoip-sip Config has tls_cert_path xor tls_key_path set; \
                 TLS listener roles require both"
            );
        }
        if matches!(
            effective_tls_mode,
            SipTlsMode::ServerOnly | SipTlsMode::ClientAndServer
        ) && (config.tls_cert_path.is_none() || config.tls_key_path.is_none())
        {
            return Err(SessionError::ConfigError(
                "SIP TLS listener modes require tls_cert_path and tls_key_path".to_string(),
            ));
        }
        if config.tls_client_cert_path.is_some() ^ config.tls_client_key_path.is_some() {
            return Err(SessionError::ConfigError(
                "TLS client certificate and key must be provided together".to_string(),
            ));
        }

        let tls_role = match effective_tls_mode {
            SipTlsMode::Disabled => {
                rvoip_sip_dialog::transaction::transport::TlsRole::ClientAndServer
            }
            SipTlsMode::ClientOnly => rvoip_sip_dialog::transaction::transport::TlsRole::ClientOnly,
            SipTlsMode::ServerOnly => rvoip_sip_dialog::transaction::transport::TlsRole::ServerOnly,
            SipTlsMode::ClientAndServer => {
                rvoip_sip_dialog::transaction::transport::TlsRole::ClientAndServer
            }
        };
        if matches!(effective_tls_mode, SipTlsMode::ClientOnly) {
            tracing::info!(
                "SIP TLS client-only mode enabled; no local endpoint certificate/key required"
            );
        }
        let transport_config = TransportManagerConfig {
            enable_udp: true,
            enable_tcp: true,
            enable_ws: false,
            enable_tls,
            tls_role,
            bind_addresses: vec![config.bind_addr],
            tls_bind_addresses: config.tls_bind_addr.into_iter().collect(),
            tls_cert_path: config
                .tls_cert_path
                .as_ref()
                .map(|p| p.to_string_lossy().into_owned()),
            tls_key_path: config
                .tls_key_path
                .as_ref()
                .map(|p| p.to_string_lossy().into_owned()),
            tls_client_cert_path: config
                .tls_client_cert_path
                .as_ref()
                .map(|p| p.to_string_lossy().into_owned()),
            tls_client_key_path: config
                .tls_client_key_path
                .as_ref()
                .map(|p| p.to_string_lossy().into_owned()),
            tls_server_client_auth: config.tls_server_client_auth.clone(),
            tls_extra_ca_path: config
                .tls_extra_ca_path
                .as_ref()
                .map(|p| p.to_string_lossy().into_owned()),
            default_channel_capacity: config.sip_transport_channel_capacity,
            udp_recv_buffer_size: config.sip_udp_recv_buffer_size,
            udp_send_buffer_size: config.sip_udp_send_buffer_size,
            udp_parse_workers: config.sip_udp_parse_workers,
            udp_parse_queue_capacity: config.sip_udp_parse_queue_capacity,
            udp_parse_dispatch: config.sip_udp_parse_dispatch,
            transport_event_dispatch_workers: config.sip_transport_dispatch_workers,
            transport_event_dispatch_queue_capacity: config.sip_transport_dispatch_queue_capacity,
            // Default build: `Config::tls_insecure_skip_verify` is not
            // compiled, so we always pass `false`. Only the
            // `dev-insecure-tls` build surfaces the field.
            #[cfg(feature = "dev-insecure-tls")]
            tls_insecure_skip_verify: config.tls_insecure_skip_verify,
            #[cfg(not(feature = "dev-insecure-tls"))]
            tls_insecure_skip_verify: false,
        };

        let dialog_tls_local_address = config.tls_bind_addr.or_else(|| {
            if matches!(
                effective_tls_mode,
                SipTlsMode::ServerOnly | SipTlsMode::ClientAndServer
            ) {
                let mut tls_addr = config.bind_addr;
                if tls_addr.port() != 0 {
                    tls_addr.set_port(tls_addr.port().saturating_add(1));
                }
                Some(tls_addr)
            } else {
                None
            }
        });

        let (mut transport_manager, transport_event_rx) =
            TransportManager::new(transport_config).await.map_err(|e| {
                SessionError::InternalError(format!("Failed to create transport manager: {}", e))
            })?;

        if let Some(owner_id) = sip_trace_owner_id {
            // SIP_API_DESIGN_2 §12.4 — always install an effective redactor.
            // Missing configuration resolves to the production-safe default;
            // verbatim tracing requires an explicit PassthroughRedactor.
            // The transform runs at the trace boundary in
            // SipTraceRuntime::publish; the wire form is unaffected.
            let redactor = config
                .trace_redaction
                .clone()
                .unwrap_or_else(crate::api::trace_redactor::default_trace_redactor);
            let redactor_fn: Option<rvoip_sip_dialog::transaction::transport::TraceRedactorFn> =
                Some(Arc::new(move |raw: &str| -> String {
                    crate::api::trace_redactor::apply_message_redactor(redactor.as_ref(), raw)
                }));

            transport_manager.enable_sip_trace_with_redactor(
                owner_id,
                config.sip_trace.clone(),
                global_coordinator.clone(),
                redactor_fn,
            );
        }

        // Initialize the transport manager
        transport_manager.initialize().await.map_err(|e| {
            SessionError::InternalError(format!("Failed to initialize transport: {}", e))
        })?;

        // Create transaction manager using transport manager
        let (transaction_manager, event_rx) =
            TransactionManager::with_transport_manager_and_index_capacity_and_dispatch_and_authorizer_shared_with_compact_retention_capacity(
                transport_manager,
                transport_event_rx,
                Some(config.transaction_event_channel_capacity),
                Some(config.transaction_index_capacity_hint()),
                config.sip_transaction_dispatch_workers,
                config.sip_transaction_dispatch_queue_capacity,
                listener_auth_policy.into_authorizer(),
                config
                    .server_retained_lifecycle_capacity
                    .unwrap_or(262_144),
            )
            .await
            .map_err(|e| {
                SessionError::InternalError(format!("Failed to create transaction manager: {}", e))
            })?;

        let mut transaction_manager = transaction_manager;
        transaction_manager.set_auto_100_trying(config.auto_100_trying);
        transaction_manager.set_transaction_command_channel_capacity(
            config
                .sip_transaction_command_channel_capacity
                .unwrap_or(Config::DEFAULT_SIP_TRANSACTION_COMMAND_CHANNEL_CAPACITY),
        );
        transaction_manager.set_stateless_overload_retry_after_secs(
            config.server_overload_retry_after_secs.unwrap_or(1),
        );
        if let Some(max_burst) = config.sip_transaction_dispatch_priority_burst_max {
            transaction_manager.set_transaction_dispatch_priority_burst_max(max_burst);
        }
        if let Some(max_due_per_tick) = config.sip_invite_2xx_retransmit_max_due_per_tick {
            transaction_manager.set_invite_2xx_retransmit_max_due_per_tick(max_due_per_tick);
        }
        let transaction_manager = Arc::new(transaction_manager);

        // Create dialog config - use hybrid mode to support both incoming and outgoing calls
        let dialog_config = DialogManagerConfig::hybrid(config.bind_addr)
            .with_from_uri(&config.local_uri)
            .with_auto_options()
            .with_100rel(config.use_100rel)
            .with_session_timer(config.session_timer_secs)
            .with_min_se(config.session_timer_min_se)
            .with_dialog_config(|mut dialog| {
                dialog.advertised_local_address = config.sip_advertised_addr;
                dialog.local_contact_uri = config.contact_uri.clone();
                dialog.tls_local_address = dialog_tls_local_address;
                dialog.tls_advertised_local_address = config.tls_advertised_addr;
                dialog.max_dialogs = Some(config.dialog_index_capacity_hint());
                dialog.event_dispatch_workers = config.sip_dialog_dispatch_workers;
                dialog.event_dispatch_queue_capacity = config.sip_dialog_dispatch_queue_capacity;
                dialog
            })
            .build();

        // Create dialog API with global event coordination AND transaction events
        let dialog_api = Arc::new(
            UnifiedDialogApi::with_shared_global_events_and_coordinator(
                transaction_manager,
                event_rx,
                dialog_config,
                global_coordinator.clone(),
            )
            .await
            .map_err(|e| {
                SessionError::InternalError(format!("Failed to create dialog API: {}", e))
            })?,
        );

        dialog_api.start().await.map_err(|e| {
            SessionError::InternalError(format!("Failed to start dialog API: {}", e))
        })?;

        Ok(dialog_api)
    }

    async fn create_media_controller(
        config: &Config,
        global_coordinator: Arc<GlobalEventCoordinator>,
        symmetric_rtp_policy: SymmetricRtpPolicy,
    ) -> Result<Arc<rvoip_media_core::relay::controller::MediaSessionController>> {
        use rvoip_media_core::relay::controller::MediaSessionController;

        let mut media_controller_config = config.media_session_controller_config.clone();
        media_controller_config.capacity_hint = config
            .media_session_capacity
            .or(config.server_call_capacity)
            .unwrap_or(media_controller_config.capacity_hint);
        media_controller_config.rtp_session_buffer_config = config.rtp_session_buffer_config;
        media_controller_config.rtp_transport_buffer_config = config.rtp_transport_buffer_config;

        // Create media controller with port range and SIP-exposed media/RTP tuning.
        let controller = Arc::new(
            MediaSessionController::with_port_range_and_config(
                config.media_port_start,
                config.media_port_end,
                media_controller_config,
            )
            .with_symmetric_rtp_policy(symmetric_rtp_policy),
        );

        // Create and set up the event hub
        let event_hub =
            rvoip_media_core::events::MediaEventHub::new(global_coordinator, controller.clone())
                .await
                .map_err(|e| {
                    SessionError::InternalError(format!("Failed to create media event hub: {}", e))
                })?;

        // Set the event hub on the media controller
        controller.set_event_hub(event_hub).await;

        Ok(controller)
    }
}

/// SIP_API_DESIGN_2 §7.1 — compatibility stage/dispatch helpers.
///
/// The public two-step surface remains stable for downstream callers. Crate
/// builders use the private atomic stage-and-dispatch path so the immutable
/// options snapshot and its matching event enter one exact-session lane.
/// Either route leaves the action handler and final-response transition as
/// the only consumers of the staged request.
impl UnifiedCoordinator {
    /// Stage a pending-options snapshot on the session and check the
    /// single-in-flight conflict guard. Returns
    /// `Err(SessionError::Conflict { method })` when a prior `.send()`
    /// for the same method on the same session has not yet reached its
    /// final response. See
    /// [`StateMachine::stage_outbound_options`](crate::state_machine::executor::StateMachine::stage_outbound_options).
    pub async fn stage_outbound_options(
        &self,
        session_id: &SessionId,
        slot: crate::state_machine::executor::PendingOptionsSlot,
    ) -> Result<()> {
        self.helpers
            .state_machine
            .stage_outbound_options(session_id, slot)
            .await
            .map_err(|e| {
                if let Ok(typed) = e.downcast::<SessionError>() {
                    *typed
                } else {
                    SessionError::InternalError(
                        "stage_outbound_options: state-machine error".to_string(),
                    )
                }
            })
    }

    /// Queue a state-machine event on the session's event queue and run
    /// the resulting transition. Thin wrapper over
    /// [`StateMachine::process_event`].
    pub async fn dispatch_outbound(
        &self,
        session_id: &SessionId,
        event: crate::state_table::EventType,
    ) -> Result<crate::state_machine::executor::ProcessEventResult> {
        let handle = self
            .helpers
            .state_machine
            .store
            .lifecycle_handle(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.to_string()))?;
        self.dispatch_outbound_exact(&handle, event).await
    }

    /// Queue an outbound event only for the captured session lifetime.
    pub(crate) async fn dispatch_outbound_exact(
        &self,
        handle: &SessionRegistryHandle,
        event: crate::state_table::EventType,
    ) -> Result<crate::state_machine::executor::ProcessEventResult> {
        // `SendOutboundNotify` has one legacy, stack-generated shape in
        // addition to the public builder path: an automatic NOTIFY with no
        // pre-staged options. Materialize that shape into an exact guarded
        // stage before dispatch so it receives the same cancellation,
        // fast-response, authentication-retry, and completion ownership as a
        // builder-generated NOTIFY. The action itself remains fail-closed for
        // any unguarded unstaged dispatch that bypasses this coordinator.
        if matches!(&event, crate::state_table::EventType::SendOutboundNotify) {
            let (has_pending_options, local_sdp) = self
                .helpers
                .state_machine
                .store
                .get_session_snapshot_exact(handle)
                .map(|session| {
                    (
                        session.pending_notify_options.is_some(),
                        session.local_sdp.clone(),
                    )
                })
                .map_err(|_| SessionError::SessionNotFound(handle.session_id().to_string()))?;

            if !has_pending_options {
                let options = Arc::new(rvoip_sip_dialog::api::unified::NotifyRequestOptions {
                    event: "presence".to_string(),
                    subscription_state: String::new(),
                    content_type: None,
                    body: local_sdp.map(bytes::Bytes::from),
                    subscription_id: None,
                    extra_headers: self.dialog_adapter.auto_emit_extra_headers.clone(),
                });
                return self
                    .dispatch_outbound_with_options_exact(
                        handle,
                        event,
                        crate::state_machine::executor::PendingOptionsSlot::Notify(options),
                    )
                    .await;
            }
        }

        let state_machine = Arc::clone(&self.helpers.state_machine);
        let task_handle = handle.clone();
        let task = AbortOutboundDispatchTaskOnDrop::new(tokio::spawn(async move {
            state_machine.process_event_exact(&task_handle, event).await
        }));
        task.join()
            .await
            .map_err(|_| SessionError::InternalError(OUTBOUND_DISPATCH_JOIN_FAILURE.to_string()))?
            .map_err(map_state_machine_dispatch_error)
    }

    /// Atomically stage a builder snapshot and dispatch its matching event.
    ///
    /// Cancellation before the state machine claims the staged Arc aborts the
    /// task and clears that exact stage. Cancellation after claim detaches the
    /// task so the first transport write and tracker activation cannot split.
    pub(crate) async fn dispatch_outbound_with_options(
        &self,
        session_id: &SessionId,
        event: crate::state_table::EventType,
        slot: crate::state_machine::executor::PendingOptionsSlot,
    ) -> Result<crate::state_machine::executor::ProcessEventResult> {
        let handle = self
            .helpers
            .state_machine
            .store
            .lifecycle_handle(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.to_string()))?;
        self.dispatch_outbound_with_options_and_input_exact(&handle, event, slot, None, None)
            .await
    }

    /// Atomically stage and dispatch only for a captured session lifetime.
    pub(crate) async fn dispatch_outbound_with_options_exact(
        &self,
        handle: &SessionRegistryHandle,
        event: crate::state_table::EventType,
        slot: crate::state_machine::executor::PendingOptionsSlot,
    ) -> Result<crate::state_machine::executor::ProcessEventResult> {
        self.dispatch_outbound_with_options_and_input_exact(handle, event, slot, None, None)
            .await
    }

    /// Dispatch a manual REGISTER refresh from one captured session lifetime.
    /// Registration metadata and the next CSeq are deliberately absent from
    /// the public builder object; the state machine derives them only after it
    /// owns this exact generation's complete-event lane.
    pub(crate) async fn dispatch_registration_refresh_exact(
        &self,
        handle: &SessionRegistryHandle,
        expires_override: Option<u32>,
        extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<crate::state_machine::executor::ProcessEventResult> {
        let state_machine = Arc::clone(&self.helpers.state_machine);
        let task_handle = handle.clone();
        let stage_claim = Arc::new(
            crate::state_machine::executor::StageDispatchClaim::new_deferred(
                Method::Register,
                crate::state_machine::executor::PendingOptionsSlotKind::Register,
            ),
        );
        let task_claim = Arc::clone(&stage_claim);
        let task = AbortOutboundDispatchTaskOnDrop::with_stage_claim(
            tokio::spawn(async move {
                state_machine
                    .process_registration_refresh_exact(
                        &task_handle,
                        crate::state_table::EventType::SendOutboundRegister,
                        expires_override,
                        extra_headers,
                        task_claim,
                    )
                    .await
            }),
            stage_claim,
        );
        task.join()
            .await
            .map_err(|_| SessionError::InternalError(OUTBOUND_DISPATCH_JOIN_FAILURE.to_string()))?
            .map_err(|e| SessionError::InternalError(format!("registration refresh dispatch: {e}")))
    }

    pub(crate) async fn dispatch_outbound_invite_with_options(
        &self,
        session_id: &SessionId,
        snapshot: Arc<crate::api::send::outbound_call::OutboundCallOptionsSnapshot>,
        pai_uri: Option<String>,
    ) -> Result<crate::state_machine::executor::ProcessEventResult> {
        let transferor_lifecycle_handle = match snapshot.transfer_leg.as_ref() {
            Some(transferor) => Some(
                self.helpers
                    .state_machine
                    .store
                    .lifecycle_handle(transferor)
                    .ok_or_else(|| SessionError::SessionNotFound(transferor.to_string()))?,
            ),
            None => None,
        };
        let input = crate::state_machine::executor::OutboundSessionStateInput::from_snapshot(
            &snapshot,
            pai_uri,
            transferor_lifecycle_handle,
        );
        let handle = self
            .helpers
            .state_machine
            .store
            .lifecycle_handle(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.to_string()))?;
        self.dispatch_outbound_with_options_and_input_exact(
            &handle,
            crate::state_table::EventType::SendOutboundInvite,
            crate::state_machine::executor::PendingOptionsSlot::Invite(snapshot),
            Some(input),
            None,
        )
        .await
    }

    async fn dispatch_outbound_with_options_and_input_exact(
        &self,
        handle: &SessionRegistryHandle,
        event: crate::state_table::EventType,
        slot: crate::state_machine::executor::PendingOptionsSlot,
        outbound_session: Option<crate::state_machine::executor::OutboundSessionStateInput>,
        task_bye_wait_owner: Option<Arc<crate::adapters::dialog_adapter::OutgoingByeWaitOwner>>,
    ) -> Result<crate::state_machine::executor::ProcessEventResult> {
        let state_machine = Arc::clone(&self.helpers.state_machine);
        let task_handle = handle.clone();
        let stage_claim = Arc::new(crate::state_machine::executor::StageDispatchClaim::new(
            slot.clone(),
        ));
        let task_claim = Arc::clone(&stage_claim);
        let task = AbortOutboundDispatchTaskOnDrop::with_stage_claim(
            tokio::spawn(async move {
                let result = state_machine
                    .process_event_with_staged_options_exact(
                        &task_handle,
                        event,
                        slot,
                        task_claim,
                        outbound_session,
                    )
                    .await;
                // Keep a claimed BYE's cancellation owner alive through the
                // complete state-machine action, including publication of its
                // exact transaction receipt.
                drop(task_bye_wait_owner);
                result
            }),
            stage_claim,
        );
        task.join()
            .await
            .map_err(|_| SessionError::InternalError(OUTBOUND_DISPATCH_JOIN_FAILURE.to_string()))?
            .map_err(map_state_machine_dispatch_error)
    }

    /// Crate-internal accessor: read the current `SessionState` snapshot for
    /// the given session id. Used by refresh-style builders that need to
    /// reuse registration / dialog identifiers from the original send.
    pub(crate) async fn session_state(
        &self,
        session_id: &SessionId,
    ) -> Result<crate::session_store::SessionState> {
        self.helpers
            .state_machine
            .store
            .get_session(session_id)
            .await
            .map_err(|_| SessionError::SessionNotFound(session_id.to_string()))
    }

    /// Test-only state setup hook. Production response and send paths must
    /// carry mutations through typed executor input instead of replacing a
    /// session snapshot before dispatch.
    #[cfg(test)]
    pub(crate) async fn update_session_state_for_test(
        &self,
        session: crate::session_store::SessionState,
    ) -> Result<()> {
        self.helpers
            .state_machine
            .store
            .update_session(session)
            .await
            .map_err(|error| {
                SessionError::InternalError(format!("test session-state update: {error}"))
            })
    }
}

/// Simple helper to create a session and make a call
impl UnifiedCoordinator {
    /// Quick method to create a UAC session and make a call
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>) -> rvoip_sip::Result<()> {
    /// let call_id = coordinator
    ///     .quick_call("sip:alice@127.0.0.1:5060", "sip:bob@127.0.0.1:5070")
    ///     .await?;
    /// # let _ = call_id;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn quick_call(self: &Arc<Self>, from: &str, to: &str) -> Result<SessionId> {
        self.invite(Some(from.to_string()), to.to_string())
            .send()
            .await
    }
}

/// Registration API
impl UnifiedCoordinator {
    /// Internal REGISTER dispatch used by
    /// [`RegisterBuilder`](crate::api::send::RegisterBuilder).
    ///
    /// When `extra_headers` is non-empty we follow SIP_API_DESIGN_2 §10 #19
    /// and stash a `RegisterRequestOptions` on the session *before* the
    /// `StartRegistration` event fires, so `execute_register_action`
    /// (`state_machine/actions.rs`) reads the slice on the very first
    /// dispatch (not just on the 401-retry).
    ///
    /// When `extra_headers` is empty we skip the stash entirely. Stashing
    /// here would occupy `pending_register_options`; the slot is only
    /// cleared once the first REGISTER reaches a final response, so a
    /// caller that fires a `RegisterRefreshBuilder::send` before that
    /// would race the stash check in
    /// [`stage_outbound_options`](crate::state_machine::executor::StateMachineExecutor::stage_outbound_options)
    /// and get back `SessionError::Conflict { method: Register }`.
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn register_with_extras(
        &self,
        registrar_uri: &str,
        from_uri: &str,
        contact_uri: &str,
        username: &str,
        password: &str,
        expires: u32,
        extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<RegistrationHandle> {
        let session_id = SessionId::new();
        self.helpers
            .create_session(
                session_id.clone(),
                from_uri.to_string(),
                registrar_uri.to_string(),
                crate::state_table::types::Role::UAC,
            )
            .await?;

        let credentials = crate::types::Credentials::new(username, password);

        // If the application didn't configure UAC auth, adopt these REGISTER
        // credentials as the default for challenged in-account requests
        // (INVITE/re-INVITE/BYE/REFER) so "register, then call" authenticates
        // out of the box. Explicit Config.credentials/Config.auth always win
        // (see `config_credentials`). Locked briefly and synchronously.
        if self.config.credentials.is_none() && self.config.auth.is_none() {
            if let Ok(mut slot) = self.registered_credentials.lock() {
                *slot = Some(credentials.clone());
            }
        }

        let pending_options = (!extra_headers.is_empty()).then(|| {
            std::sync::Arc::new(rvoip_sip_dialog::api::unified::RegisterRequestOptions {
                registrar_uri: registrar_uri.to_string(),
                aor_uri: from_uri.to_string(),
                contact_uri: contact_uri.to_string(),
                expires,
                authorization: None,
                proxy_authorization: None,
                call_id: None,
                cseq: None,
                outbound_contact: None,
                outbound_proxy_uri: None,
                extra_headers,
                refresh: false,
            })
        });

        let _ = self
            .helpers
            .state_machine
            .process_event_with_registration_start_input(
                &session_id,
                crate::state_table::types::EventType::StartRegistration,
                crate::state_machine::executor::RegistrationStartInput::new(
                    credentials,
                    registrar_uri.to_string(),
                    contact_uri.to_string(),
                    expires,
                    pending_options,
                ),
            )
            .await
            .map_err(|e| {
                SessionError::InternalError(format!("Failed to trigger registration: {}", e))
            })?;

        Ok(RegistrationHandle { session_id })
    }

    /// Unregister from the SIP server.
    ///
    /// Sends REGISTER with `Expires: 0` to remove the binding and aborts any
    /// pending automatic refresh task when the registrar confirms success.
    /// This method returns after the state machine accepts the request. Use
    /// [`unregister_and_wait`](Self::unregister_and_wait) when the caller must
    /// wait for `UnregistrationSuccess` or `UnregistrationFailed`.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, handle: rvoip_sip::RegistrationHandle) -> rvoip_sip::Result<()> {
    /// coordinator.unregister(&handle).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn unregister(&self, handle: &RegistrationHandle) -> Result<()> {
        // Trigger unregistration via state machine
        let result = self
            .helpers
            .state_machine
            .process_event(
                &handle.session_id,
                crate::state_table::types::EventType::StartUnregistration,
            )
            .await
            .map_err(|e| {
                SessionError::InternalError(format!("Failed to trigger unregistration: {}", e))
            })?;
        if result.transition.is_none() {
            return Err(SessionError::InvalidTransition(format!(
                "Cannot unregister session {} from state {:?}",
                handle.session_id.0, result.old_state
            )));
        }
        if !result.actions_executed.iter().any(|action| {
            matches!(
                action,
                Action::SendREGISTERWithOptions | Action::SendUnREGISTER
            )
        }) {
            return Err(SessionError::InternalError(format!(
                "Unregistration transition for session {} did not send REGISTER Expires: 0",
                handle.session_id.0
            )));
        }
        Ok(())
    }

    /// Refresh registration before it expires.
    ///
    /// Sends a new REGISTER request using the stored registration expiry and
    /// registration Call-ID. Successful refresh responses replace the stored
    /// accepted expiry and next automatic refresh time.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, handle: rvoip_sip::RegistrationHandle) -> rvoip_sip::Result<()> {
    /// coordinator.refresh_registration(&handle).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn refresh_registration(&self, handle: &RegistrationHandle) -> Result<()> {
        // Trigger refresh via state machine
        let _result = self
            .helpers
            .state_machine
            .process_event(
                &handle.session_id,
                crate::state_table::types::EventType::RefreshRegistration,
            )
            .await
            .map_err(|e| {
                SessionError::InternalError(format!("Failed to trigger refresh: {}", e))
            })?;
        Ok(())
    }

    /// SIP_API_DESIGN_2 §3.3 — Begin a manual REGISTER refresh on the
    /// given registration handle. Returns a `RegisterRefreshBuilder`
    /// that supports `.with_expires(n)` and ships via `.send().await`.
    pub fn refresh(
        self: &Arc<Self>,
        handle: &RegistrationHandle,
    ) -> crate::api::send::RegisterRefreshBuilder {
        let lifecycle_handle = self
            .helpers
            .state_machine
            .store
            .lifecycle_handle(&handle.session_id);
        crate::api::send::RegisterRefreshBuilder::new(
            self.clone(),
            handle.clone(),
            lifecycle_handle,
        )
    }

    /// Return whether the registration is currently marked registered.
    ///
    /// This is a coarse boolean for simple clients. Use
    /// [`registration_info`](Self::registration_info) for status, accepted
    /// expiry, next refresh timing, failure metadata, Service-Route, GRUU, and
    /// outbound-flow information.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, handle: rvoip_sip::RegistrationHandle) -> rvoip_sip::Result<()> {
    /// if coordinator.is_registered(&handle).await? {
    ///     println!("registration is active");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn is_registered(&self, handle: &RegistrationHandle) -> Result<bool> {
        let (is_registered, retry_count) = self
            .helpers
            .state_machine
            .store
            .with_session(&handle.session_id, |session| {
                (session.is_registered, session.registration_retry_count)
            })?;
        tracing::info!(
            "🔍 Checking registration for session {}: is_registered={}, retry_count={}",
            handle.session_id.0,
            is_registered,
            retry_count
        );
        Ok(is_registered)
    }

    /// Return detailed registration lifecycle information for a handle.
    ///
    /// `accepted_expires_secs`, `registered_at`, and `next_refresh_at` are
    /// populated from successful REGISTER responses. `service_route`,
    /// `pub_gruu`, and `temp_gruu` are populated when supplied by the
    /// registrar. Failure and unregister paths clear refresh metadata and keep
    /// a stable status snapshot for diagnostics.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, handle: rvoip_sip::RegistrationHandle) -> rvoip_sip::Result<()> {
    /// let info = coordinator.registration_info(&handle).await?;
    /// println!("status: {:?}", info.status);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn registration_info(&self, handle: &RegistrationHandle) -> Result<RegistrationInfo> {
        let snapshot = self
            .helpers
            .state_machine
            .store
            .get_session_snapshot(&handle.session_id)
            .await?;
        let (
            status,
            next_refresh_in,
            last_failure,
            aor,
            stored_service_route,
            stored_pub_gruu,
            stored_temp_gruu,
            registrar,
            contact,
            expires_secs,
            retry_count,
            accepted_expires_secs,
            registered_at,
            next_refresh_at,
        ) = {
            let session = snapshot.state();
            let status = if session.is_registered {
                RegistrationStatus::Registered
            } else {
                match session.call_state {
                    CallState::Registering => RegistrationStatus::Registering,
                    CallState::Unregistering => RegistrationStatus::Unregistering,
                    _ if session.registration_last_failure.is_some() => RegistrationStatus::Failed,
                    _ if session.registration_retry_count > 0 => RegistrationStatus::Failed,
                    _ => RegistrationStatus::Unregistered,
                }
            };
            let next_refresh_in = session
                .registration_next_refresh_at
                .map(|when| when.saturating_duration_since(Instant::now()));
            let last_failure = if let Some(reason) = session.registration_last_failure.clone() {
                Some(reason)
            } else if matches!(status, RegistrationStatus::Failed) {
                Some(format!(
                    "registration failed after {} retry attempt(s)",
                    session.registration_retry_count
                ))
            } else {
                None
            };
            (
                status,
                next_refresh_in,
                last_failure,
                session.local_uri.clone(),
                session.registration_service_route.clone(),
                session.registration_pub_gruu.clone(),
                session.registration_temp_gruu.clone(),
                session.registrar_uri.clone(),
                session.registration_contact.clone(),
                session.registration_expires,
                session.registration_retry_count,
                session.registration_accepted_expires,
                session.registration_registered_at,
                session.registration_next_refresh_at,
            )
        };
        drop(snapshot);

        let (dialog_service_route, dialog_pub_gruu, dialog_temp_gruu, outbound_flow_active) =
            if let Some(aor) = aor.as_deref() {
                let dialog_service_route = self
                    .dialog_adapter
                    .dialog_api
                    .service_route_for_aor(aor)
                    .await
                    .map(|uris| uris.into_iter().map(|uri| uri.to_string()).collect());
                let gruu = self.dialog_adapter.dialog_api.gruu_for_aor(aor).await;
                let outbound_flow_active = self
                    .dialog_adapter
                    .dialog_api
                    .outbound_flow_active_for_aor(aor);
                (
                    dialog_service_route,
                    gruu.as_ref().and_then(|params| params.pub_gruu.clone()),
                    gruu.and_then(|params| params.temp_gruu),
                    outbound_flow_active,
                )
            } else {
                (None, None, None, false)
            };
        let service_route = stored_service_route.or(dialog_service_route);
        let pub_gruu = stored_pub_gruu.or(dialog_pub_gruu);
        let temp_gruu = stored_temp_gruu.or(dialog_temp_gruu);

        Ok(RegistrationInfo {
            session_id: handle.session_id.clone(),
            status,
            registrar,
            contact,
            expires_secs,
            next_refresh_in,
            retry_count,
            last_failure,
            accepted_expires_secs,
            registered_at,
            next_refresh_at,
            service_route,
            pub_gruu,
            temp_gruu,
            outbound_flow_active,
        })
    }

    /// Unregister and wait for the matching registration lifecycle event.
    ///
    /// This subscribes to the coordinator event stream before sending
    /// unregister, then returns after `UnregistrationSuccess` or converts
    /// `UnregistrationFailed` into an error. Registration events are global
    /// coordinator events, not per-registration handle streams.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # async fn example(coordinator: std::sync::Arc<rvoip_sip::UnifiedCoordinator>, handle: rvoip_sip::RegistrationHandle) -> rvoip_sip::Result<()> {
    /// coordinator
    ///     .unregister_and_wait(&handle, Some(std::time::Duration::from_secs(3)))
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn unregister_and_wait(
        &self,
        handle: &RegistrationHandle,
        timeout: Option<std::time::Duration>,
    ) -> Result<()> {
        let registrar = self
            .registration_info(handle)
            .await?
            .registrar
            .unwrap_or_default();
        let mut events = self.events().await?;
        self.unregister(handle).await?;

        let fut = async {
            loop {
                match events.next().await {
                    Some(crate::api::events::Event::UnregistrationSuccess { registrar: r })
                        if registrar.is_empty() || r == registrar =>
                    {
                        return Ok(());
                    }
                    Some(crate::api::events::Event::UnregistrationFailed {
                        registrar: r,
                        reason,
                    }) if registrar.is_empty() || r == registrar => {
                        return Err(SessionError::Other(format!(
                            "Unregistration failed for {}: {}",
                            r, reason
                        )));
                    }
                    Some(_) => {}
                    None => {
                        return Err(SessionError::Other(
                            "Event channel closed while waiting for unregister".to_string(),
                        ));
                    }
                }
            }
        };

        match timeout {
            Some(duration) => tokio::time::timeout(duration, fut)
                .await
                .map_err(|_| SessionError::Timeout("unregister_and_wait timed out".to_string()))?,
            None => fut.await,
        }
    }
}

/// Handle for managing a registration.
///
/// Registration lifecycle events are emitted through
/// [`UnifiedCoordinator::events`] and [`UnifiedCoordinator::events_for_session`].
/// This handle deliberately does not expose a separate event stream today,
/// because doing so cleanly would require a per-registration event bus split.
#[derive(Clone)]
pub struct RegistrationHandle {
    /// Session id backing this registration lifecycle.
    pub session_id: SessionId,
}

impl std::fmt::Debug for RegistrationHandle {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("RegistrationHandle")
            .field("session_id_present", &true)
            .finish()
    }
}

/// Coarse registration lifecycle state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RegistrationStatus {
    /// REGISTER has been sent and the registrar response is still pending.
    Registering,
    /// Registrar accepted the binding and the contact is currently active.
    Registered,
    /// REGISTER with `Expires: 0` has been sent and the registrar response is pending.
    Unregistering,
    /// No active binding is known for this registration handle.
    Unregistered,
    /// The most recent registration or refresh attempt failed.
    Failed,
}

/// Query result for a registration handle.
///
/// This is a snapshot of the current client-side registration lifecycle. It
/// combines rvoip-sip state with metadata learned from rvoip-sip-dialog REGISTER
/// responses.
#[derive(Clone)]
pub struct RegistrationInfo {
    /// Session id backing this registration lifecycle.
    pub session_id: SessionId,
    /// Coarse lifecycle status.
    pub status: RegistrationStatus,
    /// Registrar URI originally used for REGISTER.
    pub registrar: Option<String>,
    /// Contact URI currently associated with the registration.
    pub contact: Option<String>,
    /// Last expiry value rvoip-sip will request on refresh.
    pub expires_secs: Option<u32>,
    /// Duration until the currently scheduled automatic refresh.
    pub next_refresh_in: Option<Duration>,
    /// Number of retry attempts used by the current/last registration flow.
    pub retry_count: u32,
    /// Last failure summary, if the lifecycle is failed.
    pub last_failure: Option<String>,
    /// Expiry accepted by the registrar in the most recent successful 2xx.
    pub accepted_expires_secs: Option<u32>,
    /// Local time when the most recent successful registration completed.
    pub registered_at: Option<Instant>,
    /// Local time when automatic refresh is scheduled.
    pub next_refresh_at: Option<Instant>,
    /// Registrar-provided Service-Route URIs, if supplied.
    pub service_route: Option<Vec<String>>,
    /// Registrar-assigned public GRUU, if supplied.
    pub pub_gruu: Option<String>,
    /// Registrar-assigned temporary GRUU, if supplied.
    pub temp_gruu: Option<String>,
    /// Whether rvoip-sip-dialog currently has an RFC 5626 outbound flow monitor.
    pub outbound_flow_active: bool,
}

impl std::fmt::Debug for RegistrationInfo {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("RegistrationInfo")
            .field("session_id_present", &true)
            .field("status", &self.status)
            .field("registrar_configured", &self.registrar.is_some())
            .field("contact_configured", &self.contact.is_some())
            .field("expires_secs", &self.expires_secs)
            .field("next_refresh_scheduled", &self.next_refresh_in.is_some())
            .field("retry_count", &self.retry_count)
            .field("last_failure_present", &self.last_failure.is_some())
            .field("accepted_expires_secs", &self.accepted_expires_secs)
            .field("registered", &self.registered_at.is_some())
            .field("next_refresh_at_present", &self.next_refresh_at.is_some())
            .field(
                "service_route_count",
                &self.service_route.as_ref().map_or(0, Vec::len),
            )
            .field("public_gruu_present", &self.pub_gruu.is_some())
            .field("temporary_gruu_present", &self.temp_gruu.is_some())
            .field("outbound_flow_active", &self.outbound_flow_active)
            .finish()
    }
}

/// Configuration for SIP registration.
///
/// Use [`Registration::new()`] for the common case where `from_uri` and
/// `contact_uri` are derived from the peer's [`Config`].
///
/// # Example
///
/// ```
/// use rvoip_sip::Registration;
///
/// let reg = Registration::new("sip:registrar.example.com", "alice", "secret123")
///     .expires(1800);
/// ```
#[derive(Clone)]
pub struct Registration {
    /// SIP URI of the registrar server (e.g. `sip:registrar.example.com`)
    pub registrar: String,
    /// Username for digest authentication
    pub username: String,
    /// Password for digest authentication
    pub password: String,
    /// Registration expiry in seconds (default: 3600)
    pub expires: u32,
    /// Override the From URI (defaults to the peer's local_uri)
    pub from_uri: Option<String>,
    /// Override the Contact URI (defaults to the peer's local_uri)
    pub contact_uri: Option<String>,
}

impl std::fmt::Debug for Registration {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("Registration")
            .field("registrar_configured", &!self.registrar.is_empty())
            .field("username_configured", &!self.username.is_empty())
            .field("password_configured", &!self.password.is_empty())
            .field("expires", &self.expires)
            .field("from_uri_configured", &self.from_uri.is_some())
            .field("contact_uri_configured", &self.contact_uri.is_some())
            .finish()
    }
}

impl Registration {
    /// Create a registration with the minimum required fields.
    ///
    /// `from_uri` and `contact_uri` will be derived from the peer's config.
    ///
    /// # Examples
    ///
    /// ```
    /// use rvoip_sip::Registration;
    ///
    /// let reg = Registration::new("sip:registrar.example.com", "alice", "secret");
    /// assert_eq!(reg.expires, 3600);
    /// ```
    pub fn new(
        registrar: impl Into<String>,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Self {
        Self {
            registrar: registrar.into(),
            username: username.into(),
            password: password.into(),
            expires: 3600,
            from_uri: None,
            contact_uri: None,
        }
    }

    /// Set the registration expiry in seconds (default: 3600).
    ///
    /// # Examples
    ///
    /// ```
    /// use rvoip_sip::Registration;
    ///
    /// let reg = Registration::new("sip:registrar.example.com", "alice", "secret")
    ///     .expires(600);
    /// assert_eq!(reg.expires, 600);
    /// ```
    pub fn expires(mut self, secs: u32) -> Self {
        self.expires = secs;
        self
    }

    /// Override the From URI (defaults to the peer's local URI).
    ///
    /// # Examples
    ///
    /// ```
    /// use rvoip_sip::Registration;
    ///
    /// let reg = Registration::new("sip:registrar.example.com", "alice", "secret")
    ///     .from_uri("sip:alice@example.com");
    /// assert_eq!(reg.from_uri.as_deref(), Some("sip:alice@example.com"));
    /// ```
    pub fn from_uri(mut self, uri: impl Into<String>) -> Self {
        self.from_uri = Some(uri.into());
        self
    }

    /// Override the Contact URI (defaults to the peer's local URI).
    ///
    /// # Examples
    ///
    /// ```
    /// use rvoip_sip::Registration;
    ///
    /// let reg = Registration::new("sip:registrar.example.com", "alice", "secret")
    ///     .contact_uri("sip:alice@192.168.1.50:5060");
    /// assert_eq!(reg.contact_uri.as_deref(), Some("sip:alice@192.168.1.50:5060"));
    /// ```
    pub fn contact_uri(mut self, uri: impl Into<String>) -> Self {
        self.contact_uri = Some(uri.into());
        self
    }
}

/// Sprint 3 A6 — best-effort STUN probe for the RTP-side public
/// mapping.
///
/// **Caveat.** The probe binds a fresh ephemeral UDP socket on the
/// configured `local_ip` and asks the STUN server what mapping it
/// sees. For typical cone NATs (most consumer routers, AWS / GCP
/// NAT gateways) the mapping is keyed by source IP only, so the
/// discovered address matches what the actual RTP path will see
/// later. For symmetric NATs the mapping is per-(source IP, source
/// port) and the result will be wrong — those deployments need ICE
/// (Sprint 4 D3). For Sprint 3 the simple shape is the right
/// trade-off; a deployment that breaks here can fall back to
/// `Config::media_public_addr` (static override).
async fn run_stun_probe(adapter: Arc<MediaAdapter>, stun_target: &str) -> Result<()> {
    use std::sync::Arc as StdArc;
    use tokio::net::UdpSocket as TokioUdpSocket;

    // Normalise "host" → "host:3478"; "host:port" passes through.
    let target_str = if stun_target.contains(':') {
        stun_target.to_string()
    } else {
        format!("{}:3478", stun_target)
    };

    // Resolve via tokio's DNS — STUN servers are typically fronted by
    // SRV in production but the public ones (Google, Cloudflare) all
    // expose plain A records.
    let server_addr = tokio::net::lookup_host(&target_str)
        .await
        .map_err(|e| {
            SessionError::ConfigError(format!("STUN resolve '{}' failed: {}", target_str, e))
        })?
        .next()
        .ok_or_else(|| {
            SessionError::ConfigError(format!("STUN '{}' resolved to nothing", target_str))
        })?;

    // Bind a probe socket on the same interface as the SIP/media
    // bind. Random ephemeral port; the cone-NAT-mapping caveat above
    // applies.
    let bind_local = std::net::SocketAddr::new(adapter.local_ip(), 0);
    let probe_sock = TokioUdpSocket::bind(bind_local).await.map_err(|e| {
        SessionError::ConfigError(format!("STUN probe bind {} failed: {}", bind_local, e))
    })?;
    let probe_sock = StdArc::new(probe_sock);

    let client = rvoip_rtp_core::network::stun::StunClient::new(probe_sock, server_addr);
    let discovered = client
        .discover()
        .await
        .map_err(|e| SessionError::ConfigError(format!("STUN probe failed: {}", e)))?;

    tracing::info!(
        "RTP public addr: {} (STUN-discovered via {})",
        discovered,
        target_str
    );
    adapter.set_public_rtp_addr(Some(discovered));
    Ok(())
}