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
use std::collections::HashMap;
#[cfg(test)]
use std::collections::VecDeque;
use std::collections::hash_map::Entry;
use std::net::{SocketAddr, TcpStream};
use std::os::fd::RawFd;
#[cfg(test)]
use std::sync::Barrier;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, TryRecvError, channel};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError, Weak};
use std::thread;
use std::time::{Duration, Instant};
use beamr::atom::{Atom, AtomTable};
use beamr::module::ModuleRegistry;
use beamr::native::native_process::NativeHandlerFactory;
use beamr::process::ExitReason;
use beamr::scheduler::{
ExitEvent, ExitEventSubscription, NativeBifs, ReadinessToken, Scheduler, SchedulerConfig,
SchedulerServices,
};
use beamr::timer::TimerRef;
use liminal::protocol::WorkerRegistration;
use liminal_protocol::wire::ConnectionIncarnation;
use super::incarnation::ConnectionIncarnationAuthority;
use super::loopback::{LoopbackConnectionProcess, LoopbackServerEnd};
use super::notifier::ConnectionNotifier;
use super::outbound::OutboundError;
use super::process::ConnectionProcess;
use super::refusal::AdmissionRefusal;
#[cfg(any(test, feature = "test-support"))]
use super::services::LiminalConnectionServices;
use super::services::{ConnectionServices, build_connection_services};
#[cfg(test)]
use super::services::{SubsystemFactory, build_connection_services_via};
use crate::ServerError;
use crate::auth_pass::{PassPrincipal, PassVerifier};
use crate::config::types::{AuthConfig, LimitsConfig, ServerConfig};
use crate::health::AdmissionReadiness;
use crate::server::mount::MountKind;
use crate::server::participant::{
CandidateLaneListener, ConnectionFateClass, InstalledParticipantService,
ParticipantSemanticHandler, ParticipantServiceFatal,
};
use crate::server::shutdown::ShutdownHandle;
use crate::server::signals::ServerSignals;
const CONNECTION_SCHEDULER_THREADS: usize = 4;
const CONNECTION_SHUTDOWN_CONTROL_ATOM: &str = "liminal_server_connection_shutdown_control";
/// R6 (§1.2(4)): the single `READY` wake vocabulary for a connection. One atom;
/// any marker (or N coalesced) triggers one full slice servicing all sources.
const CONNECTION_READY_ATOM: &str = "liminal_server_connection_ready";
#[path = "supervisor_fate.rs"]
mod fate;
use fate::ParkedConnectionFates;
#[cfg(test)]
#[path = "supervisor_fate_tests.rs"]
mod fate_tests;
#[cfg(test)]
#[path = "supervisor_shutdown_wake_tests.rs"]
mod shutdown_wake_tests;
#[cfg(test)]
#[path = "supervisor_tests.rs"]
mod tests;
/// Supervisor that owns the beamr scheduler for per-connection processes.
#[derive(Clone, Debug)]
pub struct ConnectionSupervisor {
inner: Arc<SupervisorInner>,
}
impl ConnectionSupervisor {
pub(in crate::server) fn install_signals(
&self,
signals: ServerSignals,
) -> Result<(), ServerError> {
self.inner
.runtime
.signals
.set(signals)
.map_err(|_| ServerError::ListenerAccept {
message: "connection signals were already installed".to_owned(),
})
}
#[cfg(test)]
pub(in crate::server) fn signals_installed(&self) -> bool {
self.inner.runtime.signals.get().is_some()
}
pub(crate) fn current_server_incarnation(&self) -> Result<Option<u64>, ServerError> {
self.inner
.incarnations
.as_ref()
.map(|authority| authority.current_server_incarnation())
.transpose()
}
/// Creates a connection supervisor backed by the services the config's
/// `[services]` profile selects: the full liminal channel/conversation stack
/// (the default) or the capability-scoped worker front door. Profile
/// enforcement is [`build_connection_services`](super::services::build_connection_services)'s,
/// so this constructor can never build full services for a worker-front-door
/// config.
///
/// # Errors
/// Returns [`ServerError`] when service construction or scheduler startup fails.
pub fn from_config(config: &ServerConfig) -> Result<Self, ServerError> {
Self::from_config_with_services(config, build_connection_services(config)?)
}
/// [`Self::from_config`] with the §9 D2 subsystem factory injected.
///
/// The factory is the only route to every scheduler-owning subsystem the
/// services construction builds, so a recording factory observes exactly what
/// was constructed; the connection scheduler itself (built below for BOTH
/// profiles) is the census baseline, not a census entry.
#[cfg(test)]
fn from_config_via(
config: &ServerConfig,
subsystems: &dyn SubsystemFactory,
) -> Result<Self, ServerError> {
Self::from_config_with_services(config, build_connection_services_via(config, subsystems)?)
}
fn from_config_with_services(
config: &ServerConfig,
services: Arc<dyn ConnectionServices>,
) -> Result<Self, ServerError> {
// Absent `[auth]` leaves both `None`, so the connection stays open-access.
let authentication = config
.auth
.as_ref()
.map(configured_authentication)
.transpose()?;
let (auth_token, pass_verifier) =
authentication.map_or((None, None), |(token, verifier)| (Some(token), verifier));
SupervisorInner::new(
services,
None,
auth_token,
pass_verifier,
config
.auth
.as_ref()
.map(|auth| configured_lys(auth, tokio::runtime::Handle::try_current().ok()))
.transpose()?
.flatten(),
config.limits,
None,
)
.map(|inner| Self {
inner: Arc::new(inner),
})
}
/// Starts composing a connection supervisor over services the caller built
/// and keeps: the embedder's constructor.
///
/// Every other public constructor fixes one of the three optional parts —
/// [`Self::from_config`] installs the configured `[auth]` (bearer AND pass
/// verifier) but builds its own services, [`Self::with_services_and_auth`]
/// carries a bearer and never a pass verifier, and
/// [`Self::with_services_and_notifier`] carries a notifier and no auth at
/// all. An application that embeds liminal — holding the
/// `Arc<LiminalConnectionServices>` to publish in-process, verifying
/// registry passes at Connect, and observing connection lifecycle through a
/// notifier — needs all three at once, and this is the one route to them.
/// Nothing set on the builder defaults exactly as the non-config
/// constructors default it: open access, no notifier, signed default
/// limits.
#[must_use]
pub fn builder(services: Arc<dyn ConnectionServices>) -> ConnectionSupervisorBuilder {
ConnectionSupervisorBuilder {
services,
notifier: None,
auth_token: None,
pass_verifier: None,
lys: None,
limits: LimitsConfig::default(),
}
}
/// Creates a connection supervisor with no configured channels.
///
/// # Errors
/// Returns [`ServerError`] when scheduler startup fails.
#[cfg(any(test, feature = "test-support"))]
pub fn new() -> Result<Self, ServerError> {
Self::with_services(Arc::new(LiminalConnectionServices::empty()?))
}
/// Creates a connection supervisor using an explicit service adapter.
///
/// # Errors
/// Returns [`ServerError`] when scheduler startup fails.
pub fn with_services(services: Arc<dyn ConnectionServices>) -> Result<Self, ServerError> {
SupervisorInner::new(
services,
None,
None,
None,
None,
LimitsConfig::default(),
None,
)
.map(|inner| Self {
inner: Arc::new(inner),
})
}
/// Creates a connection supervisor with an explicit service adapter and the
/// configured connection auth token.
///
/// This is the production constructor for callers that build services
/// themselves (the runtime needs the shared channel cluster before the
/// supervisor takes ownership) and therefore cannot use
/// [`Self::from_config`]: without it the configured `[auth]` token would be
/// silently dropped and the server would run open-access.
///
/// # Errors
/// Returns [`ServerError`] when scheduler startup fails.
pub fn with_services_and_auth(
services: Arc<dyn ConnectionServices>,
auth_token: Option<Vec<u8>>,
) -> Result<Self, ServerError> {
Self::with_services_auth_and_limits(services, auth_token, LimitsConfig::default())
}
/// Creates a connection supervisor with explicit services, authentication,
/// and operational limits.
///
/// Production runtime construction uses this form so the durable
/// incarnation stream's complete-reference bound is the same signed
/// `max_connections` bound enforced by connection admission.
///
/// # Errors
/// Returns [`ServerError`] when incarnation startup or scheduler startup fails.
pub fn with_services_auth_and_limits(
services: Arc<dyn ConnectionServices>,
auth_token: Option<Vec<u8>>,
limits: LimitsConfig,
) -> Result<Self, ServerError> {
Self::with_services_auth_limits_and_fatal_shutdown(services, auth_token, limits, None)
}
/// Production composition with the process-wide shutdown activation that a
/// post-Open participant fatal must join, without a Lys install: the
/// fixtures' constructor.
#[cfg(test)]
pub(crate) fn with_fatal_shutdown(
services: Arc<dyn ConnectionServices>,
auth_token: Option<Vec<u8>>,
pass_verifier: Option<PassVerifier>,
limits: LimitsConfig,
fatal_shutdown: ShutdownHandle,
) -> Result<Self, ServerError> {
Self::with_lys_and_fatal_shutdown(
services,
auth_token,
pass_verifier,
None,
limits,
fatal_shutdown,
)
}
/// The production constructor: `[auth]` whole, the Lys install
/// (`[auth.lys]`: admitter, link host, service bindings) included, with
/// the fatal shutdown handle. The server's `run` builds through here so
/// Lys reaches every connection it admits (ACCESS-003 R1 FOUND: the
/// path without `lys` installed none in production).
pub(crate) fn with_lys_and_fatal_shutdown(
services: Arc<dyn ConnectionServices>,
auth_token: Option<Vec<u8>>,
pass_verifier: Option<PassVerifier>,
lys: Option<LysInstall>,
limits: LimitsConfig,
fatal_shutdown: ShutdownHandle,
) -> Result<Self, ServerError> {
SupervisorInner::new(
services,
None,
auth_token,
pass_verifier,
lys,
limits,
Some(fatal_shutdown),
)
.map(|inner| Self {
inner: Arc::new(inner),
})
}
fn with_services_auth_limits_and_fatal_shutdown(
services: Arc<dyn ConnectionServices>,
auth_token: Option<Vec<u8>>,
limits: LimitsConfig,
fatal_shutdown: Option<ShutdownHandle>,
) -> Result<Self, ServerError> {
SupervisorInner::new(
services,
None,
auth_token,
None,
None,
limits,
fatal_shutdown,
)
.map(|inner| Self {
inner: Arc::new(inner),
})
}
/// Creates a connection supervisor with an explicit service adapter and a
/// connection-keyed worker-registration notifier.
///
/// The `notifier` is invoked when a worker registers on a connection and when
/// such a connection closes, and when a pass-stamped connection attaches
/// and closes. Supervisors built via [`Self::with_services`],
/// [`Self::from_config`], or [`Self::new`] carry no notifier, so liminal still
/// runs standalone; a `WorkerRegister` frame is then accepted without any
/// application callback.
///
/// # Errors
/// Returns [`ServerError`] when scheduler startup fails.
pub fn with_services_and_notifier(
services: Arc<dyn ConnectionServices>,
notifier: Arc<dyn ConnectionNotifier>,
) -> Result<Self, ServerError> {
SupervisorInner::new(
services,
Some(notifier),
None,
None,
None,
LimitsConfig::default(),
None,
)
.map(|inner| Self {
inner: Arc::new(inner),
})
}
/// A handle on whether this server can admit a connection, for the
/// readiness probe (P0 #56 R4).
///
/// Handed to `SharedReadinessState::track_admission` once the supervisor
/// exists. The health endpoint binds BEFORE the supervisor is built —
/// liveness has to be answerable while the rest of the server is still
/// coming up — so this cannot be wired at readiness construction and is
/// installed afterwards instead.
#[must_use]
pub fn admission_readiness(&self) -> AdmissionReadiness {
self.inner.admission_readiness.clone()
}
/// The channel membership gate `[auth.lys.membership]` installed
/// (ACCESS-006 R2), for the ACCESS-005 grant owner: it installs itself
/// with [`crate::auth_membership::MembershipGate::install_authority`] and
/// drives each applied change and resume into the gate through
/// [`crate::auth_membership::MembershipListener`]. `None` without the
/// section.
#[must_use]
pub fn membership_gate(&self) -> Option<Arc<crate::auth_membership::MembershipGate>> {
self.inner.runtime.membership_gate().cloned()
}
/// Counts one refused admission, classified by reason.
///
/// Hung on the THREE public admission doors — TCP accept, the sibling
/// transport spawn (WebSocket), and the in-process loopback — because those
/// are the three places a connection can be turned away, and each of them
/// reaches the shared inner body exactly once. Recording deeper would
/// double-count the loopback (which calls the inner body directly);
/// recording shallower would miss the doors that only log.
fn record_admission_refusal(error: &ServerError) {
crate::metrics::admission_refused(AdmissionRefusal::classify(error));
}
/// The runtime every connection process shares. Test-only.
#[cfg(test)]
pub(super) fn runtime_for_test(&self) -> Arc<ConnectionRuntime> {
Arc::clone(&self.inner.runtime)
}
/// Spawns one supervised beamr process that owns `stream`.
///
/// # Errors
/// Returns [`ServerError`] when stream configuration or beamr spawn fails.
pub fn spawn_connection(&self, stream: TcpStream) -> Result<ConnectionHandle, ServerError> {
self.inner
.spawn_connection(stream)
.inspect_err(Self::record_admission_refusal)
}
/// Returns the underlying beamr scheduler.
#[must_use]
pub fn scheduler(&self) -> Arc<Scheduler> {
Arc::clone(&self.inner.scheduler)
}
/// Reaps connection processes that have exited outside the normal handler path.
#[must_use]
pub fn reap_crashed_connections(&self) -> usize {
self.inner.runtime.reap_crashed(&self.inner.scheduler)
}
/// Returns true when `pid` is still tracked by the supervisor.
#[must_use]
pub fn is_tracked(&self, pid: u64) -> bool {
self.inner.runtime.contains(pid)
}
/// Returns the number of tracked live connections.
#[must_use]
pub fn active_connection_count(&self) -> usize {
self.inner.runtime.active_count()
}
/// How many connections have departed this supervisor: the count of
/// connection records removed, raised by the one removal funnel every exit
/// route reaches. A teardown that completes its connection's fate does so
/// before the record is removed, so a departure counted here is one whose
/// fate has already completed. Pass it to [`Self::await_departures`].
///
/// # Errors
/// Returns [`ServerError`] when the departure count's lock is poisoned.
pub fn departures(&self) -> Result<u64, ServerError> {
self.inner.runtime.departures()
}
/// Parks until `count` connections have departed since `since`, a value
/// [`Self::departures`] returned, or until `deadline` elapses. Returns
/// `true` when they have departed and `false` when the deadline won.
///
/// Woken by each departure through the removal `Condvar`, never by a timer
/// or a count scan; the deadline is the one bound on the park.
///
/// # Errors
/// Returns [`ServerError`] when the departure count's lock is poisoned.
pub fn await_departures(
&self,
since: u64,
count: u64,
deadline: Instant,
) -> Result<bool, ServerError> {
self.inner.runtime.await_departures(since, count, deadline)
}
/// Parks until every tracked connection has been removed or `deadline`
/// elapses, returning `true` when the drain completed and `false` when the
/// single admitted deadline won.
///
/// The TOLD drain-completion replacement (W4 leg 3, §4.3): the waiter is woken
/// by the one `remove()` funnel every connection exit reaches — never by a
/// reap/count timer. Both the graceful drain and the force-close settle call
/// this same waiter, each with its own one-shot deadline; there is no second
/// settle poll loop.
#[must_use]
pub(crate) fn wait_for_connections_drained(&self, deadline: Instant) -> bool {
self.inner
.runtime
.wait_for_active_connections_drained(deadline)
}
/// FIX A-ii shutdown flush barrier: parks until every active connection has
/// fanned out its accepted publishes to its socket, or `deadline` elapses.
/// Called in `run_shutdown_sequence` BEFORE the shutdown Disconnect broadcast
/// so an accepted-but-unfanned-out publish can no longer be overtaken by it.
#[must_use]
pub(crate) fn wait_for_delivery_quiesced(&self, deadline: Instant) -> bool {
self.inner.runtime.wait_for_delivery_quiesced(deadline)
}
/// Returns the first latched post-Open participant fatal, if any.
///
/// The production runtime reads this after its existing shutdown handle wakes,
/// then returns the typed fatal after the ordinary drain and durable flush.
pub(crate) fn participant_service_fatal(
&self,
) -> Result<Option<ParticipantServiceFatal>, ServerError> {
self.inner.runtime.participant_service_fatal()
}
/// Returns the beamr process ids of the currently tracked live connections.
///
/// Useful for addressing a specific connection — e.g. as the `pid` argument to
/// [`push_to_connection`](Self::push_to_connection) when the caller knows there
/// is a single connected client.
#[must_use]
pub fn active_connection_pids(&self) -> Vec<u64> {
self.inner
.runtime
.active_connections()
.into_iter()
.map(|connection| connection.pid)
.collect()
}
/// Broadcasts a best-effort shutdown notification to active connections.
///
/// Connections with no active subscriptions ignore the notification. Failures
/// to enqueue the control message are logged and skipped; they are not retried.
pub fn notify_shutdown_subscribers(&self) {
self.inner
.broadcast_control(&ConnectionControl::NotifyShutdown);
}
/// Sends the orderly close control message to every tracked connection
/// process.
///
/// Each live process enqueues one protocol `Disconnect`, drains its
/// outbound buffer, completes its connection fate as `ServerShutdown` and —
/// on the WebSocket transport — writes a close frame carrying
/// `CloseCode::Away` and the reason "server shutdown" before exiting
/// normally. A peer reads a shutdown, not an error. Enqueue failures are
/// logged and skipped.
///
/// Since 0.14.3 this is the ONLY close route in `run_shutdown_sequence`:
/// nothing waits for a peer to hang up first, so the log line below is the
/// ordinary shutdown record rather than a warning about an expired drain.
pub fn force_close_active_connections(&self) {
for connection in self.inner.runtime.active_connections() {
tracing::info!(
connection_pid = connection.pid,
peer_addr = ?connection.peer_addr,
"closing connection for server shutdown"
);
if !self
.inner
.enqueue_control(connection.pid, ConnectionControl::ForceClose)
{
// Observation, not diagnosis — see `broadcast_control`.
tracing::warn!(
connection_pid = connection.pid,
peer_addr = ?connection.peer_addr,
"forceful connection close was not published to the process"
);
}
}
}
/// Installs the services registry (SRV-028), once: lifecycle requests
/// are served from it and its processes' credentials admitted.
///
/// # Errors
/// [`ServerError::ConfigValidation`] when one is already installed.
pub fn install_lifecycle(
&self,
lifecycle: Arc<crate::services::lifecycle::Lifecycle>,
) -> Result<(), ServerError> {
self.inner
.runtime
.lifecycle
.set(lifecycle)
.map_err(|_| ServerError::ConfigValidation {
message: "a services registry was already installed".to_owned(),
})
}
/// Installs the grant-revocation policy (ACCESS-005), once, before the
/// first connection. From then on every `Connect` must present a pass
/// whose grant-decision binding the authority admits and must negotiate
/// the reason-bearing close; a bearer or open-access `Connect` is refused
/// `revocation_binding_missing`.
///
/// # Errors
/// [`ServerError::ConfigValidation`] when an authority is already
/// installed.
pub fn install_revocation(
&self,
authority: Arc<crate::auth_revocation::RevocationAuthority>,
) -> Result<(), ServerError> {
self.inner
.runtime
.install_revocation(authority)
.map_err(|_| ServerError::ConfigValidation {
message: "a grant-revocation authority was already installed".to_owned(),
})
}
/// Applies one event of the Lys grant-change stream the caller owns and
/// reads (ACCESS-005 R2, R4), then tells each affected connection once.
/// The denied state is in force before any connection is told; when a
/// connection's control cannot be published the refusal is counted by
/// name and the connection's own ready wake delivers the sweep. Nothing
/// is retried on a timer.
///
/// # Errors
/// [`ServerError::ConfigValidation`] when no authority is installed.
pub fn apply_grant_event(
&self,
event: &crate::auth_revocation::GrantFeedEvent,
) -> Result<crate::auth_revocation::ApplyOutcome, ServerError> {
let Some(authority) = self.inner.runtime.revocation() else {
return Err(ServerError::ConfigValidation {
message: "no grant-revocation authority is installed".to_owned(),
});
};
let outcome = authority.apply(event);
let mut told = std::collections::BTreeSet::new();
for effect in &outcome.effects {
let pid = effect.pid();
if !told.insert(pid) {
continue;
}
if !self
.inner
.enqueue_control(pid, ConnectionControl::Revocation)
{
authority.record_close_publication_refused(pid);
let woken = self
.inner
.runtime
.ready_waker(pid)
.as_ref()
.is_some_and(super::wake::ReadyWaker::fire);
tracing::warn!(
connection_pid = pid,
woken,
"revocation control refused; the connection's ready wake carries the sweep"
);
}
}
Ok(outcome)
}
/// Pushes an opaque payload to a specific connected client over that client's
/// existing connection and returns an awaiter for the client's correlated reply.
///
/// This is the server-initiated leg (server-to-client), the inverse of every
/// other request frame. It allocates a correlation id, registers a one-shot
/// reply slot keyed by that id, and enqueues a [`ConnectionControl::Push`] for
/// the connection process owning `pid`; that process writes a [`Frame::Push`]
/// out on its socket. When the client answers with a `PushReply` carrying the
/// same correlation id, the connection process resolves the awaiter's slot. The
/// returned [`PushReplyAwaiter`] blocks (bounded) for that reply.
///
/// The reply's lifetime belongs to the push, not to any one
/// [`PushReplyAwaiter::receive`] call: this no-deadline push reserves a slot
/// that is reclaimed only by (a) the reply being consumed or (b) the
/// connection closing. An elapsed `receive` poll is a benign re-arm, never a
/// failure and never a cancellation. The §5
/// `max_pending_pushes_per_connection` cap bounds abandonment; use
/// [`push_to_connection_with_deadline`](Self::push_to_connection_with_deadline)
/// when the reply must have an explicit expiry.
///
/// # Errors
/// Returns [`ServerError`] when the correlation id cannot be allocated, the
/// reply slot cannot be registered, or the control message cannot be enqueued
/// for the (possibly already-gone or concurrently-closing) connection
/// process. PUBLICATION INVARIANT: an `Err` guarantees no `Push` control was
/// published — the client never sees a `Push` frame for a failed call.
/// Conversely `Ok` promises ADMISSION, not delivery: the awaiter's outcome
/// is the delivery truth (a push admitted just as its connection closes
/// resolves to the truthful disconnected outcome, never to a lost reply).
pub fn push_to_connection(
&self,
pid: u64,
payload: Vec<u8>,
) -> Result<PushReplyAwaiter, ServerError> {
self.push_with_deadline(pid, payload, None, None)
}
/// Like [`push_to_connection`](Self::push_to_connection), with the push
/// made ON `subject`: the reply slot retains the subject, and a connection
/// admitted on a Lys pass has its `PushReply` decided as `serve` on that
/// subject before the slot is resolved (the access matrix's `push_binding`
/// source). A refused reply resolves the awaiter to
/// [`ServerError::PushReplyRefused`], so the pusher learns the outcome by
/// type rather than waiting out a deadline. A push made without a subject
/// to a Lys-admitted connection is refused the same way when its reply
/// arrives: the subject is recorded here, at push time, or not at all.
/// `deadline` is as in
/// [`push_to_connection_with_deadline`](Self::push_to_connection_with_deadline).
///
/// # Errors
/// As [`push_to_connection_with_deadline`](Self::push_to_connection_with_deadline).
pub fn push_to_subject(
&self,
pid: u64,
subject: &str,
payload: Vec<u8>,
deadline: Option<Duration>,
) -> Result<PushReplyAwaiter, ServerError> {
self.push_with_deadline(pid, payload, deadline, Some(subject.to_owned()))
}
/// Like [`push_to_connection`](Self::push_to_connection) but attaches an
/// explicit reply deadline to the reserved slot: `deadline` is a DURATION
/// FROM NOW bounding the reply's lifetime — a property of THIS push rather
/// than of any [`PushReplyAwaiter::receive`] wait quantum.
///
/// Deadline expiry is evaluated HOST-SIDE and LAZILY — at the next `receive`
/// touch, and at connection close at the latest. It never wakes the connection
/// process, adds no timer thread, and runs no periodic sweeper: a push that is
/// abandoned and never polled resolves at the next host-side touch (connection
/// close). At expiry the slot resolves to [`ServerError::PushReplyExpired`],
/// is removed, and its §5 `max_pending_pushes_per_connection` cap admission is
/// released. An elapsed `receive` poll BEFORE the deadline is still a benign
/// re-arm. A `receive` call in flight when the deadline falls due returns
/// the terminal expiry PROMPTLY — it waits the earlier of its quantum and
/// the deadline, so a large quantum can never extend the reply's lifetime
/// and the terminal outcome is quantum-independent.
///
/// The deadline is evaluated at OBSERVATION POINTS, not enforced against the
/// wall clock: a reply that arrives before expiry is observed is delivered
/// normally, even if it arrives after the deadline instant. The deadline
/// bounds waiting and slot occupancy; it is not a delivery-freshness
/// guarantee. (This is deliberate — a reply is checked for at every
/// observation point before the deadline is, so an answer in hand always
/// beats an expiry.)
///
/// # Errors
/// Returns [`ServerError`] when `deadline` is not representable on the
/// monotonic clock (an extreme duration is refused, never a panic), the
/// correlation id cannot be allocated, the reply slot cannot be registered,
/// or the control message cannot be enqueued for the (possibly already-gone
/// or concurrently-closing) connection process. PUBLICATION INVARIANT: an
/// `Err` guarantees no `Push` control was published — the client never sees
/// a `Push` frame for a failed call. Conversely `Ok` promises ADMISSION,
/// not delivery: the awaiter's outcome is the delivery truth.
pub fn push_to_connection_with_deadline(
&self,
pid: u64,
payload: Vec<u8>,
deadline: Duration,
) -> Result<PushReplyAwaiter, ServerError> {
self.push_with_deadline(pid, payload, Some(deadline), None)
}
/// Shared body for the no-deadline and explicit-deadline push paths. With
/// `deadline == None` this is byte-for-byte the historical
/// `push_to_connection` behaviour (no per-slot deadline); with `Some`, the
/// slot carries an absolute expiry evaluated lazily at `receive`. `subject`
/// is retained on the slot for the reply's access decision
/// ([`push_to_subject`](Self::push_to_subject)); `None` records no binding.
fn push_with_deadline(
&self,
pid: u64,
payload: Vec<u8>,
deadline: Option<Duration>,
subject: Option<String>,
) -> Result<PushReplyAwaiter, ServerError> {
// S5: an extreme `Duration` must surface as this fallible API's typed
// error, not an `Instant` addition panic. Checked BEFORE any slot is
// registered so a refused deadline leaves nothing to roll back.
let deadline_at = match deadline {
None => None,
Some(window) => {
Some(
Instant::now()
.checked_add(window)
.ok_or_else(|| ServerError::ListenerAccept {
message: format!(
"cannot push to connection process {pid}: reply deadline of {window:?} overflows the monotonic clock"
),
})?,
)
}
};
let correlation_id = self.inner.runtime.next_push_correlation_id();
let receiver =
self.inner
.runtime
.register_push(pid, correlation_id, deadline_at, subject, None)?;
// S3+S7 close-vs-register wall, ordered INSERT -> CONFIRM -> PUBLISH.
// The confirmation runs BEFORE the control is enqueued, which yields the
// PUBLICATION INVARIANT: an `Err` from this method guarantees no `Push`
// control was published — the client never sees a Push for a failed
// call. (Confirming after the enqueue was S7's non-linearizable race: a
// close could sweep, the published Push could already be answered and
// resolved, and the failed confirmation then returned `Err` for a push
// the client had received.) A close landing AFTER a successful confirm
// linearizes after push admission: the enqueue either fails (process
// gone — rollback below, `Err` truthful, nothing delivered) or succeeds
// with the slot already swept, and the awaiter then reads the truthful
// DISCONNECTED while a late client reply is the pinned harmless no-op.
// The exactly-one-side-observes argument lives at
// `confirm_push_registration`.
if !self
.inner
.runtime
.confirm_push_registration(pid, correlation_id)
{
return Err(ServerError::ListenerAccept {
message: format!(
"cannot push to connection process {pid}: the connection closed during push registration"
),
});
}
let control = ConnectionControl::Push {
correlation_id,
payload,
};
if self.inner.enqueue_control(pid, control) {
Ok(PushReplyAwaiter {
correlation_id,
receiver,
deadline: deadline_at,
runtime: Arc::downgrade(&self.inner.runtime),
})
} else {
// The control provably never reached a consumer: `enqueue_control`
// returns false only when the control was never queued at all, or
// when its failed-wake rollback REMOVED the queued control (S8 — an
// entry a drain already consumed counts as published and returns
// true, with the slot lifecycle carrying the delivery truth).
// Dropping the now-unreachable reply slot here therefore keeps the
// publication invariant exact on every `Err` path. The message
// states that outcome rather than naming a cause this branch cannot
// distinguish — the refused-queue case has already warned with its
// own error.
self.inner.runtime.cancel_push(correlation_id);
Err(ServerError::ListenerAccept {
message: format!(
"cannot push to connection process {pid}: the control was not published"
),
})
}
}
/// SRV-027 R4: how many keyed lookups the service directory has made,
/// read by the count pins.
#[must_use]
pub fn directory_lookups(&self) -> u64 {
self.inner.runtime.directory_lookups()
}
/// Flushes durable channel state through the configured liminal services.
///
/// # Errors
/// Returns [`ServerError::ShutdownFlush`] when the underlying service flush fails.
pub fn flush_durable_state(&self) -> Result<(), ServerError> {
self.inner.runtime.services().flush_durable_state()
}
/// Tells the services the listener is bound, so what they read off the
/// start path starts now.
pub(crate) fn listening(&self) {
// The thread runs on its own; nothing waits for it.
drop(self.inner.runtime.services_arc().listening());
}
/// Stops the participant warm and records the clean stop's capacity
/// snapshot, before the final flush (DUR-020 R3, R5).
pub(crate) fn stop_participant_warm(&self) {
self.inner.runtime.services().stop_participant_warm();
}
/// Completes, before a clean stop reports success, every connection fate
/// parked on candidate-lane `Precedence`.
///
/// # Errors
/// Returns [`ServerError::ShutdownUnsettledConnectionFates`] naming every
/// durable Open the stop could not complete.
pub(crate) fn settle_parked_connection_fates(&self) -> Result<(), ServerError> {
self.inner.runtime.settle_parked_connection_fates()
}
/// LP-WS-TRANSPORT R1.3 sibling-transport spawn seam (ADDITIVE ONLY).
///
/// Admits, allocates a durable connection incarnation for, spawns, and
/// registers a connection process whose handler is built by `build_factory`
/// over this supervisor's shared [`ConnectionRuntime`]. The WebSocket
/// sibling acceptor uses this so its connections share the ONE §5
/// `max_connections` admission bound, the one incarnation authority, the
/// one registry (controls, pushes, crash reap, drain, forced close), and the
/// one `apply_frame` seam with TCP connections. The TCP accept path above
/// (`spawn_connection`) is byte-for-byte untouched and never calls this.
///
/// `fd_guard` is a host-held duplicate of the connection's underlying
/// socket, exactly like the TCP path's: it keeps the fd alive until the
/// single record-removal path has synchronously deregistered readiness. It
/// is `None` for a transport that owns no descriptor.
///
/// `mount` is the admitting door's own name for itself (design §10), which
/// is why this seam takes it rather than deriving it: the caller IS the
/// door, and no other party — least of all the client — has any input.
///
/// This method exists because Rust module privacy makes the runtime,
/// admission counter, incarnation authority, and registry unreachable from
/// the sibling `websocket` module family; it is the narrow additive seam
/// that shares them without generalizing any TCP hot path.
///
/// # Errors
/// Returns [`ServerError`] when admission is refused
/// ([`ServerError::ConnectionLimitReached`]), incarnation allocation fails,
/// or beamr spawn/registration fails.
pub(super) fn spawn_transport_connection(
&self,
peer_addr: Option<SocketAddr>,
fd_guard: Option<TcpStream>,
mount: MountKind,
build_factory: &dyn Fn(
Arc<ConnectionRuntime>,
Option<ConnectionIncarnation>,
) -> NativeHandlerFactory,
) -> Result<ConnectionHandle, ServerError> {
self.inner
.spawn_transport_connection(peer_addr, fd_guard, mount, build_factory)
.inspect_err(Self::record_admission_refusal)
}
/// Admits one in-process connection over `server_end` (design §8 step 3).
///
/// This replaces exactly the listener's `accept()` + `spawn_connection`
/// pair, and NOTHING else about admission. It runs the same
/// `try_reserve_admission` against the same §5 slot pool — an in-process
/// connect at capacity is refused with the same typed
/// [`ServerError::ConnectionLimitReached`] a socket connect is — allocates a
/// real durable [`ConnectionIncarnation`] from the same authority, so
/// participant binding, resume, and fate records work identically, and
/// registers the same record. Only two fields differ, and both are honest
/// descriptions rather than semantics: no fd guard (there is no descriptor
/// to keep alive) and `peer_addr: None` (there is no socket to have an
/// address). Nothing on this path reads a socket fact.
///
/// The connection's wake is installed by the process itself on its first
/// serviced slice, which is the earliest point at which its pid and host
/// record — the two things the wake names — both exist.
///
/// `pub(crate)` rather than `pub`: the embedding handle that grants
/// loopback connections lives in this crate, and widening the surface
/// further would hand an outside caller a way to reach the runtime that
/// module privacy currently denies it.
///
/// # Errors
/// Returns [`ServerError`] when admission is refused
/// ([`ServerError::ConnectionLimitReached`]), incarnation allocation fails,
/// or beamr spawn/registration fails.
pub(crate) fn spawn_loopback_connection(
&self,
server_end: LoopbackServerEnd,
) -> Result<ConnectionHandle, ServerError> {
// The same interior-mutability handoff the socket path uses: the native
// handler factory is `Fn + Send + Sync`, so the duplex end cannot be
// moved into it and the FIRST handler build takes it out exactly once.
let holder = Arc::new(Mutex::new(Some(server_end)));
let build = move |runtime: Arc<ConnectionRuntime>,
incarnation: Option<ConnectionIncarnation>|
-> NativeHandlerFactory {
let holder = Arc::clone(&holder);
Box::new(move || {
Box::new(LoopbackConnectionProcess::from_loopback_holder(
Arc::clone(&runtime),
&holder,
incarnation,
))
})
};
self.inner
.spawn_transport_connection(None, None, MountKind::Loopback, &build)
.inspect_err(Self::record_admission_refusal)
}
/// Stops the beamr scheduler used by connection processes.
pub fn shutdown(&self) {
// A connection waiting on a conversation's restore is woken and
// answered at once, so the scheduler join below never waits on a
// room's replay or rebuild (Gaia, 11 October 2026: 60 s).
self.stop_participant_warm();
// Remove every host record while the readiness owner is still live. The
// removal path ACKs deregistration and only then releases each fd guard;
// scheduler shutdown subsequently drops the process-owned handles.
for connection in self.inner.runtime.active_connections() {
self.inner.runtime.finish(connection.pid);
}
self.inner.scheduler.shutdown();
}
/// R7 test instrument: slices serviced by connection `pid` since spawn.
#[cfg(test)]
pub(crate) fn slice_count(&self, pid: u64) -> u64 {
self.inner.runtime.slice_count(pid)
}
/// The mount the admitting door stamped on `pid`'s registry record, or
/// `None` when no record is tracked (design §10).
#[cfg(test)]
pub(crate) fn connection_mount(&self, pid: u64) -> Option<MountKind> {
self.inner.runtime.connection_mount(pid)
}
/// Whether `pid`'s registry record holds an fd guard, or `None` when no
/// record is tracked. A loopback record must answer `Some(false)`: there is
/// no descriptor for the guard to keep alive.
#[cfg(test)]
pub(crate) fn connection_has_fd_guard(&self, pid: u64) -> Option<bool> {
self.inner.runtime.connection_has_fd_guard(pid)
}
/// Installs a one-use readiness marker for the next serviced slice of `pid`.
#[cfg(test)]
pub(crate) fn observe_next_slice(&self, pid: u64) -> Receiver<u64> {
self.inner.runtime.observe_next_slice(pid)
}
/// Installs a one-use readiness marker for the next genuine scheduler park of
/// `pid`. The delivered value is the process's slice count at the final probe
/// that selected `Wait`.
#[cfg(test)]
pub(crate) fn observe_next_park(&self, pid: u64) -> Receiver<u64> {
self.inner.runtime.observe_next_park(pid)
}
/// Returns a marker for the current park when `pid` is already settled, or
/// the next park when a coalesced readiness event has started another slice.
#[cfg(test)]
pub(crate) fn observe_settled_park(&self, pid: u64) -> Receiver<u64> {
self.inner.runtime.observe_settled_park(pid)
}
/// Queues an explicit outbound capacity for the next TCP process constructed.
#[cfg(test)]
pub(crate) fn queue_next_outbound_capacity(&self, capacity: usize) {
self.inner.runtime.queue_next_outbound_capacity(capacity);
}
#[cfg(test)]
pub(crate) fn install_participant_holdback_pause(&self, pid: u64) -> Receiver<()> {
self.inner.runtime.install_participant_holdback_pause(pid)
}
#[cfg(test)]
pub(crate) fn resume_test_process(&self, pid: u64) -> bool {
self.inner.runtime.ready_waker(pid).is_some_and(|waker| {
waker.fire();
true
})
}
/// Server `Push` frames this supervisor's connections have queued for their
/// sockets since it started. A push that failed, was cancelled or was rolled
/// back never reaches a socket and is not counted.
#[must_use]
pub fn pushes_queued(&self) -> u64 {
self.inner.runtime.pushes_queued()
}
/// Reserved push reply slots outstanding (test observability for the public
/// push paths — lets e2e tests assert slot reclamation and cap accounting).
#[cfg(test)]
pub(super) fn pending_push_count(&self) -> usize {
self.inner.runtime.pending_push_count()
}
/// R6 test seam: a [`ReadyWaker`](super::wake::ReadyWaker) for `pid` — the same
/// handle a subscription-inbox or reply-availability notifier fires.
#[cfg(test)]
pub(super) fn ready_waker(&self, pid: u64) -> Option<super::wake::ReadyWaker> {
self.inner.runtime.ready_waker(pid)
}
/// Registered readiness tokens held in host records (test observability).
#[cfg(test)]
pub(super) fn readiness_registration_count(&self) -> usize {
self.inner.runtime.readiness_registration_count()
}
/// Kernel fd registered for `pid` (test observability for fd-reuse races).
#[cfg(test)]
pub(super) fn readiness_fd(&self, pid: u64) -> Option<RawFd> {
self.inner.runtime.readiness_fd(pid)
}
/// The readiness token registered for `pid` (test observability). Lets the
/// fd-reuse successor oracle capture a stale token before reclamation and
/// replay its deregister afterwards, proving it is a keyed no-op.
#[cfg(test)]
pub(super) fn readiness_token(&self, pid: u64) -> Option<ReadinessToken> {
self.inner.runtime.readiness_token(pid)
}
/// Installs the pid-specific reclamation gate (oracle 26) and returns its
/// `(reached, release, done)` endpoints.
#[cfg(test)]
pub(super) fn install_reclaim_barrier(
&self,
pid: u64,
) -> (Arc<Barrier>, Arc<Barrier>, Arc<Barrier>) {
self.inner.runtime.install_reclaim_barrier(pid)
}
/// A weak handle to the connection runtime (test observability): lets a
/// lifetime test assert the runtime — and transitively the durable store's
/// writer lock — is released synchronously at supervisor drop rather than
/// held by the detached reclaim reactor.
#[cfg(test)]
pub(super) fn runtime_weak(&self) -> Weak<ConnectionRuntime> {
Arc::downgrade(&self.inner.runtime)
}
/// Installs a one-use observation for the process-owned stream at `fd` being
/// dropped. External scheduler termination removes the process-table entry
/// before an executing native handler is destroyed, so table absence is not
/// sufficient evidence that the descriptor is reusable.
#[cfg(test)]
pub(super) fn observe_process_stream_drop(&self, fd: RawFd) -> Receiver<()> {
self.inner.runtime.observe_process_stream_drop(fd)
}
/// Installs a one-use arm-to-probe barrier and returns its test endpoints.
#[cfg(test)]
pub(super) fn install_pre_wait_barrier(&self) -> (Arc<Barrier>, Arc<Barrier>) {
self.inner.runtime.install_pre_wait_barrier()
}
/// Barrier-staged final probes that observed newly arrived work.
#[cfg(test)]
pub(super) fn pre_wait_probe_hits(&self) -> u64 {
self.inner.runtime.pre_wait_probe_hits()
}
/// Installs the one-use drain-park gate (oracles 18, 19) and returns its
/// `(armed, release)` endpoints.
#[cfg(test)]
pub(super) fn install_drain_park_barrier(&self) -> (Arc<Barrier>, Arc<Barrier>) {
self.inner.runtime.install_drain_park_barrier()
}
/// Drain waiter wakes that observed a real connection removal (oracle 12).
#[cfg(test)]
pub(super) fn drain_exit_wakes(&self) -> u64 {
self.inner.runtime.drain_exit_wakes()
}
/// Drain waiter deadline expirations (oracles 12, 16).
#[cfg(test)]
pub(super) fn drain_deadline_hits(&self) -> u64 {
self.inner.runtime.drain_deadline_hits()
}
}
/// Handle for one supervised connection process.
#[derive(Clone, Debug)]
pub struct ConnectionHandle {
pid: u64,
peer_addr: Option<SocketAddr>,
connection_incarnation: Option<ConnectionIncarnation>,
supervisor: Arc<SupervisorInner>,
}
impl ConnectionHandle {
/// Every later report of the frames this connection writes to its
/// transport. Test-only (R3b F8, ruling 2a).
#[cfg(test)]
pub(crate) fn observe_frames_written(&self) -> Receiver<Vec<liminal::protocol::FrameType>> {
self.supervisor.runtime.observe_frames_written(self.pid)
}
/// Returns the beamr process id for this connection.
#[must_use]
pub const fn pid(&self) -> u64 {
self.pid
}
/// Returns the peer address if it was available from the accepted stream.
#[must_use]
pub const fn peer_addr(&self) -> Option<SocketAddr> {
self.peer_addr
}
/// Returns the durable participant connection incarnation, when this
/// supervisor has a complete participant service installed.
///
/// `None` identifies a services adapter that does not advertise participant
/// lifecycle semantics.
#[must_use]
pub const fn connection_incarnation(&self) -> Option<ConnectionIncarnation> {
self.connection_incarnation
}
/// Returns whether the beamr process is still live.
#[must_use]
pub fn is_live(&self) -> bool {
self.supervisor
.scheduler
.process_table()
.get(self.pid)
.is_some()
}
/// Requests an error exit for tests and supervisor control paths.
///
/// # Errors
/// Returns [`ServerError`] when the process is no longer live.
pub fn request_crash(&self) -> Result<(), ServerError> {
if self
.supervisor
.scheduler
.enqueue_atom_message(self.pid, Atom::ERROR)
{
Ok(())
} else {
Err(ServerError::ListenerAccept {
message: format!("connection process {} is not live", self.pid),
})
}
}
}
/// Awaits the correlated reply to a single server-initiated push.
///
/// Returned by [`ConnectionSupervisor::push_to_connection`]. The reply slot is
/// resolved when the originating connection process receives a `PushReply` frame
/// carrying the same correlation id, so [`PushReplyAwaiter::receive`] blocks
/// (bounded) for that one correlated answer.
#[derive(Debug)]
pub struct PushReplyAwaiter {
correlation_id: u64,
receiver: Receiver<PushSlotResolution>,
/// This push's absolute reply deadline, mirrored from its slot. `None` (the
/// default push) selects the no-deadline receive path, which NEVER touches
/// the runtime — byte-compatible with 0.2.3, no shared-lock exposure.
/// `Some` lets `receive` wait `min(caller quantum, time until deadline)` and
/// resolve expiry promptly, so the caller's quantum can never select a
/// deadlined push's terminal outcome.
deadline: Option<Instant>,
/// Weak handle to the owning runtime, used ONLY by the explicit-deadline
/// path to resolve expiry host-side at [`receive`](Self::receive). A
/// no-deadline push never upgrades it. `Weak` so the awaiter never keeps the
/// runtime alive; if it is already gone, the slot (and its sender) is gone
/// with it — the connection side is torn down.
runtime: Weak<ConnectionRuntime>,
}
impl PushReplyAwaiter {
/// Returns the correlation id this awaiter is matched on.
#[must_use]
pub const fn correlation_id(&self) -> u64 {
self.correlation_id
}
/// Blocks up to `timeout` for the client's correlated reply payload.
///
/// `timeout` is a WAIT QUANTUM ONLY — a MAXIMUM wait, not a promise to
/// block: an elapsed poll is a benign re-arm, never a failure; the reply's
/// lifetime belongs to the push. A caller may re-invoke `receive`
/// indefinitely after a [`ServerError::PushReplyTimeout`]: the reserved slot
/// is untouched and a later reply is still delivered byte-exact. The poll
/// quantum never changes the protocol outcome — for a deadlined push the
/// call waits no longer than the EARLIER of the caller's quantum and the
/// push's deadline, so the terminal expiry is returned promptly once due,
/// never held until the quantum ends and never deferred past it.
///
/// A push with no explicit deadline never touches shared supervisor state
/// here: the elapsed quantum returns straight from the channel wait
/// (behaviour-compatible with 0.2.3 — no registry lock, no contention, no
/// poison exposure on the unchanged API).
///
/// # Errors
/// Returns [`ServerError::PushReplyTimeout`] when no reply arrived within this
/// `timeout` quantum and the push's deadline (if any) is not yet due (a
/// benign re-arm — call again to keep waiting);
/// [`ServerError::PushReplyExpired`] when the push carried an explicit reply
/// deadline (via
/// [`push_to_connection_with_deadline`](ConnectionSupervisor::push_to_connection_with_deadline))
/// and that deadline is due (terminal: the slot is removed and its §5 cap
/// admission released; returned as soon as the deadline passes, even
/// mid-quantum — but evaluated at observation points, not against the wall
/// clock: a reply already delivered when this call observes the slot wins
/// over expiry, even if it arrived after the deadline instant); or
/// [`ServerError::PushReplyDisconnected`] when the connection process
/// dropped the reply slot (the connection closed — the prompt worker-death
/// signal). The variants are distinct so callers classify by type, not
/// message.
pub fn receive(&self, timeout: Duration) -> Result<Vec<u8>, ServerError> {
self.deadline.map_or_else(
|| self.receive_no_deadline(timeout),
|deadline| self.receive_deadlined(timeout, deadline),
)
}
/// The default-push receive: exactly the 0.2.3 shape. One bounded channel
/// wait; an elapsed quantum is a benign timeout straight from the channel —
/// no runtime upgrade, no registry lock, EVER (unrelated registry work can
/// never stretch this call past its quantum, and registry poison cannot
/// reach it).
fn receive_no_deadline(&self, timeout: Duration) -> Result<Vec<u8>, ServerError> {
match self.receiver.recv_timeout(timeout) {
Ok(resolution) => self.resolution_into_result(resolution),
Err(RecvTimeoutError::Timeout) => Err(ServerError::PushReplyTimeout {
correlation_id: self.correlation_id,
}),
Err(RecvTimeoutError::Disconnected) => Err(ServerError::PushReplyDisconnected {
correlation_id: self.correlation_id,
}),
}
}
/// The deadlined receive: waits `min(caller quantum, time until deadline)`
/// and re-evaluates reply-first-then-expiry on every wake, so the caller's
/// quantum can never select the terminal outcome (S1). Order per iteration:
///
/// 1. Deliver a reply already in hand — an answer that is here must never be
/// reported as a timeout OR an expiry (the observation-point rule).
/// 2. If the deadline is due, resolve expiry atomically against the registry
/// (`expire_slot`) and return the terminal outcome promptly — even when
/// the caller's quantum has time left (the quantum is a max wait).
/// 3. Otherwise wait for the earlier of quantum-remaining and deadline; a
/// wake re-runs 1-2, and an exhausted quantum before the deadline is the
/// benign `PushReplyTimeout` re-arm with the slot untouched.
fn receive_deadlined(
&self,
timeout: Duration,
deadline: Instant,
) -> Result<Vec<u8>, ServerError> {
let started = Instant::now();
loop {
if let Some(result) = self.try_take_reply() {
return result;
}
let now = Instant::now();
if now >= deadline {
return self.expire_slot();
}
let quantum_left = timeout.saturating_sub(now.duration_since(started));
if quantum_left.is_zero() {
return Err(ServerError::PushReplyTimeout {
correlation_id: self.correlation_id,
});
}
match self
.receiver
.recv_timeout(quantum_left.min(deadline.duration_since(now)))
{
Ok(resolution) => return self.resolution_into_result(resolution),
Err(RecvTimeoutError::Disconnected) => {
return Err(ServerError::PushReplyDisconnected {
correlation_id: self.correlation_id,
});
}
// Re-loop: deliver a reply that raced the wake, expire a
// now-due deadline, or report the exhausted quantum benignly.
Err(RecvTimeoutError::Timeout) => {}
}
}
}
/// Resolves a due deadline against the registry's atomic removal transition.
fn expire_slot(&self) -> Result<Vec<u8>, ServerError> {
let timeout_error = || ServerError::PushReplyTimeout {
correlation_id: self.correlation_id,
};
let Some(runtime) = self.runtime.upgrade() else {
// The runtime is gone, and the slot map (with every sender) with it:
// the connection side is torn down. Re-check the channel so the
// dropped sender reads as the established DISCONNECTED outcome — a
// dead runtime must not be misreported as a benign healthy-but-slow
// timeout (S4).
return self
.try_take_reply()
.unwrap_or(Err(ServerError::PushReplyDisconnected {
correlation_id: self.correlation_id,
}));
};
match runtime.expire_push_if_due(self.correlation_id) {
PushSlotDisposition::Expired => Err(ServerError::PushReplyExpired {
correlation_id: self.correlation_id,
}),
// Unreachable by construction (this is only called with the deadline
// due, and the registry re-reads a monotonic clock); honest benign
// fallback rather than a panic.
PushSlotDisposition::Live => Err(timeout_error()),
// Another path (a concurrent `resolve_push`, or connection close)
// removed the slot under the registry lock while we waited on it. Its
// send, if any, happens under that same lock, so re-check the channel:
// a delivered reply is present now; a dropped sender is disconnected.
PushSlotDisposition::Absent => self
.try_take_reply()
.unwrap_or_else(|| Err(timeout_error())),
}
}
/// SRV-027 R2: the outcome if the slot has resolved, read without waiting
/// by the requester's slice after its wake: `Some(Ok(payload))` for the
/// worker's reply, `Some(Err(..))` for a refusal, a frame the worker's
/// connection could not carry, or the worker gone (the slot swept at its
/// close), `None` while nothing has arrived.
pub(super) fn try_receive(&self) -> Option<Result<Vec<u8>, ServerError>> {
self.try_take_reply()
}
/// Non-blocking check for a reply already sitting in the channel. `Some` with
/// the payload or a disconnected error; `None` when the channel is still empty
/// (no reply yet — the caller re-arms).
fn try_take_reply(&self) -> Option<Result<Vec<u8>, ServerError>> {
match self.receiver.try_recv() {
Ok(resolution) => Some(self.resolution_into_result(resolution)),
Err(TryRecvError::Disconnected) => Some(Err(ServerError::PushReplyDisconnected {
correlation_id: self.correlation_id,
})),
Err(TryRecvError::Empty) => None,
}
}
/// Turns one delivered [`PushSlotResolution`] into this awaiter's result, so
/// all three receive paths read a resolution the same way and none of them
/// can grow its own interpretation of one.
///
/// Note what is NOT here: a dropped `Sender` never reaches this function. It
/// is a channel disconnect, and so stays the retryable
/// [`ServerError::PushReplyDisconnected`] on every path that kills a slot
/// without naming a reason — connection close included.
fn resolution_into_result(
&self,
resolution: PushSlotResolution,
) -> Result<Vec<u8>, ServerError> {
match resolution {
PushSlotResolution::Reply(payload) => Ok(payload),
PushSlotResolution::ReplyRefused { reason } => Err(ServerError::PushReplyRefused {
correlation_id: self.correlation_id,
reason,
}),
PushSlotResolution::OutboundFrameTooLarge {
needed,
capacity,
queued,
} => Err(ServerError::PushFrameExceedsOutboundCapacity {
correlation_id: self.correlation_id,
needed,
capacity,
queued,
}),
}
}
}
/// The kernel-parked exit-event reactor (W4 leg 1 reclamation carve-out, §4.1).
/// It is the single TOLD source that reclaims connection host records for
/// processes that exit WITHOUT a final handler slice, replacing the retired
/// per-accept `reap_crashed` scan for that class.
///
/// It blocks on beamr's sole exit-event subscription — never polling, never
/// timed — and on each delivered [`ExitEvent::Exited`] it (1) drains the
/// retained additive outcome so beamr's exactly-once outcome store stays bounded
/// (we are the sole subscriber and therefore the sole drainer) and (2) reclaims
/// the pid through [`ConnectionRuntime::reclaim_terminated`], which funnels into
/// `remove()`. On the bounded queue's [`ExitEvent::Lagged`] overflow marker it
/// runs exactly one reconciliation pass over the tracked records (beamr's
/// documented recovery), driven by that one TELL — not a timer.
///
/// It holds WEAK handles to both the scheduler and the runtime and upgrades them
/// per event, so it never keeps either alive past supervisor drop. It returns
/// when the subscription disconnects (scheduler and publisher dropped) OR when a
/// per-event upgrade fails — both observed at an event delivery, never sampled,
/// so there is no stop flag (LAW-1). The runtime and its durable store therefore
/// release synchronously at supervisor drop rather than after the reactor exits.
fn run_reclaim_reactor(
subscription: &ExitEventSubscription,
scheduler: &Weak<Scheduler>,
runtime: &Weak<ConnectionRuntime>,
) {
loop {
match subscription.recv() {
Ok(ExitEvent::Exited { pid, reason }) => {
let Some(runtime) = runtime.upgrade() else {
return;
};
runtime.deliver_reclamation(scheduler, pid, reason);
}
Ok(ExitEvent::Lagged) => {
let (Some(runtime), Some(scheduler)) = (runtime.upgrade(), scheduler.upgrade())
else {
return;
};
runtime.reap_crashed(&scheduler);
}
Err(error) => {
// The sole crash-reclamation source for a process that dies
// without a final slice is ending. Named at the same volume as
// the startup branch that finds no subscription at all.
tracing::warn!(
%error,
"connection reclamation reactor stopping; external-termination \
reclamation has no further TOLD exit source"
);
return;
}
}
}
}
pub(super) struct SupervisorInner {
scheduler: Arc<Scheduler>,
runtime: Arc<ConnectionRuntime>,
incarnations: Option<Arc<ConnectionIncarnationAuthority>>,
/// P0 #56 R4: the readiness probe's view of whether this server can admit.
/// Shared with the incarnation authority when one is installed.
admission_readiness: AdmissionReadiness,
}
impl std::fmt::Debug for SupervisorInner {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("SupervisorInner")
.field("runtime", &self.runtime)
.finish_non_exhaustive()
}
}
/// The configured `[auth]` section as the supervisor carries it: the bearer
/// token as opaque bytes for the handshake's constant-time comparison, and the
/// registry pass verifier built from `auth.pass` when one is configured. The
/// single derivation behind [`ConnectionSupervisor::from_config`] and
/// [`ConnectionSupervisorBuilder::auth`], so the two cannot drift.
fn configured_authentication(
auth: &AuthConfig,
) -> Result<(Vec<u8>, Option<PassVerifier>), ServerError> {
let pass_verifier = PassVerifier::from_auth(auth)?;
Ok((auth.token.clone().into_bytes(), pass_verifier))
}
/// Composes a [`ConnectionSupervisor`] over caller-owned services.
///
/// Any of the optional parts — `[auth]` (bearer + pass verifier), a connection
/// notifier, operational limits — can be set together. Minted by
/// [`ConnectionSupervisor::builder`].
#[derive(Debug)]
pub struct ConnectionSupervisorBuilder {
services: Arc<dyn ConnectionServices>,
notifier: Option<Arc<dyn ConnectionNotifier>>,
auth_token: Option<Vec<u8>>,
pass_verifier: Option<PassVerifier>,
lys: Option<LysInstall>,
limits: LimitsConfig,
}
/// What `[auth.lys]` installs on the connection runtime: the admitter with
/// the network id its subjects are placed under (ACCESS-001 R2), the
/// machine's link host (ACCESS-002 R1), the service bindings (ACCESS-003 R1)
/// and the channel membership gate (ACCESS-006 R1).
#[derive(Debug)]
pub struct LysInstall {
/// Admits a Lys pass at `Connect` and decides its routes.
pub(crate) admitter: Arc<dyn crate::auth_lys::session::LysAdmitter>,
/// The network every subject is placed under.
pub(crate) network_id: String,
/// This machine's link host, `[auth.lys.machine]`.
pub(crate) link_host: Option<Arc<crate::link::LinkHost>>,
/// The service effect seams, `[auth.lys.services]`.
pub(crate) services: Option<Arc<crate::services::production::ServiceBindings>>,
/// The channel membership gate `[auth.lys.membership]` configures, over
/// the same issuer.
pub(crate) membership: Option<Arc<crate::auth_membership::MembershipGate>>,
}
/// The tokio runtime Lys is asked on, live deliberate decisions and the
/// service bindings' HTTP alike, owned by the server for its life; `None`
/// without `[auth.lys]`. One worker: every ask is one short request made
/// from a connection's slice through `Handle::block_on` on a scoped thread,
/// never a runtime nested in the connection scheduler.
///
/// # Errors
/// The runtime could not start, by name.
pub fn lys_ask_runtime(
auth: Option<&AuthConfig>,
) -> Result<Option<tokio::runtime::Runtime>, ServerError> {
if auth.is_none_or(|auth| auth.lys.is_none()) {
return Ok(None);
}
tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.thread_name("liminal-lys-ask")
.enable_all()
.build()
.map(Some)
.map_err(|error| ServerError::ConfigValidation {
message: format!("the Lys ask runtime could not start: {error}"),
})
}
/// Builds the Lys admitter `[auth.lys]` configures, reading the issuer's key
/// set once; `None` without the section. `ask_handle` is the runtime live
/// asks run on ([`lys_ask_runtime`], or an embedder's own); `auth.lys.live`
/// without one is refused at start, by name.
///
/// # Errors
/// A key set, pass or identity that cannot be read or is refused, by name.
pub fn configured_lys(
auth: &AuthConfig,
ask_handle: Option<tokio::runtime::Handle>,
) -> Result<Option<LysInstall>, ServerError> {
let Some(lys) = auth.lys.as_ref() else {
return Ok(None);
};
let keys_json =
std::fs::read_to_string(&lys.keys_path).map_err(|error| ServerError::ConfigValidation {
message: format!("auth.lys.keys_path {}: {error}", lys.keys_path.display()),
})?;
let mut adapter = crate::auth_lys::lys_pass_adapter::LysPassAdapter::from_keys_json(
&keys_json,
lys.issuer.clone(),
)
.map_err(|error| ServerError::ConfigValidation {
message: format!("auth.lys key set refused: {error}"),
})?;
if lys.live {
// Deliberate decisions ask the issuer live, with the holder's pass,
// on the server's runtime; the ask never nests a runtime.
let Some(handle) = ask_handle else {
return Err(ServerError::ConfigValidation {
message:
"auth.lys.live needs the server's Lys ask runtime at start; none was given"
.to_owned(),
});
};
let mut live = crate::auth_lys::live::HttpLysAsk::new(
lys.api_url.as_deref().unwrap_or(&lys.issuer),
handle,
)
.map_err(|error| ServerError::ConfigValidation {
message: format!("auth.lys.issuer refused for live asks: {error}"),
})?;
// Lys answers its batch check for an administrator or an app, never
// a seat's pass: with an app credential configured the question is
// asked as this liminal, about the holder.
if let Some(path) = lys.app_credential_path.as_ref() {
let credential =
std::fs::read_to_string(path).map_err(|error| ServerError::ConfigValidation {
message: format!(
"auth.lys.app_credential_path '{}' cannot be read: {}",
path.display(),
error.kind()
),
})?;
live = live.asking_as(credential.trim().to_owned());
}
adapter = adapter.with_live(Arc::new(live));
}
let adapter = Arc::new(adapter);
let link_host = lys
.machine
.as_ref()
.map(|machine| configured_link_host(adapter.as_ref(), machine))
.transpose()?
.map(Arc::new);
let admitter: Arc<dyn crate::auth_lys::session::LysAdmitter> =
Arc::new(crate::auth_lys::session::ConsumerAdmitter::new(adapter));
let membership = lys
.membership
.as_ref()
.map(|membership| crate::auth_membership::configured_gate(membership, &lys.issuer))
.transpose()?;
Ok(Some(LysInstall {
admitter,
network_id: lys.network_id.clone(),
link_host,
services: None,
membership,
}))
}
/// Reads 32 bytes as 64 hexadecimal digits, naming `what` in the refusal.
fn hex_key(what: &str, digits: &str) -> Result<[u8; 32], ServerError> {
let bytes = hex::decode(digits.trim()).map_err(|error| ServerError::ConfigValidation {
message: format!("{what} is not hexadecimal: {error}"),
})?;
<[u8; 32]>::try_from(bytes).map_err(|bytes| ServerError::ConfigValidation {
message: format!("{what} is {} bytes, not 32", bytes.len()),
})
}
/// Builds this liminal as a machine Lys knows from `[auth.lys.machine]`
/// (ACCESS-002 R1): its identity from the seed file, its own link rights from
/// its own pass verified like any other, and the recorded machine keys.
fn configured_link_host(
adapter: &crate::auth_lys::lys_pass_adapter::LysPassAdapter,
machine: &crate::config::types::MachineConfig,
) -> Result<crate::link::LinkHost, ServerError> {
use crate::auth_lys::LysPassConsumer;
let seed_digits = std::fs::read_to_string(&machine.identity_path).map_err(|error| {
ServerError::ConfigValidation {
message: format!(
"auth.lys.machine.identity_path {}: {error}",
machine.identity_path.display()
),
}
})?;
let seed = zeroize::Zeroizing::new(hex_key("auth.lys.machine identity seed", &seed_digits)?);
let local =
crate::link_handshake::LocalMachine::new(lys_core::keys::Ed25519Identity::from_seed(&seed));
let pass_bytes =
std::fs::read(&machine.pass_path).map_err(|error| ServerError::ConfigValidation {
message: format!(
"auth.lys.machine.pass_path {}: {error}",
machine.pass_path.display()
),
})?;
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_secs());
let pass = adapter
.verify_offline(&pass_bytes, crate::auth_lys::LIMINAL_PASS_AUDIENCE, now)
.map_err(|error| ServerError::ConfigValidation {
message: format!("auth.lys.machine pass refused: {error}"),
})?;
let rights = crate::auth_lys::lys_pass_adapter::MachineLinkRights::new(adapter, pass);
let mut recorded = std::collections::BTreeMap::new();
for (holder, digits) in &machine.machines {
let key = hex_key(&format!("auth.lys.machine.machines.{holder}"), digits)?;
recorded.insert(
holder.clone(),
crate::link_handshake::MachineIdentity::new(key),
);
}
Ok(crate::link::LinkHost::new(
local,
Box::new(rights),
recorded,
))
}
impl ConnectionSupervisorBuilder {
/// Installs the configured `[auth]` section: the bearer token, and the
/// registry pass verifier when `auth.pass` is present — derived exactly as
/// [`ConnectionSupervisor::from_config`] derives them.
///
/// # Errors
/// Returns [`ServerError::ConfigValidation`] when `auth.pass` names a key
/// that is not exactly one valid Ed25519 verifying key as 64 hexadecimal
/// digits — the same error, with the same text, that `from_config` returns
/// for that configuration.
pub fn auth(mut self, auth: &AuthConfig) -> Result<Self, ServerError> {
let (auth_token, pass_verifier) = configured_authentication(auth)?;
self.auth_token = Some(auth_token);
self.pass_verifier = pass_verifier;
self.lys = configured_lys(auth, tokio::runtime::Handle::try_current().ok())?;
Ok(self)
}
/// Test seam: installs `lys` exactly as `[auth.lys]` would, with no
/// configuration file and no issuer key behind it.
#[cfg(test)]
#[must_use]
pub(super) fn lys_for_tests(mut self, lys: LysInstall) -> Self {
self.lys = Some(lys);
self
}
/// Installs the connection-keyed notifier, invoked on worker registration
/// lifecycle and on pass-stamped attach/detach.
#[must_use]
pub fn notifier(mut self, notifier: Arc<dyn ConnectionNotifier>) -> Self {
self.notifier = Some(notifier);
self
}
/// Installs the operational limits (§5); unset, the signed defaults apply.
#[must_use]
pub const fn limits(mut self, limits: LimitsConfig) -> Self {
self.limits = limits;
self
}
/// Starts the supervisor.
///
/// # Errors
/// Returns [`ServerError`] when incarnation startup or scheduler startup
/// fails.
pub fn build(self) -> Result<ConnectionSupervisor, ServerError> {
SupervisorInner::new(
self.services,
self.notifier,
self.auth_token,
self.pass_verifier,
self.lys,
self.limits,
None,
)
.map(|inner| ConnectionSupervisor {
inner: Arc::new(inner),
})
}
}
/// Installs the `[auth.lys]` parts on the runtime, each once: the admitter,
/// the link host, the membership gate and the service bindings.
fn install_lys(runtime: &ConnectionRuntime, lys: LysInstall) -> Result<(), ServerError> {
let LysInstall {
admitter,
network_id,
link_host,
services: bindings,
membership,
} = lys;
runtime
.install_lys_admitter(admitter, network_id)
.map_err(|_| ServerError::ConfigValidation {
message: "auth.lys admitter was already installed".to_owned(),
})?;
if let Some(host) = link_host {
runtime
.install_link_host(host)
.map_err(|_| ServerError::ConfigValidation {
message: "auth.lys.machine was already installed".to_owned(),
})?;
}
if let Some(gate) = membership {
runtime
.install_membership_gate(gate)
.map_err(|_| ServerError::ConfigValidation {
message: "auth.lys.membership was already installed".to_owned(),
})?;
}
if let Some(bindings) = bindings {
runtime
.install_service_bindings(bindings)
.map_err(|_| ServerError::ConfigValidation {
message: "auth.lys.services was already installed".to_owned(),
})?;
}
Ok(())
}
impl SupervisorInner {
fn new(
services: Arc<dyn ConnectionServices>,
notifier: Option<Arc<dyn ConnectionNotifier>>,
auth_token: Option<Vec<u8>>,
pass_verifier: Option<PassVerifier>,
lys: Option<LysInstall>,
limits: LimitsConfig,
fatal_shutdown: Option<ShutdownHandle>,
) -> Result<Self, ServerError> {
let installed_services = ConnectionServiceInstallation::capture(services);
// P0 #56 R4. Owned by the supervisor so the readiness probe has a stable
// handle whether or not a participant service (and therefore an
// incarnation authority) is installed: a server with no authority has
// nothing that can hold admission, and reports available.
let admission_readiness = AdmissionReadiness::available();
let incarnations = installed_services
.participant_service
.as_ref()
.map(
|service| -> Result<Arc<ConnectionIncarnationAuthority>, ServerError> {
ConnectionIncarnationAuthority::startup(
service.durable_store(),
limits.max_connections,
service.publication_conversation_limit(),
service,
admission_readiness.clone(),
)
.map(Arc::new)
},
)
.transpose()?;
let atoms = AtomTable::with_common_atoms();
let control_atom = atoms.intern(CONNECTION_SHUTDOWN_CONTROL_ATOM);
let registry = Arc::new(ModuleRegistry::new());
let scheduler = Scheduler::with_services(
SchedulerConfig {
thread_count: Some(CONNECTION_SCHEDULER_THREADS),
..SchedulerConfig::default()
},
SchedulerServices::from_config().owned_readiness(),
registry,
// The strongest of the three cases: `registry` here is a bare
// `ModuleRegistry::new()` with NO module ever inserted, so this
// scheduler cannot execute a single bytecode instruction, let alone
// a guard BIF. Connections run as native processes via
// `NativeHandlerFactory`. beamr 0.19 requires the answer be written
// down rather than inherited; the answer is none.
NativeBifs::none(),
)
.map_err(|message| ServerError::ListenerAccept {
message: format!("failed to start connection scheduler: {message}"),
})?;
let ready_atom = atoms.intern(CONNECTION_READY_ATOM);
let scheduler = Arc::new(scheduler);
// The runtime captures a WEAK handle to the connection scheduler so
// notifier wakes (R3/R1(vi)) can be fired from another actor's slice
// without a strong scheduler↔process↔runtime cycle that would leak the
// whole connection scheduler.
let runtime = Arc::new(ConnectionRuntime::new(
ConnectionRuntimeInstallation {
services: installed_services,
incarnations: incarnations.clone(),
fatal_shutdown,
},
control_atom,
ready_atom,
Arc::downgrade(&scheduler),
notifier,
(auth_token, pass_verifier),
limits,
));
if let Some(lys) = lys {
install_lys(&runtime, lys)?;
}
// A connection fate parked on candidate-lane `Precedence` is retried by
// the drain that clears it, so the runtime is told about every drain.
if let (Some(service), Some(notifier)) = (runtime.participant_service(), runtime.notifier())
{
service.install_checkpoint_crossing_observer(Arc::clone(notifier));
}
if let Some(service) = runtime.participant_service() {
let runtime_weak: Weak<ConnectionRuntime> = Arc::downgrade(&runtime);
let listener: Weak<dyn CandidateLaneListener> = runtime_weak;
service
.install_candidate_lane_listener(listener)
.map_err(|error| ServerError::ParticipantIncarnation {
phase: "candidate-lane listener installation",
message: error.to_string(),
})?;
}
// W4 leg 1 reclamation carve-out (§4.1): the kernel-parked exit-event
// reactor is the TOLD source that reclaims a connection host record whose
// process exited WITHOUT a final handler slice (external/panic
// termination). It blocks on beamr's single exit-event subscription —
// never a poll — and routes every reclamation through the same `remove()`
// funnel as an ordinary exit. Detached on purpose: it exits when the
// scheduler (and so its event publisher) drops, so there is no stop flag
// to sample (LAW-1).
match scheduler.subscribe_exit_events() {
Some(subscription) => {
let reactor_scheduler = Arc::downgrade(&scheduler);
// WEAK, symmetric with the scheduler handle: the reactor must not
// keep the runtime (and its durable store's writer lock) alive past
// supervisor drop. It upgrades per event and exits on a failed
// upgrade, so the runtime is released synchronously at drop.
let reactor_runtime = Arc::downgrade(&runtime);
thread::Builder::new()
.name("liminal-connection-reclaim".to_owned())
.spawn(move || {
run_reclaim_reactor(&subscription, &reactor_scheduler, &reactor_runtime);
})
.map_err(|error| ServerError::ListenerAccept {
message: format!("failed to start connection reclamation reactor: {error}"),
})?;
}
None => {
tracing::error!(
"connection scheduler exit-event subscription unavailable; \
external-termination reclamation has no TOLD exit source (the \
shutdown-drain scan that once backstopped it was retired by W4 leg 3)"
);
}
}
Ok(Self {
scheduler,
runtime,
incarnations,
admission_readiness,
})
}
fn spawn_connection(
self: &Arc<Self>,
stream: TcpStream,
) -> Result<ConnectionHandle, ServerError> {
// §5 `max_connections`: ATOMIC admission reservation acquired BEFORE any
// process construction (review round 1 item 7 — a signed bound must not
// be exceedable by concurrent callers; check-then-spawn across an
// unlocked window was). The CAS reservation is released on every failure
// path below and converts into the connection record at `register`;
// thereafter the single record-removal path (`remove`) releases it. An
// over-cap accept therefore costs nothing and the bound holds under any
// concurrency.
self.runtime.try_reserve_admission()?;
let reservation = AdmissionReservation {
runtime: &self.runtime,
armed: true,
};
stream
.set_nonblocking(true)
.map_err(|error| ServerError::ListenerAccept {
message: format!("failed to configure connection stream: {error}"),
})?;
// A failed `peer_addr` is folded to `None` rather than refusing the
// accept: an unidentifiable peer is still a serviceable connection. The
// cost is paid in triage, not in service — every later log line for this
// connection reports `peer_addr=None`, so nothing that happens on it can
// be tied back to a remote endpoint.
let peer_addr = stream.peer_addr().ok();
// The host-held duplicate keeps the fd alive until the single record-removal
// path has synchronously deregistered readiness. External process death can
// therefore never let fd reuse overtake host-side deregistration.
let fd_guard = stream
.try_clone()
.map_err(|error| ServerError::ListenerAccept {
message: format!("failed to retain connection fd for teardown: {error}"),
})?;
let connection_incarnation = self.allocate_connection_incarnation()?;
let holder = Arc::new(Mutex::new(Some(stream)));
let runtime = Arc::clone(&self.runtime);
let process_holder = Arc::clone(&holder);
let factory: NativeHandlerFactory = Box::new(move || {
Box::new(ConnectionProcess::from_holder(
Arc::clone(&runtime),
peer_addr,
&process_holder,
connection_incarnation,
))
});
let pid =
self.scheduler
.spawn_native(factory)
.map_err(|error| ServerError::ListenerAccept {
message: format!("failed to spawn connection process: {error}"),
})?;
if let Err(error) = self.runtime.register_connection(
pid,
peer_addr,
connection_incarnation,
MountKind::Tcp,
Some(fd_guard),
) {
// Registration failure leaves no host record to reap. Terminate the
// just-spawned process explicitly so neither its stream nor admission
// reservation can escape this failed spawn.
self.scheduler.terminate_process(pid, ExitReason::Error);
return Err(error);
}
// The reservation is now owned by the registered record: `remove` (the
// single record-removal path — finish/mark_crashed/reap all funnel
// through it) releases the admission when the record goes away.
reservation.convert();
Ok(ConnectionHandle {
pid,
peer_addr,
connection_incarnation,
supervisor: Arc::clone(self),
})
}
/// LP-WS-TRANSPORT R1.3: the sibling-transport spawn body. Mirrors
/// [`Self::spawn_connection`]'s admission → incarnation → spawn → register →
/// convert sequence exactly (same reservation guard, same failure rollback,
/// same single record-removal ownership), differing only in that the caller
/// supplies the native handler factory and the host-held fd guard instead of
/// a raw `TcpStream`. Purely additive; the TCP path never calls this.
fn spawn_transport_connection(
self: &Arc<Self>,
peer_addr: Option<SocketAddr>,
fd_guard: Option<TcpStream>,
mount: MountKind,
build_factory: &dyn Fn(
Arc<ConnectionRuntime>,
Option<ConnectionIncarnation>,
) -> NativeHandlerFactory,
) -> Result<ConnectionHandle, ServerError> {
self.runtime.try_reserve_admission()?;
let reservation = AdmissionReservation {
runtime: &self.runtime,
armed: true,
};
let connection_incarnation = self.allocate_connection_incarnation()?;
let factory = build_factory(Arc::clone(&self.runtime), connection_incarnation);
let pid =
self.scheduler
.spawn_native(factory)
.map_err(|error| ServerError::ListenerAccept {
message: format!("failed to spawn connection process: {error}"),
})?;
if let Err(error) = self.runtime.register_connection(
pid,
peer_addr,
connection_incarnation,
mount,
fd_guard,
) {
self.scheduler.terminate_process(pid, ExitReason::Error);
return Err(error);
}
reservation.convert();
Ok(ConnectionHandle {
pid,
peer_addr,
connection_incarnation,
supervisor: Arc::clone(self),
})
}
fn allocate_connection_incarnation(
&self,
) -> Result<Option<ConnectionIncarnation>, ServerError> {
let Some(authority) = self.incarnations.as_ref() else {
return Ok(None);
};
// Production-era uniqueness invariant: every published incarnation is
// unique against ALL durable references — binding epochs committed
// into conversation logs included — by allocator-log monotonicity
// alone, not by the completeness of the reference set below.
//
// 1. Startup replays the durable allocator stream and STRICTLY
// increments the server incarnation, fsyncing the Startup event
// before any listener becomes ready
// (`IncarnationStream::startup`); a server value is never wrapped
// or reused, so no two process lifetimes share one.
// 2. Within a lifetime, allocations are serialized under this
// authority's mutex, candidates start strictly above the durable
// `last_examined_connection_ordinal`
// (`allocate_connection_incarnation`), and every allocation's
// event is appended and flushed BEFORE its pair is published
// (`StartedIncarnationStream::allocate`), so ordinals never
// repeat within a lifetime and replay restores a head at or
// above every published ordinal.
// 3. A durable reference can only name a pair this allocator
// previously PUBLISHED (binding epochs are committed only after
// their connection was admitted), and the same store's flush
// barrier orders the allocator event before any conversation-log
// entry that references it.
//
// The live-connection reference set below is therefore defense in
// depth — a bounded collision skip against a rolled-back or divergent
// allocator stream — never the uniqueness foundation, and never a raw
// caller-supplied matrix.
let references = self.runtime.complete_active_incarnation_references()?;
authority.allocate(&references).map(Some)
}
fn broadcast_control(&self, control: &ConnectionControl) {
for connection in self.runtime.active_connections() {
if !self.enqueue_control(connection.pid, control.clone()) {
// Observation, not diagnosis: the routine cause is a process
// that is no longer live, but a refused control queue reaches
// here too and has already warned with its own error.
tracing::debug!(
connection_pid = connection.pid,
peer_addr = ?connection.peer_addr,
?control,
"connection control message was not published to the process"
);
}
}
}
/// Queues `control` for `pid` and wakes the process. Returns whether the
/// control was PUBLISHED (left in the queue with a successful wake, or
/// already consumed by a drain) — `false` guarantees no consumer ever saw
/// it.
///
/// S8: a failed wake does NOT prove the queued control was never consumed.
/// The insert releases the queue lock before the wake attempt, and a
/// process already executing a control drain (each control atom drains ALL
/// queued controls for the pid) can pop the just-inserted entry in that
/// window, then exit before the wake check. Publication is therefore
/// disambiguated BY OBSERVATION on the failed-wake path: `remove_control`
/// finding and removing the entry proves no consumer saw it (truly
/// unpublished — `false`); finding nothing proves a drain consumed it
/// (`pop_control` is the only other remover of queue entries, and the
/// removal key embeds the push's runtime-unique correlation id, so it can
/// never match a different entry) — the control was published and the
/// caller's slot lifecycle carries the delivery truth (`true`).
fn enqueue_control(&self, pid: u64, control: ConnectionControl) -> bool {
self.runtime.publish_control(&self.scheduler, pid, control)
}
}
impl ConnectionRuntime {
/// Queues `control` for connection `pid` and wakes it on `scheduler`;
/// `true` means the control was published (queued and the wake landed,
/// or a drain consumed it first). The one publication path for a control,
/// shared by the supervisor's pushes and a routed request's (SRV-027 R2).
pub(super) fn publish_control(
&self,
scheduler: &Scheduler,
pid: u64,
control: ConnectionControl,
) -> bool {
// Keep a key for the failure-path removal before the control is moved into
// the queue, so a non-`Copy` (push) control can still be located and pulled
// back out if the scheduler wakeup fails.
let removal_key = control.clone();
if let Err(error) = self.push_control(pid, control) {
// The cause is only knowable HERE. Callers see a bare `false` and
// used to render every one of them as "process is not live", which
// is a lie about a live process whose control queue refused the
// entry — and it discarded the one error that said what happened.
tracing::warn!(
connection_pid = pid,
%error,
"connection control queue refused the entry; the control was never queued"
);
return false;
}
// Deterministic test seam in the insert->wake window (S8 staging).
#[cfg(test)]
self.run_pre_wake_barrier();
if scheduler.enqueue_atom_message(pid, self.control_atom()) {
true
} else {
// Failed wake: the entry's fate is the publication verdict. Removed
// here => nobody consumed it => unpublished. Already gone => a
// drain consumed it before the wake check => published. (A poisoned
// queue lock reads as not-removed => published — the safe
// direction: the slot lifecycle then reports the truthful outcome,
// whereas claiming "unpublished" could be a lie.)
!self.remove_control(pid, &removal_key)
}
}
/// SRV-027 R2: pushes a routed request's `payload` to the worker
/// connection `pid` on `subject`, the slot carrying the requester's
/// `wake`, and hands back the awaiter the requester's slice reads
/// non-blocking ([`PushReplyAwaiter::try_receive`]). The same
/// INSERT -> CONFIRM -> PUBLISH order and publication invariant as the
/// supervisor's pushes: an `Err` means no `Push` was published. The slot
/// carries no deadline of its own; the requester's pending-reply deadline
/// governs, and its expiry cancels the slot by correlation id.
///
/// # Errors
/// The worker's `max_pending_pushes_per_connection` cap, a worker whose
/// record closed during registration, a scheduler that is gone, or a
/// control the queue refused: each by name, with nothing published.
pub(super) fn route_push(
&self,
pid: u64,
subject: &str,
payload: Vec<u8>,
wake: Option<super::wake::ReadyWaker>,
) -> Result<PushReplyAwaiter, ServerError> {
let correlation_id = self.next_push_correlation_id();
let receiver =
self.register_push(pid, correlation_id, None, Some(subject.to_owned()), wake)?;
if !self.confirm_push_registration(pid, correlation_id) {
return Err(ServerError::ListenerAccept {
message: format!(
"cannot route to connection process {pid}: the connection closed during push registration"
),
});
}
let Some(scheduler) = self.scheduler.upgrade() else {
self.cancel_push(correlation_id);
return Err(ServerError::ListenerAccept {
message: format!(
"cannot route to connection process {pid}: the connection scheduler is gone"
),
});
};
let control = ConnectionControl::Push {
correlation_id,
payload,
};
if self.publish_control(&scheduler, pid, control) {
Ok(PushReplyAwaiter {
correlation_id,
receiver,
deadline: None,
runtime: Weak::new(),
})
} else {
self.cancel_push(correlation_id);
Err(ServerError::ListenerAccept {
message: format!(
"cannot route to connection process {pid}: the control was not published"
),
})
}
}
/// SRV-027 R1: the connection serving `subject`, by one keyed lookup in
/// the directory under the registry lock; `None` when no worker serves it.
pub(super) fn serving(&self, subject: &str) -> Option<u64> {
self.records
.lock()
.ok()
.and_then(|records| records.directory.serving(subject))
}
/// How many directory lookups `serving` has made (R4 count pins).
pub(super) fn directory_lookups(&self) -> u64 {
self.records
.lock()
.map_or(0, |records| records.directory.lookups())
}
}
/// RAII guard for one §5 `max_connections` admission reservation.
///
/// Acquired (via [`ConnectionRuntime::try_reserve_admission`]) before any process
/// construction in `spawn_connection`; every early-return failure path releases
/// it through `Drop`, and a successful `register` converts it into the
/// connection record (whose removal releases the admission instead). RAII means
/// no failure path — present or future — can leak a reservation.
struct AdmissionReservation<'a> {
runtime: &'a ConnectionRuntime,
armed: bool,
}
impl AdmissionReservation<'_> {
/// Converts the reservation into record ownership: `Drop` no longer releases
/// it, because the registered record's removal will.
fn convert(mut self) {
self.armed = false;
}
}
impl Drop for AdmissionReservation<'_> {
fn drop(&mut self) {
if self.armed {
self.runtime.release_admission();
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum ConnectionControl {
NotifyShutdown,
ForceClose,
/// Server-initiated push of an opaque payload, correlated by `correlation_id`,
/// to be written out as a [`Frame::Push`] by the receiving connection process.
Push {
correlation_id: u64,
payload: Vec<u8>,
},
/// ACCESS-005 R4/R6: this connection's rights changed under a grant
/// revocation. The connection sweeps its own `ConnectionGrants`: it
/// retires withdrawn rights' work and, when its admitting right is lost,
/// closes with the reason. The denied state is already in force before
/// this control is read, so a refused publication only delays the sweep
/// to the connection's own wake.
Revocation,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ActiveConnection {
pid: u64,
peer_addr: Option<SocketAddr>,
}
#[cfg(test)]
#[derive(Debug, Clone)]
struct PreWaitBarrier {
armed: Arc<Barrier>,
release: Arc<Barrier>,
}
/// Pid-specific, one-use deterministic gate on the reclamation delivery path
/// (oracle 26). The exit-event reactor stages it only for the targeted pid, so
/// unrelated exits still reclaim immediately; for the target it rendezvouses
/// `reached` (proving the pid is dead but its record still tracked — the S8
/// reclamation window), then `release` (the harness lets the reclaim proceed),
/// then `done` (the `remove()` funnel completed). It changes no production
/// semantics — the whole type and its call sites are `#[cfg(test)]`.
#[cfg(test)]
#[derive(Debug, Clone)]
struct ReclaimBarrier {
pid: u64,
reached: Arc<Barrier>,
release: Arc<Barrier>,
done: Arc<Barrier>,
}
#[derive(Debug)]
struct ConnectionServiceInstallation {
services: Arc<dyn ConnectionServices>,
participant_service: Option<InstalledParticipantService>,
}
impl ConnectionServiceInstallation {
/// Captures the service adapter's capability posture exactly once, before
/// participant incarnation startup or connection process construction.
fn capture(services: Arc<dyn ConnectionServices>) -> Self {
let participant_service = services.participant_service();
Self {
services,
participant_service,
}
}
}
#[derive(Debug)]
struct ConnectionRuntimeInstallation {
services: ConnectionServiceInstallation,
incarnations: Option<Arc<ConnectionIncarnationAuthority>>,
fatal_shutdown: Option<ShutdownHandle>,
}
#[cfg(test)]
#[derive(Debug)]
enum CloseEventFdProbe {
Off,
Armed,
Observed(Result<bool, std::io::Error>),
}
#[derive(Debug)]
pub(super) struct ConnectionRuntime {
signals: OnceLock<ServerSignals>,
/// The Lys pass admitter and the Lys network id liminal's subjects are
/// placed under, installed once before the first connection (ACCESS-001
/// R2). Absent, a Lys pass record is refused at `Connect` by name.
lys_admitter: OnceLock<(Arc<dyn crate::auth_lys::session::LysAdmitter>, String)>,
/// The ACCESS-003 service bindings, installed once from
/// `[auth.lys.services]`; a service request without them is refused by
/// name.
service_bindings: OnceLock<Arc<crate::services::production::ServiceBindings>>,
/// The services registry and lifecycle (SRV-028), installed once after
/// the listener binds; absent, every lifecycle request is refused by
/// name and no service process credential is admitted.
lifecycle: OnceLock<Arc<crate::services::lifecycle::Lifecycle>>,
/// The channel membership gate, installed once with the admitter
/// (ACCESS-006 R1). Absent, no channel is membership-protected.
membership_gate: OnceLock<Arc<crate::auth_membership::MembershipGate>>,
/// This liminal as a machine Lys knows, installed once with the admitter
/// (ACCESS-002 R1). Absent, no link opens here, by name.
link_host: OnceLock<Arc<crate::link::LinkHost>>,
/// The grant-revocation policy, installed once before the first
/// connection (ACCESS-005). Present, every `Connect` must carry a bound
/// pass the authority admits and negotiate the reason-bearing close;
/// absent, admission is exactly as before.
revocation: OnceLock<Arc<crate::auth_revocation::RevocationAuthority>>,
#[cfg(test)]
close_event_fd_probe: Mutex<CloseEventFdProbe>,
services: Arc<dyn ConnectionServices>,
/// Live retry index woken by candidate-lane drains; durable Open rows remain
/// the recovery authority.
parked_connection_fates: Mutex<ParkedConnectionFates>,
/// Complete participant handler/store bundle captured at supervisor startup.
/// `Some` is paired with an incarnation authority on `SupervisorInner`.
participant_service: Option<InstalledParticipantService>,
/// Same started authority used for allocation, shared for terminal Open/Complete.
incarnations: Option<Arc<ConnectionIncarnationAuthority>>,
/// Existing runtime shutdown activation notified by the first post-Open fatal.
/// Test-only/runtime-less constructors intentionally carry `None`.
fatal_shutdown: Option<ShutdownHandle>,
records: Mutex<Registry>,
controls: Mutex<Vec<QueuedConnectionControl>>,
control_atom: Atom,
/// R6 single `READY` wake atom for this connection scheduler. Fired by every
/// wake source's notifier (R3/R1(vi)); coalescing and duplicates are harmless.
ready_atom: Atom,
/// Weak handle to the connection scheduler, used to build [`ReadyWaker`]s a
/// notifier fires from another actor's slice. Weak so it never keeps the
/// scheduler alive (the scheduler owns the processes that own this runtime).
scheduler: Weak<Scheduler>,
/// W4 leg 3 (§4.3) TOLD drain-completion primitive. Reuses the
/// [`ShutdownHandle`] `Condvar` shape (`shutdown.rs` reuse candidate (c)): a
/// monotonic connection-removal generation guarded by [`Self::drain_removed`]'s
/// mutex, bumped once whenever [`Self::remove`] actually drops a record — the
/// single removal funnel every exit route (in-slice `mark_crashed`/`finish`,
/// the reclaim reactor, and the reconciliation scan) reaches. The
/// shutdown-sequence drain/settle waiter parks on the `Condvar` and wakes only
/// on a delivered exit (a generation bump + `notify_all`) or the one admitted
/// deadline it passes to `wait_timeout`. No periodic reap or count scan.
drain_generation: Mutex<u64>,
/// Woken on every connection-record removal; the drain/settle waiter parks
/// here. Paired with [`Self::drain_generation`] under the same mutex so an
/// exit delivered between the waiter's arm-before-observe snapshot and its
/// park cannot be lost (oracle 18).
drain_removed: Condvar,
/// FIX A-ii shutdown flush barrier: a delivery-quiescence generation of the
/// exact TOLD `drain_generation` shape. Bumped whenever a connection parks
/// with every accepted publish already fanned out to its socket — but only
/// while [`Self::settle_armed`] is set (the flush barrier is waiting) — so
/// normal operation pays nothing. Guards [`Self::settle_changed`]'s mutex.
settle_generation: Mutex<u64>,
/// Woken when a connection reaches delivery quiescence during shutdown; the
/// flush barrier parks here, paired with [`Self::settle_generation`] for the
/// same arm-before-observe safety as the drain waiter.
settle_changed: Condvar,
/// Set only while the flush barrier is actively waiting, so a park bumps the
/// settle generation and wakes the barrier ONLY when someone is listening.
settle_armed: AtomicBool,
/// Server `Push` frames this runtime's connections have queued for their
/// sockets, counted once per frame accepted into an outbound buffer. A push
/// that fails, is cancelled or is rolled back is never counted.
pushes_queued: AtomicU64,
/// Observes the real condvar predicate while its generation lock is held.
#[cfg(test)]
settle_wait_observer: Mutex<Option<Sender<()>>>,
/// Test-only count of drain waiter wakes that observed a real removal
/// (generation advanced across the park). A quiet drain records zero — it
/// wakes only for the single deadline (oracle 12).
#[cfg(test)]
drain_exit_wakes: AtomicU64,
/// Test-only count of drain waiter deadline expirations. A quiet drain that
/// times out records exactly one — one arming, one delivery, no helper tick
/// (oracles 12, 16).
#[cfg(test)]
drain_deadline_hits: AtomicU64,
/// Test-only one-use gate in the drain waiter's observe->park window, so a
/// harness can deliver an exit strictly after the completion observation and
/// before the park to pin the arm-before-observe barrier (oracles 18, 19).
#[cfg(test)]
drain_park_barrier: Mutex<Option<PreWaitBarrier>>,
/// R7 (§1.2(6)) test-only per-connection slice counter, keyed by pid. Bumped
/// once at the head of every serviced slice. The park-flip's permanent rule-1
/// assertion (a parked connection's counter must not advance without an event)
/// reads this; the instrument lands now with a test proving it counts slices.
#[cfg(test)]
slice_counts: Mutex<HashMap<u64, u64>>,
/// One-use readiness markers for the next serviced slice of a process.
#[cfg(test)]
slice_observers: Mutex<HashMap<u64, Sender<u64>>>,
/// One-use readiness markers emitted only after the real final probe selects
/// `Wait`, immediately before the native process returns to the scheduler.
#[cfg(test)]
park_observers: Mutex<HashMap<u64, Sender<u64>>>,
/// Most recent slice count whose real final probe selected `Wait`.
#[cfg(test)]
park_counts: Mutex<HashMap<u64, u64>>,
/// Where each report of frames written to a connection's transport goes,
/// by pid (R3b F8, ruling 2a).
#[cfg(test)]
frame_observers: Mutex<HashMap<u64, Sender<Vec<liminal::protocol::FrameType>>>>,
/// Explicit capacities consumed in TCP process construction order.
#[cfg(test)]
next_outbound_capacities: Mutex<VecDeque<usize>>,
#[cfg(test)]
participant_holdback_pauses: Mutex<HashMap<u64, Sender<()>>>,
/// Deterministic test gate placed after arm and before the final probe.
#[cfg(test)]
pre_wait_barrier: Mutex<Option<PreWaitBarrier>>,
/// Deterministic test gate in `enqueue_control`'s insert->wake window (S8).
#[cfg(test)]
pre_wake_barrier: Mutex<Option<PreWaitBarrier>>,
/// Pid-specific one-use gate held on the reclamation delivery path so a test
/// can pin the dead-but-tracked S8 window deterministically (oracle 26).
#[cfg(test)]
reclaim_barrier: Mutex<Option<ReclaimBarrier>>,
/// Barrier-staged slices where the final probe found newly arrived work.
#[cfg(test)]
pre_wait_probe_hits: AtomicU64,
/// One-use observers for process-owned streams reaching their actual drop
/// boundary after external scheduler termination.
#[cfg(test)]
process_stream_drop_observers: Mutex<HashMap<RawFd, Sender<()>>>,
/// One-shot reply slots for in-flight server pushes, keyed by correlation id.
/// The supervisor registers a slot in `push_to_connection`; the connection
/// process resolves it when the matching `PushReply` frame arrives. Each slot
/// records the owning connection pid so the close path can drop a connection's
/// outstanding slots and wake their awaiters with a prompt disconnected error.
push_replies: Mutex<HashMap<u64, PendingPush>>,
/// Monotonic source of push correlation ids. Server-allocated, so it never
/// collides with a client-chosen id on this connection.
next_push_id: AtomicU64,
/// §5 `max_connections` admission counter. Incremented atomically (CAS
/// against the limit) BEFORE a connection process is constructed and
/// decremented on every spawn-failure path and on final record removal, so
/// the signed bound holds under concurrent spawns — admission is never
/// derived from the records-map length across an unlocked window.
admissions: AtomicU64,
/// Optional application hook invoked on worker registration and on the close
/// of a connection that had registered, and on the attach and close of a
/// pass-stamped connection. `None` keeps liminal standalone: a
/// `WorkerRegister` is accepted with no callback, a pass attaches silently.
notifier: Option<Arc<dyn ConnectionNotifier>>,
/// Configured connection auth token (the `[auth]` section's token as opaque
/// bytes). `Some` gates the `Connect` handshake — the frame's `auth_token` must
/// match under a constant-time comparison; `None` leaves the server open-access,
/// byte-identical to the pre-auth behaviour.
auth_token: Option<Vec<u8>>,
pass_verifier: Option<PassVerifier>,
/// Operational caps (§5). Enforced with typed refusals at admission:
/// per-connection subscription, conversation, push, and pending-reply counts,
/// plus the shared inbox byte budget. Non-config constructors carry the signed
/// defaults ([`LimitsConfig::default`]).
limits: LimitsConfig,
}
impl ConnectionRuntime {
pub(super) fn pressure(&self, connection: u64, response: &str) {
if let Some(signals) = self.signals.get() {
signals.event(crate::server::self_streams::events::ServerEvent::Pressure {
connection,
response,
});
}
}
fn new(
installation: ConnectionRuntimeInstallation,
control_atom: Atom,
ready_atom: Atom,
scheduler: Weak<Scheduler>,
notifier: Option<Arc<dyn ConnectionNotifier>>,
authentication: (Option<Vec<u8>>, Option<PassVerifier>),
limits: LimitsConfig,
) -> Self {
let (auth_token, pass_verifier) = authentication;
let ConnectionRuntimeInstallation {
services:
ConnectionServiceInstallation {
services,
participant_service,
},
incarnations,
fatal_shutdown,
} = installation;
Self {
services,
participant_service,
incarnations,
fatal_shutdown,
signals: OnceLock::new(),
lys_admitter: OnceLock::new(),
service_bindings: OnceLock::new(),
lifecycle: OnceLock::new(),
membership_gate: OnceLock::new(),
link_host: OnceLock::new(),
revocation: OnceLock::new(),
#[cfg(test)]
close_event_fd_probe: Mutex::new(CloseEventFdProbe::Off),
parked_connection_fates: Mutex::new(ParkedConnectionFates::default()),
records: Mutex::new(Registry::default()),
controls: Mutex::new(Vec::new()),
control_atom,
ready_atom,
scheduler,
drain_generation: Mutex::new(0),
drain_removed: Condvar::new(),
settle_generation: Mutex::new(0),
settle_changed: Condvar::new(),
settle_armed: AtomicBool::new(false),
pushes_queued: AtomicU64::new(0),
#[cfg(test)]
settle_wait_observer: Mutex::new(None),
#[cfg(test)]
drain_exit_wakes: AtomicU64::new(0),
#[cfg(test)]
drain_deadline_hits: AtomicU64::new(0),
#[cfg(test)]
drain_park_barrier: Mutex::new(None),
#[cfg(test)]
slice_counts: Mutex::new(HashMap::new()),
#[cfg(test)]
slice_observers: Mutex::new(HashMap::new()),
#[cfg(test)]
park_observers: Mutex::new(HashMap::new()),
#[cfg(test)]
frame_observers: Mutex::new(HashMap::new()),
#[cfg(test)]
park_counts: Mutex::new(HashMap::new()),
#[cfg(test)]
next_outbound_capacities: Mutex::new(VecDeque::new()),
#[cfg(test)]
participant_holdback_pauses: Mutex::new(HashMap::new()),
#[cfg(test)]
pre_wait_barrier: Mutex::new(None),
#[cfg(test)]
pre_wake_barrier: Mutex::new(None),
#[cfg(test)]
reclaim_barrier: Mutex::new(None),
#[cfg(test)]
pre_wait_probe_hits: AtomicU64::new(0),
#[cfg(test)]
process_stream_drop_observers: Mutex::new(HashMap::new()),
push_replies: Mutex::new(HashMap::new()),
next_push_id: AtomicU64::new(1),
admissions: AtomicU64::new(0),
notifier,
auth_token,
pass_verifier,
limits,
}
}
/// Atomically reserves one §5 `max_connections` admission slot: a CAS loop
/// against the configured limit, so N concurrent callers racing for the last
/// slot admit EXACTLY one — the bound cannot be transiently exceeded.
///
/// # Errors
/// Returns [`ServerError::ConnectionLimitReached`] when every slot is taken.
fn try_reserve_admission(&self) -> Result<(), ServerError> {
self.ensure_participant_service_live()?;
let limit = self.limits.max_connections as u64;
let mut current = self.admissions.load(Ordering::Acquire);
loop {
if current >= limit {
return Err(ServerError::ConnectionLimitReached {
limit: self.limits.max_connections,
});
}
match self.admissions.compare_exchange_weak(
current,
current + 1,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => return Ok(()),
Err(observed) => current = observed,
}
}
}
/// Releases one admission slot. Called by the spawn failure paths (via the
/// [`AdmissionReservation`] guard) and by [`Self::remove`] when a registered
/// record is removed — exactly one release per reservation. Saturating so a
/// spurious release can never wrap the counter.
fn release_admission(&self) {
let mut current = self.admissions.load(Ordering::Acquire);
loop {
let next = current.saturating_sub(1);
match self.admissions.compare_exchange_weak(
current,
next,
Ordering::AcqRel,
Ordering::Acquire,
) {
Ok(_) => return,
Err(observed) => current = observed,
}
}
}
/// The operational caps (§5) this runtime enforces.
pub(super) const fn limits(&self) -> &LimitsConfig {
&self.limits
}
/// The connection's single R6 `READY` wake atom.
pub(super) const fn ready_atom(&self) -> Atom {
self.ready_atom
}
/// Builds a [`ReadyWaker`] targeting `pid` on the connection scheduler, if the
/// scheduler is still live. `None` when the scheduler is gone (teardown) or in
/// scheduler-free unit tests — a notifier with no waker simply never wakes,
/// which under the busy loop is redundant anyway (the every-slice pump still
/// services the source). This is the seam every wake source installs its
/// notifier through (R3/R1(vi)).
pub(super) fn ready_waker(&self, pid: u64) -> Option<super::wake::ReadyWaker> {
let scheduler = self.scheduler.upgrade()?;
let ready_pending = self
.records
.lock()
.ok()?
.connections
.get(&pid)
.map(|record| Arc::clone(&record.ready_pending))?;
Some(super::wake::ReadyWaker::new(
&scheduler,
pid,
self.ready_atom,
ready_pending,
))
}
/// Acknowledges READY edges whose mailbox atoms were drained before this slice.
pub(super) fn acknowledge_ready(&self, pid: u64) {
if let Ok(records) = self.records.lock()
&& let Some(record) = records.connections.get(&pid)
{
record.ready_pending.store(false, Ordering::Release);
}
}
/// Reports a READY edge queued while the current process snapshot is executing.
pub(super) fn ready_pending(&self, pid: u64) -> bool {
self.records
.lock()
.ok()
.and_then(|records| {
records
.connections
.get(&pid)
.map(|record| record.ready_pending.load(Ordering::Acquire))
})
.unwrap_or(false)
}
/// FIX A-ii: marks `pid` as executing a slice — not parked, so not yet
/// delivery-quiescent. Reuses the registry lock the slice already takes for
/// `is_registered`; it never touches the barrier condvar.
pub(super) fn mark_running(&self, pid: u64) {
if let Ok(records) = self.records.lock()
&& let Some(record) = records.connections.get(&pid)
{
record.parked.store(false, Ordering::Release);
}
}
/// FIX A-ii: marks `pid` as parked with every accepted publish already fanned
/// out to its socket, and — only while the shutdown flush barrier is armed —
/// bumps the settle generation and wakes it. The bump/notify is skipped
/// entirely in normal operation, so a park off the shutdown path is just one
/// flag store.
pub(super) fn mark_parked(&self, pid: u64) {
if let Ok(records) = self.records.lock()
&& let Some(record) = records.connections.get(&pid)
{
record.parked.store(true, Ordering::Release);
}
if self.settle_armed.load(Ordering::Acquire) {
self.signal_settle_changed();
}
}
/// Bumps the delivery-quiescence generation under its mutex, then wakes the
/// flush barrier — the same lock-then-notify discipline as
/// [`Self::signal_connection_removed`], so a park published before the notify
/// can never be missed by a waiter holding the mutex across its re-check.
fn signal_settle_changed(&self) {
{
let mut generation = recover_lock(&self.settle_generation);
*generation = generation.wrapping_add(1);
}
self.settle_changed.notify_all();
}
/// Reads the current delivery-quiescence generation under its mutex.
fn settle_generation_snapshot(&self) -> u64 {
*recover_lock(&self.settle_generation)
}
/// True when every tracked connection is parked with no pending READY edge —
/// i.e. every accepted publish has been pumped to its subscriber's outbound
/// and no fan-out wake is still in flight. An empty registry is trivially
/// quiescent.
fn all_connections_delivery_quiesced(&self) -> bool {
let Ok(records) = self.records.lock() else {
return false;
};
records.connections.values().all(|record| {
record.parked.load(Ordering::Acquire) && !record.ready_pending.load(Ordering::Acquire)
})
}
/// FIX A-ii: wakes every tracked connection once so it drains its socket and
/// pumps its subscriptions. This is what makes the flush barrier robust to the
/// readiness gap: a publisher whose fire-and-forget publish bytes have arrived
/// but whose readiness wake has not yet rescheduled it still looks "parked",
/// so without this it could be sampled as quiescent before it admits and fans
/// out those publishes. Firing sets each connection's `ready_pending` edge, so
/// the quiescence check below cannot pass until every woken connection has run
/// its slice (reading and admitting any buffered publish, whose admission then
/// fires its subscribers in turn) and re-parked.
fn wake_all_connections_for_flush(&self) {
let pids: Vec<u64> = self
.records
.lock()
.map(|records| records.connections.keys().copied().collect())
.unwrap_or_default();
for pid in pids {
if let Some(waker) = self.ready_waker(pid) {
waker.fire();
}
}
}
/// FIX A-ii: parks until every tracked connection has fanned out its accepted
/// publishes (delivery quiescence) or `deadline` elapses, returning `true` on
/// quiescence and `false` when the single admitted deadline won. The TOLD
/// shape mirrors [`Self::wait_for_active_connections_drained`]: arm the
/// barrier, then snapshot-before-observe so a park delivered between the
/// observation and the wait bumps a generation the wait detects. It samples
/// nothing on a timer — it wakes only on a delivered park (generation bump) or
/// the one deadline.
pub(super) fn wait_for_delivery_quiesced(&self, deadline: Instant) -> bool {
self.settle_armed.store(true, Ordering::Release);
// Force every connection to run once so a publisher whose buffered publish
// bytes have not yet triggered a readiness wake still drains and admits
// them (and fires its subscribers) before the quiescence check can pass.
self.wake_all_connections_for_flush();
let quiesced = loop {
let snapshot = self.settle_generation_snapshot();
if self.all_connections_delivery_quiesced() {
break true;
}
let Some(remaining) = deadline.checked_duration_since(Instant::now()) else {
break false;
};
let (generation, outcome) = self
.settle_changed
.wait_timeout_while(
recover_lock(&self.settle_generation),
remaining,
|current| {
#[cfg(test)]
{
let observer = recover_lock(&self.settle_wait_observer).take();
if let Some(observer) = observer {
let _sent = observer.send(());
}
}
*current == snapshot
},
)
.unwrap_or_else(PoisonError::into_inner);
drop(generation);
// A predicate that became true without its completion signal must
// not turn a missed wake into success when the deadline wakes us.
if outcome.timed_out() {
break false;
}
};
self.settle_armed.store(false, Ordering::Release);
quiesced
}
/// R7: records one serviced slice for `pid`. Bumped at the head of every
/// slice; the park-flip's quiescence assertion reads [`Self::slice_count`].
#[cfg(test)]
pub(super) fn record_slice(&self, pid: u64) {
let count = if let Ok(mut counts) = self.slice_counts.lock() {
let count = counts.entry(pid).or_insert(0);
*count += 1;
*count
} else {
return;
};
if let Ok(mut observers) = self.slice_observers.lock()
&& let Some(observer) = observers.remove(&pid)
{
let _ = observer.send(count);
}
}
#[cfg(test)]
fn observe_next_slice(&self, pid: u64) -> Receiver<u64> {
let (sender, receiver) = channel();
if let Ok(mut observers) = self.slice_observers.lock() {
observers.insert(pid, sender);
}
receiver
}
#[cfg(test)]
fn observe_next_park(&self, pid: u64) -> Receiver<u64> {
let (sender, receiver) = channel();
if let Ok(mut observers) = self.park_observers.lock() {
observers.insert(pid, sender);
}
receiver
}
#[cfg(test)]
fn observe_settled_park(&self, pid: u64) -> Receiver<u64> {
let (sender, receiver) = channel();
let Ok(counts) = self.slice_counts.lock() else {
return receiver;
};
let current = counts.get(&pid).copied().unwrap_or(0);
let Ok(parks) = self.park_counts.lock() else {
return receiver;
};
if current > 0 && parks.get(&pid).copied() == Some(current) {
let _ = sender.send(current);
} else if let Ok(mut observers) = self.park_observers.lock() {
observers.insert(pid, sender);
}
drop(parks);
drop(counts);
receiver
}
/// Reports the kinds of the frames `pid` has written to its transport,
/// once its outbound buffer has drained (R3b F8, ruling 2a).
#[cfg(test)]
pub(super) fn record_frames_written(&self, pid: u64, kinds: Vec<liminal::protocol::FrameType>) {
if kinds.is_empty() {
return;
}
let observer = self
.frame_observers
.lock()
.ok()
.and_then(|observers| observers.get(&pid).cloned());
if let Some(observer) = observer {
let _ = observer.send(kinds);
}
}
/// Every later report of the frames `pid` writes to its transport.
#[cfg(test)]
fn observe_frames_written(&self, pid: u64) -> Receiver<Vec<liminal::protocol::FrameType>> {
let (sender, receiver) = channel();
if let Ok(mut observers) = self.frame_observers.lock() {
observers.insert(pid, sender);
}
receiver
}
#[cfg(test)]
pub(super) fn record_park(&self, pid: u64) {
let count = self.slice_count(pid);
if let Ok(mut parks) = self.park_counts.lock() {
parks.insert(pid, count);
}
if let Ok(mut observers) = self.park_observers.lock()
&& let Some(observer) = observers.remove(&pid)
{
let _ = observer.send(count);
}
}
#[cfg(test)]
fn queue_next_outbound_capacity(&self, capacity: usize) {
if let Ok(mut capacities) = self.next_outbound_capacities.lock() {
capacities.push_back(capacity);
}
}
#[cfg(test)]
pub(super) fn take_next_outbound_capacity(&self) -> Option<usize> {
self.next_outbound_capacities
.lock()
.ok()
.and_then(|mut capacities| capacities.pop_front())
}
#[cfg(test)]
fn install_participant_holdback_pause(&self, pid: u64) -> Receiver<()> {
let (sender, receiver) = channel();
if let Ok(mut pauses) = self.participant_holdback_pauses.lock() {
pauses.insert(pid, sender);
}
receiver
}
#[cfg(test)]
pub(super) fn pause_participant_holdback(&self, pid: u64) -> bool {
self.participant_holdback_pauses
.lock()
.ok()
.and_then(|mut pauses| pauses.remove(&pid))
.is_some_and(|sender| {
let _ = sender.send(());
true
})
}
/// R7: slices serviced by connection `pid` since spawn (test instrument).
#[cfg(test)]
pub(super) fn slice_count(&self, pid: u64) -> u64 {
self.slice_counts
.lock()
.map_or(0, |counts| counts.get(&pid).copied().unwrap_or(0))
}
#[cfg(test)]
fn install_pre_wait_barrier(&self) -> (Arc<Barrier>, Arc<Barrier>) {
let armed = Arc::new(Barrier::new(2));
let release = Arc::new(Barrier::new(2));
if let Ok(mut slot) = self.pre_wait_barrier.lock() {
*slot = Some(PreWaitBarrier {
armed: Arc::clone(&armed),
release: Arc::clone(&release),
});
}
(armed, release)
}
/// Installs the pid-specific reclamation gate (oracle 26) and returns its
/// `(reached, release, done)` endpoints. The harness rendezvouses `reached`
/// to pin the dead-but-tracked window, `release` to let the reclaim proceed,
/// and `done` to observe the `remove()` funnel completing.
#[cfg(test)]
pub(super) fn install_reclaim_barrier(
&self,
pid: u64,
) -> (Arc<Barrier>, Arc<Barrier>, Arc<Barrier>) {
let reached = Arc::new(Barrier::new(2));
let release = Arc::new(Barrier::new(2));
let done = Arc::new(Barrier::new(2));
if let Ok(mut slot) = self.reclaim_barrier.lock() {
*slot = Some(ReclaimBarrier {
pid,
reached: Arc::clone(&reached),
release: Arc::clone(&release),
done: Arc::clone(&done),
});
}
(reached, release, done)
}
/// Takes the installed reclamation gate iff it targets `pid` (one-use). Any
/// other pid's delivery is ungated, so unrelated exits reclaim immediately.
#[cfg(test)]
fn stage_reclaim_barrier(&self, pid: u64) -> Option<ReclaimBarrier> {
let mut slot = self.reclaim_barrier.lock().ok()?;
if slot.as_ref().is_some_and(|barrier| barrier.pid == pid) {
slot.take()
} else {
None
}
}
/// Installs the one-use drain-park gate (oracles 18, 19) and returns its
/// `(armed, release)` endpoints. Staged in the drain waiter's observe->park
/// window so a harness can deliver an exit strictly between the completion
/// observation and the park. Entirely `#[cfg(test)]`; changes no production
/// wait semantics.
#[cfg(test)]
pub(super) fn install_drain_park_barrier(&self) -> (Arc<Barrier>, Arc<Barrier>) {
let armed = Arc::new(Barrier::new(2));
let release = Arc::new(Barrier::new(2));
if let Ok(mut slot) = self.drain_park_barrier.lock() {
*slot = Some(PreWaitBarrier {
armed: Arc::clone(&armed),
release: Arc::clone(&release),
});
}
(armed, release)
}
/// Runs the one-use drain-park gate, if installed. One-use so only the staged
/// park rendezvouses; every later park in the same waiter runs ungated.
#[cfg(test)]
fn run_drain_park_barrier(&self) {
let barrier = self
.drain_park_barrier
.lock()
.ok()
.and_then(|mut slot| slot.take());
let Some(barrier) = barrier else {
return;
};
barrier.armed.wait();
barrier.release.wait();
}
/// Test-only count of drain waiter wakes that observed a real removal.
#[cfg(test)]
pub(super) fn drain_exit_wakes(&self) -> u64 {
self.drain_exit_wakes.load(Ordering::SeqCst)
}
/// Test-only count of drain waiter deadline expirations.
#[cfg(test)]
pub(super) fn drain_deadline_hits(&self) -> u64 {
self.drain_deadline_hits.load(Ordering::SeqCst)
}
/// Runs a one-use deterministic test gate after arm. Returns whether the gate
/// was installed so only that staged probe contributes to observability.
#[cfg(test)]
pub(super) fn run_pre_wait_barrier(&self) -> bool {
let barrier = self
.pre_wait_barrier
.lock()
.ok()
.and_then(|mut slot| slot.take());
let Some(barrier) = barrier else {
return false;
};
barrier.armed.wait();
barrier.release.wait();
true
}
/// Installs a one-use barrier in `enqueue_control`'s insert->wake window
/// (S8 staging: lets a test act as the control-drain consumer between the
/// queue insertion and the wake attempt) and returns its test endpoints.
#[cfg(test)]
pub(super) fn install_pre_wake_barrier(&self) -> (Arc<Barrier>, Arc<Barrier>) {
let armed = Arc::new(Barrier::new(2));
let release = Arc::new(Barrier::new(2));
if let Ok(mut slot) = self.pre_wake_barrier.lock() {
*slot = Some(PreWaitBarrier {
armed: Arc::clone(&armed),
release: Arc::clone(&release),
});
}
(armed, release)
}
/// Runs the one-use insert->wake test gate, if installed.
#[cfg(test)]
pub(super) fn run_pre_wake_barrier(&self) {
let barrier = self
.pre_wake_barrier
.lock()
.ok()
.and_then(|mut slot| slot.take());
if let Some(barrier) = barrier {
barrier.armed.wait();
barrier.release.wait();
}
}
#[cfg(test)]
pub(super) fn record_pre_wait_probe_hit(&self) {
self.pre_wait_probe_hits.fetch_add(1, Ordering::AcqRel);
}
#[cfg(test)]
fn pre_wait_probe_hits(&self) -> u64 {
self.pre_wait_probe_hits.load(Ordering::Acquire)
}
#[cfg(test)]
fn observe_process_stream_drop(&self, fd: RawFd) -> Receiver<()> {
let (sender, receiver) = channel();
if let Ok(mut observers) = self.process_stream_drop_observers.lock() {
observers.insert(fd, sender);
}
receiver
}
/// Publishes the process-owned stream's real drop boundary to a waiting test.
#[cfg(test)]
pub(super) fn record_process_stream_drop(&self, fd: RawFd) {
let observer = self
.process_stream_drop_observers
.lock()
.ok()
.and_then(|mut observers| observers.remove(&fd));
if let Some(observer) = observer {
let _ = observer.send(());
}
}
/// Builds a runtime wrapping `services` for unit tests that exercise
/// `apply_frame` without a live scheduler. Uses a fresh interned control atom
/// and no notifier.
#[cfg(test)]
pub(super) fn for_tests(services: Arc<dyn ConnectionServices>) -> Self {
let atoms = AtomTable::with_common_atoms();
let control_atom = atoms.intern(CONNECTION_SHUTDOWN_CONTROL_ATOM);
let ready_atom = atoms.intern(CONNECTION_READY_ATOM);
Self::new(
ConnectionRuntimeInstallation {
services: ConnectionServiceInstallation::capture(services),
incarnations: None,
fatal_shutdown: None,
},
control_atom,
ready_atom,
Weak::new(),
None,
(None, None),
LimitsConfig::default(),
)
}
/// Builds a runtime wrapping `services` with explicit `limits` for unit tests
/// that exercise the §5 admission caps without a live scheduler.
#[cfg(test)]
pub(super) fn for_tests_with_limits(
services: Arc<dyn ConnectionServices>,
limits: LimitsConfig,
) -> Self {
let atoms = AtomTable::with_common_atoms();
let control_atom = atoms.intern(CONNECTION_SHUTDOWN_CONTROL_ATOM);
let ready_atom = atoms.intern(CONNECTION_READY_ATOM);
Self::new(
ConnectionRuntimeInstallation {
services: ConnectionServiceInstallation::capture(services),
incarnations: None,
fatal_shutdown: None,
},
control_atom,
ready_atom,
Weak::new(),
None,
(None, None),
limits,
)
}
/// Builds a runtime wrapping `services` with a configured auth `token` for unit
/// tests that exercise the `Connect` handshake enforcement without a live
/// scheduler. Uses a fresh interned control atom and no notifier.
#[cfg(test)]
pub(super) fn for_tests_with_auth_token(
services: Arc<dyn ConnectionServices>,
token: Vec<u8>,
) -> Self {
let atoms = AtomTable::with_common_atoms();
let control_atom = atoms.intern(CONNECTION_SHUTDOWN_CONTROL_ATOM);
let ready_atom = atoms.intern(CONNECTION_READY_ATOM);
Self::new(
ConnectionRuntimeInstallation {
services: ConnectionServiceInstallation::capture(services),
incarnations: None,
fatal_shutdown: None,
},
control_atom,
ready_atom,
Weak::new(),
None,
(Some(token), None),
LimitsConfig::default(),
)
}
/// Builds a runtime wrapping `services` with a `notifier` for unit tests that
/// exercise `apply_frame` and the close path without a live scheduler.
#[cfg(test)]
pub(super) fn for_tests_with_notifier(
services: Arc<dyn ConnectionServices>,
notifier: Arc<dyn ConnectionNotifier>,
) -> Self {
let atoms = AtomTable::with_common_atoms();
let control_atom = atoms.intern(CONNECTION_SHUTDOWN_CONTROL_ATOM);
let ready_atom = atoms.intern(CONNECTION_READY_ATOM);
Self::new(
ConnectionRuntimeInstallation {
services: ConnectionServiceInstallation::capture(services),
incarnations: None,
fatal_shutdown: None,
},
control_atom,
ready_atom,
Weak::new(),
Some(notifier),
(None, None),
LimitsConfig::default(),
)
}
/// Builds a runtime wrapping `services` that verifies registry passes
/// with `verifier`, accepts the bearer `token` when given, and reports to
/// `notifier`, for unit tests of a worker
/// bound to the holder its `Connect` verified (ACCESS-004).
#[cfg(test)]
pub(super) fn for_tests_with_pass(
services: Arc<dyn ConnectionServices>,
notifier: Arc<dyn ConnectionNotifier>,
token: Option<Vec<u8>>,
verifier: PassVerifier,
) -> Self {
let atoms = AtomTable::with_common_atoms();
let control_atom = atoms.intern(CONNECTION_SHUTDOWN_CONTROL_ATOM);
let ready_atom = atoms.intern(CONNECTION_READY_ATOM);
Self::new(
ConnectionRuntimeInstallation {
services: ConnectionServiceInstallation::capture(services),
incarnations: None,
fatal_shutdown: None,
},
control_atom,
ready_atom,
Weak::new(),
Some(notifier),
(token, Some(verifier)),
LimitsConfig::default(),
)
}
pub(super) fn services(&self) -> &dyn ConnectionServices {
self.services.as_ref()
}
pub(super) fn services_arc(&self) -> Arc<dyn ConnectionServices> {
Arc::clone(&self.services)
}
/// Returns the complete participant service captured at supervisor startup.
pub(super) const fn participant_service(&self) -> Option<&InstalledParticipantService> {
self.participant_service.as_ref()
}
fn participant_service_fatal(&self) -> Result<Option<ParticipantServiceFatal>, ServerError> {
let Some(service) = self.participant_service() else {
return Ok(None);
};
service
.service_fatal()
.map_err(|error| ServerError::ParticipantIncarnation {
phase: "participant fatal latch inspection",
message: error.to_string(),
})
}
fn activate_fatal_shutdown(&self) {
if let Some(shutdown) = self.fatal_shutdown.as_ref() {
shutdown.initiate();
}
}
fn ensure_participant_service_live(&self) -> Result<(), ServerError> {
let Some(fatal) = self.participant_service_fatal()? else {
return Ok(());
};
self.activate_fatal_shutdown();
Err(ServerError::ParticipantServiceFatal { fatal })
}
fn latch_connection_fate_intent_incomplete(
&self,
open_sequence: u64,
conversation_id: u64,
) -> Result<ParticipantServiceFatal, ServerError> {
let Some(service) = self.participant_service() else {
return Err(ServerError::ParticipantIncarnation {
phase: "connection-fate fatal latch",
message: "a durable Open lacks its installed participant service".to_owned(),
});
};
let fatal = service
.latch_connection_fate_intent_incomplete(open_sequence, conversation_id)
.map_err(|error| ServerError::ParticipantIncarnation {
phase: "connection-fate fatal latch",
message: error.to_string(),
})?;
self.activate_fatal_shutdown();
Ok(fatal)
}
fn complete_connection_fate_fatal(
&self,
open_sequence: u64,
conversations: &[u64],
phase: &'static str,
error: &impl std::fmt::Display,
) -> ServerError {
tracing::error!(open_sequence, phase, %error, "durable connection-fate intent is incomplete");
let Some(&conversation_id) = conversations.first() else {
return ServerError::ParticipantIncarnation {
phase: "connection-fate fatal target",
message: "a durable Open has no tracked conversation target".to_owned(),
};
};
match self.latch_connection_fate_intent_incomplete(open_sequence, conversation_id) {
Ok(fatal) => ServerError::ParticipantServiceFatal { fatal },
Err(latch_error) => latch_error,
}
}
/// Runs one typed terminal fold after classification and before teardown.
pub(super) fn complete_connection_fate(
&self,
connection_incarnation: Option<ConnectionIncarnation>,
class: ConnectionFateClass,
conversations: &[u64],
) -> Result<(), ServerError> {
if conversations.is_empty() {
return Ok(());
}
self.ensure_participant_service_live()?;
let (Some(connection_incarnation), Some(_), Some(authority)) = (
connection_incarnation,
self.participant_service(),
self.incarnations.as_ref(),
) else {
return Err(ServerError::ParticipantIncarnation {
phase: "connection-fate authority composition",
message: "tracked participant conversations lack a complete service/incarnation authority"
.to_owned(),
});
};
let intent =
authority.open_connection_fate(connection_incarnation, class, conversations)?;
self.fold_or_park_connection_fate(intent)
}
/// Resolves the bound-only protocol-error gate from participant authority.
pub(super) fn connection_has_bound_participant(
&self,
connection_incarnation: Option<ConnectionIncarnation>,
conversations: &[u64],
) -> Result<bool, ServerError> {
if conversations.is_empty() {
return Ok(false);
}
self.ensure_participant_service_live()?;
let (Some(connection_incarnation), Some(service)) =
(connection_incarnation, self.participant_service())
else {
return Err(ServerError::ParticipantIncarnation {
phase: "bound participant classification",
message:
"tracked participant conversations lack a complete service/incarnation pair"
.to_owned(),
});
};
service
.connection_has_bound_participant(connection_incarnation, conversations)
.map_err(|error| ServerError::ParticipantIncarnation {
phase: "bound participant classification",
message: error.to_string(),
})
}
/// Returns the configured connection auth token as opaque bytes, or `None` when
/// no `[auth]` section was configured (open access).
pub(super) fn auth_token(&self) -> Option<&[u8]> {
self.auth_token.as_deref()
}
pub(super) const fn pass_verifier(&self) -> Option<&PassVerifier> {
self.pass_verifier.as_ref()
}
/// The installed Lys admitter with the network id subjects are placed
/// under, or `None` while no deploy has installed one.
pub(super) fn lys_admitter(
&self,
) -> Option<(&Arc<dyn crate::auth_lys::session::LysAdmitter>, &str)> {
self.lys_admitter
.get()
.map(|(admitter, network)| (admitter, network.as_str()))
}
/// Installs the Lys admitter once; a second install is refused so one
/// deploy cannot swap the authority another relied on.
///
/// # Errors
/// The admitter already installed.
pub(super) fn install_lys_admitter(
&self,
admitter: Arc<dyn crate::auth_lys::session::LysAdmitter>,
network_id: String,
) -> Result<(), Arc<dyn crate::auth_lys::session::LysAdmitter>> {
self.lys_admitter
.set((admitter, network_id))
.map_err(|(admitter, _)| admitter)
}
/// This liminal as a machine Lys knows, if `[auth.lys.machine]` named it.
pub(super) fn link_host(&self) -> Option<&Arc<crate::link::LinkHost>> {
self.link_host.get()
}
pub(super) fn service_bindings(
&self,
) -> Option<&Arc<crate::services::production::ServiceBindings>> {
self.service_bindings.get()
}
/// The services registry, if templates are configured (SRV-028).
pub(super) fn lifecycle(&self) -> Option<&Arc<crate::services::lifecycle::Lifecycle>> {
self.lifecycle.get()
}
/// Installs a services registry on a test runtime, once.
#[cfg(test)]
pub(super) fn install_lifecycle_for_tests(
&self,
lifecycle: Arc<crate::services::lifecycle::Lifecycle>,
) -> bool {
self.lifecycle.set(lifecycle).is_ok()
}
pub(super) fn install_service_bindings(
&self,
bindings: Arc<crate::services::production::ServiceBindings>,
) -> Result<(), Arc<crate::services::production::ServiceBindings>> {
self.service_bindings.set(bindings)
}
/// The channel membership gate, if `[auth.lys.membership]` configured
/// one (ACCESS-006 R1).
pub(super) fn membership_gate(&self) -> Option<&Arc<crate::auth_membership::MembershipGate>> {
self.membership_gate.get()
}
/// Installs the membership gate once; a second install is refused so
/// one deploy cannot swap the gate live bindings rely on.
///
/// # Errors
/// The gate already installed.
pub(super) fn install_membership_gate(
&self,
gate: Arc<crate::auth_membership::MembershipGate>,
) -> Result<(), Arc<crate::auth_membership::MembershipGate>> {
self.membership_gate.set(gate)
}
/// Installs the link host once; a second install is refused.
///
/// # Errors
/// The host already installed.
pub(super) fn install_link_host(
&self,
host: Arc<crate::link::LinkHost>,
) -> Result<(), Arc<crate::link::LinkHost>> {
self.link_host.set(host)
}
/// The grant-revocation authority, when a revocation policy is
/// installed (ACCESS-005).
pub(super) fn revocation(&self) -> Option<&Arc<crate::auth_revocation::RevocationAuthority>> {
self.revocation.get()
}
/// Installs the grant-revocation authority once; a second install is
/// refused.
///
/// # Errors
/// The authority already installed.
pub(super) fn install_revocation(
&self,
authority: Arc<crate::auth_revocation::RevocationAuthority>,
) -> Result<(), Arc<crate::auth_revocation::RevocationAuthority>> {
self.revocation.set(authority)
}
/// Returns the configured connection-keyed notifier, if any.
pub(super) fn notifier(&self) -> Option<&Arc<dyn ConnectionNotifier>> {
self.notifier.as_ref()
}
/// Offers a channel publish to the notifier's observability-drain tap, returning
/// `true` when the application consumed it (so the connection process skips the
/// normal fan-out). `false` when no notifier is installed (liminal standalone) or
/// the notifier did not recognise the channel, so the caller can invoke it
/// unconditionally and fall through to the normal publish path.
pub(super) fn notifier_channel_publish(&self, pid: u64, channel: &str, payload: &[u8]) -> bool {
self.notifier
.as_ref()
.is_some_and(|notifier| notifier.on_channel_publish(pid, channel, payload))
}
/// SRV-012 R7: connection `pid`'s pass names `participant`, so the
/// topology shows it on that connection from now on, in lowercase hex.
pub(super) fn pass_attached(&self, pid: u64, mount: MountKind, participant: &[u8]) {
const HEX: &[u8; 16] = b"0123456789abcdef";
if let Some(signals) = self.signals.get() {
let mut text = String::with_capacity(participant.len() * 2);
for byte in participant {
text.push(char::from(HEX[usize::from(byte >> 4)]));
text.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
signals.topology(crate::console::TopologyChange::ConnectionOpened {
id: pid,
mount: mount.into(),
participant: Some(text),
});
}
}
/// SRV-012 `to_stations`: the subscription whose library subscriber is
/// `subscriber` belongs to connection `pid`, so a publish it receives
/// names `pid`'s station.
pub(super) fn receiver(&self, pid: u64, subscriber: u64) {
if let Some(signals) = self.signals.get() {
signals.receiver(subscriber, pid);
}
}
/// SRV-012 R7: connection `pid` starts (`present`) or stops using `line`
/// one way; a worker's flows are its line's stops.
pub(super) fn flow(&self, pid: u64, line: &str, role: crate::console::FlowRole, present: bool) {
if let Some(signals) = self.signals.get() {
signals.topology(crate::console::TopologyChange::Flow {
connection: pid,
line: line.to_owned(),
role,
present,
});
}
}
/// Stores `registration` on the connection record for `pid`, so the close
/// path can later fire `on_worker_unregistered` for exactly the connections
/// that registered. A missing record (the connection already closed) is a
/// no-op.
///
/// # Errors
/// Returns [`ServerError`] when the connection registry mutex is poisoned.
pub(super) fn set_registration(
&self,
pid: u64,
registration: WorkerRegistration,
) -> Result<(), ServerError> {
let identity = registration.identity.clone();
let subjects = vec![registration.task_queue.clone()];
let activities = registration
.activities
.iter()
.map(|activity| crate::console::StationActivity {
name: activity.name.clone(),
input_schema_json: activity.input_schema_json.clone(),
output_schema_json: activity.output_schema_json.clone(),
})
.collect();
let mut records = lock(&self.records, "connection registry")?;
let Registry {
connections,
directory,
} = &mut *records;
let stored = match connections.get_mut(&pid) {
Some(record) => {
// SRV-027 R1: the directory follows the record under the one
// lock; a replacement registration moves the subject.
if let Some(earlier) = record.registration.as_ref() {
directory.forget(pid, &earlier.task_queue);
}
directory.register(pid, ®istration.task_queue);
record.registration = Some(registration);
true
}
None => false,
};
drop(records);
// SRV-012 R7: a registered worker is a station on the topology, by
// its identity, until its connection closes; SRV-027 R3: with its
// subjects and activities.
if stored && let Some(signals) = self.signals.get() {
signals.topology(crate::console::TopologyChange::Worker {
connection: pid,
identity,
subjects,
activities,
});
}
Ok(())
}
/// Stores the registry principal a successful pass-stamped `Connect`
/// verified on the connection record for `pid`, then fires
/// `on_pass_attached` — so the close path can later fire the matching
/// `on_pass_detached` for exactly the connections that attached, with the
/// same principal. The store precedes the fire and the registry lock is
/// released before it, so the notifier may call back into the supervisor.
/// A missing record (the connection already closed) stores nothing and
/// fires nothing: an attach with no record could never be paired with a
/// detach.
///
/// # Errors
/// Returns [`ServerError`] when the connection registry mutex is poisoned.
pub(super) fn attach_pass_principal(
&self,
pid: u64,
principal: &PassPrincipal,
) -> Result<(), ServerError> {
let stored = lock(&self.records, "connection registry")?
.connections
.get_mut(&pid)
.is_some_and(|record| {
record.pass_principal = Some(principal.clone());
true
});
if stored {
if let Some(notifier) = self.notifier.as_ref() {
notifier.on_pass_attached(pid, principal);
}
}
Ok(())
}
/// Allocates the next monotonic push correlation id.
fn next_push_correlation_id(&self) -> u64 {
self.next_push_id.fetch_add(1, Ordering::Relaxed)
}
/// Registers a one-shot reply slot for `correlation_id`, owned by connection
/// `pid`, and returns its receiver. `deadline` is the slot's optional absolute
/// reply expiry (`None` = the default no-deadline shape). The connection
/// process resolves the slot via [`resolve_push`]; the close path drops the
/// connection's outstanding slots via [`cancel_pushes_for_connection`]; an
/// explicit deadline resolves it via [`expire_push_if_due`].
///
/// # Errors
/// Returns [`ServerError`] when the correlation registry mutex is poisoned.
fn register_push(
&self,
pid: u64,
correlation_id: u64,
deadline: Option<Instant>,
subject: Option<String>,
wake: Option<super::wake::ReadyWaker>,
) -> Result<Receiver<PushSlotResolution>, ServerError> {
let (sender, receiver) = channel();
let limit = self.limits.max_pending_pushes_per_connection;
{
let mut slots = lock(&self.push_replies, "push correlation registry")?;
// §5 `max_pending_pushes_per_connection`: refuse a new in-flight push
// once this connection already holds the cap. Counted per owning pid so
// one connection cannot exhaust the shared registry; slots free on
// reply, deadline expiry, or connection close. The count-and-insert
// stays under the one lock so the cap is enforced atomically.
let outstanding = slots.values().filter(|pending| pending.pid == pid).count();
if outstanding >= limit {
return Err(ServerError::ConnectionCapReached {
operation: "server push".to_owned(),
cap: "max_pending_pushes_per_connection",
limit,
});
}
slots.insert(
correlation_id,
PendingPush {
pid,
subject,
sender,
deadline,
wake,
},
);
}
Ok(receiver)
}
/// Registers a confirmed, no-deadline push slot for `pid` without a
/// supervisor, so a unit fixture can answer it with a `PushReply` frame
/// through `apply_frame` and read the outcome on the awaiter. The awaiter's
/// runtime handle is empty: the no-deadline receive path never upgrades it.
#[cfg(test)]
pub(super) fn push_for_tests(
&self,
pid: u64,
subject: Option<&str>,
) -> Result<PushReplyAwaiter, ServerError> {
let correlation_id = self.next_push_correlation_id();
let receiver =
self.register_push(pid, correlation_id, None, subject.map(str::to_owned), None)?;
if !self.confirm_push_registration(pid, correlation_id) {
return Err(ServerError::ListenerAccept {
message: format!("connection process {pid} is not registered"),
});
}
Ok(PushReplyAwaiter {
correlation_id,
receiver,
deadline: None,
runtime: Weak::new(),
})
}
/// The subject retained by `pid`'s reply slot for `correlation_id`, read
/// before the reply is decided. Read and settle are two lock takes on
/// purpose (never nested with a record lock): a slot swept between them is
/// named by the settle as `UnknownCorrelation`, which is the truth then.
pub(super) fn push_binding(&self, pid: u64, correlation_id: u64) -> PushBinding {
let slots = recover_lock(&self.push_replies);
match slots.get(&correlation_id) {
Some(pending) if pending.pid == pid => pending
.subject
.clone()
.map_or(PushBinding::Subjectless, PushBinding::Subject),
Some(_) | None => PushBinding::Unbound,
}
}
/// Host-side, lazy evaluation of a push's reply deadline, called from an
/// elapsed [`PushReplyAwaiter::receive`] quantum. This NEVER wakes the
/// connection process and runs no timer — it inspects supervisor-owned state
/// under the registry lock only.
///
/// A slot with an explicit deadline that has passed is removed here (dropping
/// its `Sender` and releasing its §5 `max_pending_pushes_per_connection` cap
/// admission, since the cap is the per-pid slot count) and reported
/// [`PushSlotDisposition::Expired`]. A slot with no deadline, or a deadline
/// still in the future, is left UNTOUCHED and reported
/// [`PushSlotDisposition::Live`] — the elapsed quantum is a benign re-arm. A
/// missing slot is [`PushSlotDisposition::Absent`].
fn expire_push_if_due(&self, correlation_id: u64) -> PushSlotDisposition {
// S4: a poisoned registry must NOT read as slot absence — the slot (and
// its cap admission) may still be in the map. Reclamation recovers the
// guard: removal-only operations are sound on a recovered map (a panic
// in another critical section cannot leave the HashMap itself in a
// partial state; only our bookkeeping invariants could be stale, and
// removal restores them). Admission (`register_push`) stays fail-closed.
let mut slots = recover_lock(&self.push_replies);
let Some(pending) = slots.get(&correlation_id) else {
return PushSlotDisposition::Absent;
};
// Copy the deadline out so the immutable borrow of `slots` ends before the
// conditional `remove` below takes a mutable one.
let deadline = pending.deadline;
match deadline {
Some(at) if Instant::now() >= at => {
slots.remove(&correlation_id);
PushSlotDisposition::Expired
}
_ => PushSlotDisposition::Live,
}
}
/// Drops a registered reply slot without resolving it, used on the
/// push-enqueue failure path (the control could not be delivered to a
/// now-gone process, so the just-reserved slot is unreachable). Dropping the
/// slot's `Sender` wakes a still-waiting awaiter with a disconnected error.
///
/// Returns whether THIS call removed the slot. Removal under the registry
/// mutex is the atomic resolved-vs-cancelled transition: `false` means
/// another path won — [`resolve_push`](Self::resolve_push) already sent the
/// reply (its send happens under the same lock, so the payload is already in
/// the channel when this returns), or the connection's close path dropped
/// the slot (sender gone, channel disconnected).
/// Records one server `Push` frame queued for a connection's socket.
pub(super) fn record_push_queued(&self) {
self.pushes_queued.fetch_add(1, Ordering::Relaxed);
}
/// Server `Push` frames queued for sockets so far.
pub(super) fn pushes_queued(&self) -> u64 {
self.pushes_queued.load(Ordering::Relaxed)
}
pub(super) fn cancel_push(&self, correlation_id: u64) -> bool {
// S4: reclamation recovers a poisoned guard — a rollback that silently
// skipped its removal would strand the slot and its cap admission.
recover_lock(&self.push_replies)
.remove(&correlation_id)
.is_some()
}
/// Settles the reply slot for a push whose frame could not be enqueued,
/// applying the one ruling that separates a certain failure from a
/// recoverable one.
///
/// A frame larger than the whole outbound buffer can never be carried on
/// this connection at this bound, so its slot resolves to the named terminal
/// [`ServerError::PushFrameExceedsOutboundCapacity`]. EVERYTHING ELSE —
/// congestion behind traffic still draining, an encode failure, a socket
/// write error — cancels the slot exactly as before, and its dropped
/// `Sender` keeps the retryable [`ServerError::PushReplyDisconnected`]
/// reading, because retrying is the correct answer to all three.
///
/// This is the sole branch between the two, deliberately: a caller that
/// widened it would turn a busy moment into a permanent failure, which is a
/// worse defect than the one the named outcome exists to fix.
pub(super) fn settle_push_enqueue_failure(
&self,
pid: u64,
correlation_id: u64,
error: &OutboundError,
) {
if let Some(too_large) = error.frame_exceeds_capacity() {
tracing::warn!(
connection_pid = pid,
correlation_id,
needed = too_large.needed,
capacity = too_large.capacity,
queued = too_large.queued,
"server push frame exceeds the connection's whole outbound capacity; \
it can never be sent on this connection and its reply slot is failed by name"
);
self.fail_push_outbound_frame_too_large(
correlation_id,
too_large.needed,
too_large.capacity,
too_large.queued,
);
return;
}
tracing::warn!(
connection_pid = pid,
correlation_id,
%error,
"server push could not be enqueued; the push reply slot is cancelled"
);
self.cancel_push(correlation_id);
}
/// Resolves the reply slot for `correlation_id` with the ONE named terminal
/// outcome the outbound path can prove: the push's encoded frame is larger
/// than the whole outbound buffer, so it can never be carried on this
/// connection at this bound and no retry could change that.
///
/// Callers must have established `needed > capacity` first —
/// [`settle_push_enqueue_failure`](Self::settle_push_enqueue_failure) is the
/// only one, and it does. A frame that merely does not fit the CURRENT free
/// space is congestion and belongs on [`cancel_push`](Self::cancel_push),
/// whose dropped `Sender` keeps its retryable disconnect reading.
///
/// A slot that is already gone — answered, expired, or swept by connection
/// close — is a harmless no-op, exactly as a late reply is to
/// [`resolve_push`](Self::resolve_push): the first path to remove it under
/// the registry lock wins and the outcome it chose stands.
///
/// Removal and delivery stay under the ONE registry lock for the same reason
/// `resolve_push` does it — an awaiter that observes the slot gone is then
/// guaranteed to find the outcome already in the channel, instead of seeing
/// the removal, finding the channel empty, and reporting something else.
fn fail_push_outbound_frame_too_large(
&self,
correlation_id: u64,
needed: usize,
capacity: usize,
queued: usize,
) {
// S4: as `cancel_push` — a skipped removal here would strand the slot and
// its cap admission, and lose the only report the caller will ever get.
let mut slots = recover_lock(&self.push_replies);
if let Some(pending) = slots.remove(&correlation_id) {
pending
.sender
.send(PushSlotResolution::OutboundFrameTooLarge {
needed,
capacity,
queued,
})
.ok();
}
}
/// Drops every reply slot owned by connection `pid`, waking each awaiter with a
/// disconnected error (the dropped `Sender` disconnects the awaiter's
/// `Receiver`). Called from the close path so a connection that exits with
/// in-flight pushes signals worker death immediately instead of leaving each
/// awaiter to block the full push-reply timeout. A slot that [`resolve_push`]
/// already removed is gone, so it is untouched here; an unknown pid is a no-op.
fn cancel_pushes_for_connection(&self, pid: u64) {
// S4: the close sweep is the reclamation of last resort ("connection
// close at the latest") — it must complete on a poisoned map too.
// SRV-027 R2: a requester waiting on a routed push to this connection
// is woken now, so its next slice names the worker gone instead of
// waiting out the reply deadline. The senders drop with the slots, so
// each requester reads the disconnected outcome.
let woken = {
let mut slots = recover_lock(&self.push_replies);
let mut woken = Vec::new();
slots.retain(|_correlation_id, pending| {
if pending.pid == pid {
woken.extend(pending.wake.take());
false
} else {
true
}
});
woken
};
for wake in woken {
wake.fire();
}
}
/// S3 second half (shape (b), check-after-insert): pre-publication
/// confirmation that the connection record for `pid` still exists, run in
/// the INSERT -> CONFIRM -> PUBLISH order (S7 — confirming after the
/// enqueue let a close-swept-then-answered push report `Err` for a Push the
/// client had received). `true` leaves the slot in place and the caller may
/// publish; `false` means a concurrent close already removed the record —
/// this call then removes the caller's own just-inserted slot (rolling back
/// its cap admission) so nothing is stranded, and the caller returns
/// WITHOUT publishing: an `Err` from the push methods guarantees no `Push`
/// control was published.
///
/// Why exactly one side always observes the slot: `remove` (the single
/// record-removal path) removes the host record BEFORE sweeping the pid's
/// push slots, and this check reads the record AFTER inserting the slot and
/// BEFORE the control is published. Both records accesses are serialized by
/// the `records` mutex, so either (i) this read precedes the record removal
/// — then the slot insert precedes the sweep (insert < read < removal <
/// sweep in the happens-before order) and the SWEEP observes and removes
/// the slot: if the control was published in the meantime the awaiter reads
/// the truthful disconnected outcome and a late client reply is a harmless
/// no-op; or (ii) this read follows the record removal — then THIS call
/// observes the absence, rolls the slot back itself, and nothing was
/// published. When both observe (a sweep and a rollback can both run in
/// case (ii) if the insert also preceded the sweep), removal is idempotent
/// and the cap is derived from map membership, so nothing double-releases.
///
/// Lock discipline: `records` and `push_replies` are NEVER held together —
/// here (`records` read, released, then `push_replies` on rollback), in
/// `remove` (`records` removal, released, then the sweep), and everywhere
/// else in this file the two mutexes are taken strictly sequentially, so no
/// lock-order inversion is possible. This adds ZERO work to the connection
/// slice path: the re-check runs on the push caller's thread only.
pub(super) fn confirm_push_registration(&self, pid: u64, correlation_id: u64) -> bool {
if self.is_registered(pid) {
return true;
}
self.cancel_push(correlation_id);
false
}
/// Number of reserved push reply slots outstanding. A benign wait-quantum
/// timeout must NOT change this (the slot survives); an explicit-deadline
/// expiry, a consumed reply, and connection close each release exactly one.
#[cfg(test)]
pub(super) fn pending_push_count(&self) -> usize {
recover_lock(&self.push_replies).len()
}
/// Reserved push reply slots owned by connection `pid` — the exact quantity
/// the §5 `max_pending_pushes_per_connection` cap counts (test instrument).
#[cfg(test)]
pub(super) fn pending_push_count_for(&self, pid: u64) -> usize {
recover_lock(&self.push_replies)
.values()
.filter(|pending| pending.pid == pid)
.count()
}
/// Resolves the reply slot for `correlation_id` with the client's reply
/// payload, waking the [`PushReplyAwaiter`]. Called by the connection process
/// when a correlated `PushReply` frame arrives. A different connection is
/// refused without consuming the slot. A missing slot — already
/// resolved, expired at its explicit deadline, dropped by connection close, or
/// an unknown id — is a harmless no-op: a late `PushReply` for a slot that is
/// gone is discarded here, never delivered and never a panic or desync.
pub(super) fn resolve_push(
&self,
pid: u64,
correlation_id: u64,
payload: Vec<u8>,
) -> PushReplyDisposition {
self.settle_push(pid, correlation_id, PushSlotResolution::Reply(payload))
}
/// Settles the reply slot for `correlation_id` with the access refusal the
/// connection process decided for its `PushReply`: the slot is removed
/// exactly as for a delivered reply and the awaiter reads
/// [`ServerError::PushReplyRefused`] carrying `reason`. Same ownership and
/// missing-slot rules as [`resolve_push`](Self::resolve_push).
pub(super) fn refuse_push(
&self,
pid: u64,
correlation_id: u64,
reason: String,
) -> PushReplyDisposition {
self.settle_push(
pid,
correlation_id,
PushSlotResolution::ReplyRefused { reason },
)
}
/// The one removal-and-send for a reply slot, shared by the delivered reply
/// and the refused one so neither can grow its own slot lifecycle.
fn settle_push(
&self,
pid: u64,
correlation_id: u64,
resolution: PushSlotResolution,
) -> PushReplyDisposition {
// Recover the guard so a poisoned registry still delivers and reclaims replies.
let mut slots = recover_lock(&self.push_replies);
let Entry::Occupied(entry) = slots.entry(correlation_id) else {
return PushReplyDisposition::UnknownCorrelation;
};
// The connection identity is checked before the slot or its credit is released.
if entry.get().pid != pid {
return PushReplyDisposition::SenderMismatch;
}
let pending = entry.remove();
// Keep removal and send atomic to awaiters checking whether the slot still exists.
// The unbounded send never blocks; an abandoned receiver is a named discard.
let disposition = match pending.sender.send(resolution) {
Ok(()) => PushReplyDisposition::Resolved,
Err(_) => PushReplyDisposition::ReceiverDropped,
};
drop(slots);
// SRV-027 R2: a routed push tells its requester, once, after the
// resolution is in the channel; the requester's slice reads it.
if let Some(wake) = pending.wake {
wake.fire();
}
disposition
}
pub(super) const fn control_atom(&self) -> Atom {
self.control_atom
}
/// Sole registration path for a connection: the spawn thread inserts the
/// record synchronously, before `spawn_connection` returns the handle, so
/// `is_tracked`/`active_connection_count` reflect the connection
/// immediately. The connection handler never writes the registry (it only
/// reads via `mark_crashed`/`finish`), so there is a single writer here and
/// no register/ensure-register race.
///
/// Ordering note: `spawn_native` only enqueues the process, so its first
/// slice may run on another worker thread before this insert lands. If that
/// first slice exits immediately (e.g. a missing-stream crash) its
/// `mark_crashed`/`finish` removes nothing and this insert then leaves a
/// record for an already-dead pid. W4 leg 1 retires the per-accept
/// `reap_crashed` scan that used to self-heal that orphan continuously;
/// instead [`Self::reconcile_register_orphan`] closes the race with a SINGLE
/// point check on the registration event itself — never a loop.
/// `fd_guard` is `None` for a transport that owns no descriptor. The guard
/// exists to keep an fd alive until readiness deregistration has been
/// acknowledged; a loopback connection registers no readiness and holds no
/// descriptor, so there is nothing to guard and the slot is honestly empty
/// rather than filled with a placeholder.
fn register_connection(
&self,
pid: u64,
peer_addr: Option<SocketAddr>,
connection_incarnation: Option<ConnectionIncarnation>,
mount: MountKind,
fd_guard: Option<TcpStream>,
) -> Result<(), ServerError> {
self.register_record(pid, peer_addr, connection_incarnation, mount, fd_guard)?;
self.reconcile_register_orphan(pid);
Ok(())
}
/// Closes the register-orphan race (see [`Self::register_with_fd`]) with one
/// point check driven by the registration event — not a periodic scan. If
/// the just-registered pid is already absent from the scheduler process
/// table, its first slice has run and exited, so the record this
/// registration inserted is an orphan the retiring reap scan used to sweep;
/// reclaim it immediately through the ordinary `remove()` funnel. A pid still
/// present is live and needs nothing here: a later external termination rides
/// the exit-event reactor and an ordinary exit its own final slice.
fn reconcile_register_orphan(&self, pid: u64) {
let Some(scheduler) = self.scheduler.upgrade() else {
return;
};
// The process-table lookup returns a sharded guard; bind only the
// presence bool so the guard is released before `reclaim_terminated`
// takes the connection registry lock (no cross-lock hold).
let already_exited = scheduler.process_table().get(pid).is_none();
if !already_exited {
return;
}
let reason = scheduler
.peek_exit_reason(pid)
.unwrap_or(ExitReason::Normal);
self.reclaim_terminated(pid, reason);
}
/// TOLD reclamation of a connection whose process exited WITHOUT running a
/// final handler slice — external/panic termination, where
/// [`ConnectionProcess::Drop`] runs but no `mark_crashed`/`finish` does, and
/// the register-orphan race above. Delivered the instant beamr publishes the
/// process's [`ExitEvent`] (via [`run_reclaim_reactor`]) or at the
/// registration point check, and routed through the SAME [`Self::remove`]
/// funnel as every other teardown — no third funnel, no periodic scan.
/// Idempotent: a record already removed in-slice, by the orphan reconcile, or
/// by a duplicate delivery is a no-op here (remove returns `None`), so the §5
/// admission gauge is released exactly once.
fn reclaim_terminated(&self, pid: u64, reason: ExitReason) {
let Some(record) = self.remove(pid) else {
return;
};
self.fire_close_hooks(pid, &record);
tracing::warn!(
connection_pid = pid,
peer_addr = ?record.peer_addr,
mount = ?record.mount,
reason = ?reason,
"connection process exited without a final slice; host record reclaimed by delivery"
);
}
/// One exit-event delivery: drain beamr's retained outcome (sole drainer,
/// bounding its store) then reclaim through [`Self::reclaim_terminated`]. The
/// only non-production element is the `#[cfg(test)]` reclamation gate, which
/// is staged for at most one targeted pid and compiled out entirely in
/// production — the delivery semantics are identical with or without it.
fn deliver_reclamation(&self, scheduler: &Weak<Scheduler>, pid: u64, reason: ExitReason) {
if let Some(scheduler) = scheduler.upgrade() {
// The reason is already in-hand from the event; the drained outcome
// is discarded, its purpose being only to bound beamr's store.
drop(scheduler.take_exit_outcome(pid));
}
#[cfg(test)]
let staged = self.stage_reclaim_barrier(pid);
#[cfg(test)]
if let Some(barrier) = staged.as_ref() {
// Rendezvous: the pid is now dead but its record is still tracked —
// the S8 reclamation window (oracle 26). Then wait for the harness to
// release the reclaim.
barrier.reached.wait();
barrier.release.wait();
}
self.reclaim_terminated(pid, reason);
#[cfg(test)]
if let Some(barrier) = staged.as_ref() {
// Signal the funnel completed so the harness can observe the record
// gone without sampling.
barrier.done.wait();
}
}
#[cfg(test)]
fn register(&self, pid: u64, peer_addr: Option<SocketAddr>) -> Result<(), ServerError> {
self.register_record(pid, peer_addr, None, MountKind::Tcp, None)
}
/// Gives connection `pid` a record, as a spawned connection has, so a
/// unit test through `apply_frame` can see what is stored on it.
#[cfg(test)]
pub(super) fn register_for_tests(&self, pid: u64) -> Result<(), ServerError> {
self.register(pid, None)
}
/// The worker registration stored on connection `pid`'s record. A
/// registration is stored before its topology change is emitted, and
/// only then (`set_registration`), so `None` also means no
/// `TopologyChange::Worker` was emitted for it.
#[cfg(test)]
pub(super) fn stored_registration_for_tests(
&self,
pid: u64,
) -> Result<Option<WorkerRegistration>, ServerError> {
Ok(lock(&self.records, "connection registry")?
.connections
.get(&pid)
.and_then(|record| record.registration.clone()))
}
fn register_record(
&self,
pid: u64,
peer_addr: Option<SocketAddr>,
connection_incarnation: Option<ConnectionIncarnation>,
mount: MountKind,
fd_guard: Option<TcpStream>,
) -> Result<(), ServerError> {
match lock(&self.records, "connection registry")?
.connections
.entry(pid)
{
// ENFORCED (not comment-only): pids are fresh per spawn and a record
// is reclaimed through the single `remove` funnel before its pid can
// recycle, so an occupied slot here is a supervision defect. Refuse
// the whole registration rather than silently replacing — a replace
// would drop the displaced record's `fd_guard` outside the teardown
// funnel (orphaning a live connection's stream) and increment the
// `liminal_connections_active` gauge a second time with no paired
// decrement. The prior record stays intact; both spawn paths roll the
// fresh process back on this error. Same idiom as
// `StreamTable::insert` (entry-vacant → typed error) and the
// fail-closed duplicate-conversation refusal in `apply.rs`.
Entry::Occupied(_) => return Err(ServerError::ConnectionPidCollision { pid }),
Entry::Vacant(entry) => {
entry.insert(ConnectionRecord {
peer_addr,
mount,
connection_incarnation,
registration: None,
pass_principal: None,
readiness: None,
ready_pending: Arc::new(AtomicBool::new(false)),
parked: AtomicBool::new(false),
fd_guard,
});
}
}
// Single-writer vacant-only insert (see doc above and the refusal arm)
// pairs EXACTLY one gauge increment with the decrement in `remove`,
// keeping `liminal_connections_active` equal to the live record count on
// every teardown route; a refused duplicate increments nothing.
crate::metrics::connection_spawned();
if let Some(signals) = self.signals.get() {
signals.connection(pid, true);
signals.topology(crate::console::TopologyChange::ConnectionOpened {
id: pid,
mount: mount.into(),
participant: None,
});
}
Ok(())
}
pub(super) fn mark_crashed(&self, pid: u64, reason: ExitReason, peer_addr: Option<SocketAddr>) {
let removed = self.remove(pid);
if let Some(record) = removed.as_ref() {
self.fire_close_hooks(pid, record);
}
let removed_peer_addr = removed
.as_ref()
.and_then(|record| record.peer_addr)
.or(peer_addr);
// The mount names the door this connection came through — the one fact
// that tells a reader whether a crashed connection was a socket peer or
// a co-resident caller, which `peer_addr: None` alone cannot.
let mount = removed.as_ref().map(|record| record.mount);
tracing::warn!(
connection_pid = pid,
peer_addr = ?removed_peer_addr,
mount = ?mount,
reason = ?reason,
"connection process crashed"
);
}
/// Whether the spawn thread has installed the host record. A first native
/// slice can win the enqueue-vs-record race and must remain runnable until it
/// has somewhere host-reachable to publish its readiness token.
pub(super) fn is_registered(&self, pid: u64) -> bool {
self.contains(pid)
}
/// Removes a token minted in-slice when publishing it to the host record fails.
pub(super) fn deregister_unpublished_readiness(&self, token: ReadinessToken) {
if let Some(scheduler) = self.scheduler.upgrade() {
scheduler.readiness_deregister(token);
}
}
/// Cancels deadline timers detached by reply completion or connection close.
pub(super) fn cancel_deadline_timers(&self, timers: Vec<TimerRef>) {
let Some(scheduler) = self.scheduler.upgrade() else {
return;
};
if let Ok(mut wheel) = scheduler.timers().lock() {
for timer in timers {
wheel.cancel(timer);
}
}
}
pub(super) fn finish(&self, pid: u64) {
if let Some(removed) = self.remove(pid) {
self.fire_close_hooks(pid, &removed);
}
}
/// Records the one readiness token minted for this connection. A live
/// connection never re-registers: later parked slices rearm this identity.
pub(super) fn set_readiness_token_once(
&self,
pid: u64,
token: ReadinessToken,
fd: RawFd,
) -> Result<(), ServerError> {
let mut records = lock(&self.records, "connection registry")?;
let record =
records
.connections
.get_mut(&pid)
.ok_or_else(|| ServerError::ListenerAccept {
message: format!(
"connection {pid} has no host record for readiness registration"
),
})?;
if record.readiness.is_some() {
return Err(ServerError::ListenerAccept {
message: format!("connection {pid} attempted to replace its readiness token"),
});
}
record.readiness = Some(ReadinessRegistration { token, fd });
drop(records);
Ok(())
}
/// Fires the close-side notifier hooks for a removed connection record:
/// `on_worker_unregistered` when it carried a worker registration, and
/// `on_pass_detached` (with the principal) when it carried a pass
/// principal. A record with neither — a plain bearer or open-access
/// connection, or a worker connection that never registered — is a no-op,
/// so each close hook fires for exactly the connections whose open-side
/// counterpart fired. Every teardown route (`finish`, `mark_crashed`,
/// `reclaim_terminated`, `reap_crashed`) reaches this through the
/// idempotent [`Self::remove`], so each fires at most once per connection.
fn fire_close_hooks(&self, pid: u64, record: &ConnectionRecord) {
let Some(notifier) = self.notifier.as_ref() else {
return;
};
if record.registration.is_some() {
notifier.on_worker_unregistered(pid);
}
if let Some(principal) = record.pass_principal.as_ref() {
notifier.on_pass_detached(pid, principal);
}
}
fn reap_crashed(&self, scheduler: &Scheduler) -> usize {
let pids = match self.records.lock() {
Ok(records) => records.connections.keys().copied().collect::<Vec<_>>(),
Err(error) => {
tracing::warn!(%error, "connection registry unavailable during crash reap");
return 0;
}
};
let mut reaped = 0;
for pid in pids {
if scheduler.process_table().get(pid).is_none() {
let removed = self.remove(pid);
if let Some(record) = removed.as_ref() {
self.fire_close_hooks(pid, record);
}
let peer_addr = removed.and_then(|record| record.peer_addr);
// This process exited without ever reaching `mark_crashed`/`finish`
// (e.g. the beamr scheduler terminated it externally). W4 leg 1
// retired this scan from the per-accept listener loop, and W4 leg 3
// retired the shutdown-drain reconciliation that also drove it: the
// reclaimer of these exits is now the TOLD exit-event reactor
// ([`run_reclaim_reactor`]), which also composes drain completion
// through the one `remove()` funnel. This scan now survives only as
// that reactor's exit-event overflow (`Lagged`) recovery, driven a
// bounded number of times, never periodically. beamr 0.15.4 exposes
// a public, non-blocking
// `peek_exit_reason` (and `take_exit_outcome`), so the real reason
// IS recoverable here rather than logged as an opaque literal.
let reason = scheduler.peek_exit_reason(pid);
tracing::warn!(
connection_pid = pid,
?peer_addr,
?reason,
"connection process exited without a final slice; reclaimed by reconciliation"
);
reaped += 1;
}
}
reaped
}
fn contains(&self, pid: u64) -> bool {
self.records
.lock()
.is_ok_and(|records| records.connections.contains_key(&pid))
}
#[cfg(test)]
fn readiness_registration_count(&self) -> usize {
self.records.lock().map_or(0, |records| {
records
.connections
.values()
.filter(|record| record.readiness.is_some())
.count()
})
}
#[cfg(test)]
fn readiness_fd(&self, pid: u64) -> Option<RawFd> {
self.records
.lock()
.ok()?
.connections
.get(&pid)
.and_then(|record| record.readiness.map(|registration| registration.fd))
}
#[cfg(test)]
fn readiness_token(&self, pid: u64) -> Option<ReadinessToken> {
self.records
.lock()
.ok()?
.connections
.get(&pid)
.and_then(|record| record.readiness.map(|registration| registration.token))
}
fn active_connections(&self) -> Vec<ActiveConnection> {
self.records.lock().map_or_else(
|_| Vec::new(),
|records| {
records
.connections
.iter()
.map(|(&pid, record)| ActiveConnection {
pid,
peer_addr: record.peer_addr,
})
.collect()
},
)
}
/// Reads the complete active-connection incarnation set under the
/// registry lock — the bounded defense-in-depth collision-skip input to
/// incarnation allocation (uniqueness itself comes from allocator-log
/// monotonicity; see `allocate_connection_incarnation`). Poisoning fails
/// admission closed: treating an unreadable registry as empty would
/// silently drop the defense layer.
fn complete_active_incarnation_references(
&self,
) -> Result<Vec<ConnectionIncarnation>, ServerError> {
Ok(
lock(&self.records, "connection incarnation reference registry")?
.connections
.values()
.filter_map(|record| record.connection_incarnation)
.collect(),
)
}
fn push_control(&self, pid: u64, control: ConnectionControl) -> Result<(), ServerError> {
lock(&self.controls, "connection control queue")?
.push(QueuedConnectionControl { pid, control });
Ok(())
}
pub(super) fn pop_control(&self, pid: u64) -> Option<ConnectionControl> {
let mut controls = self.controls.lock().ok()?;
let index = controls.iter().position(|queued| queued.pid == pid)?;
Some(controls.remove(index).control)
}
/// Non-consuming final-probe query for controls enqueued after mailbox drain.
pub(super) fn has_control(&self, pid: u64) -> bool {
self.controls
.lock()
.is_ok_and(|controls| controls.iter().any(|queued| queued.pid == pid))
}
/// Pulls a queued-but-unconsumed control back out of the queue. Returns
/// whether THIS call removed it — `false` means the entry already left the
/// queue, and since [`Self::pop_control`] is the only other remover, a
/// consumer drain took it (S8's publication disambiguator). Matching is
/// `pid` + full control equality; a `Push` control embeds its
/// runtime-unique correlation id, so this can never remove a different
/// push's entry and misreport.
fn remove_control(&self, pid: u64, control: &ConnectionControl) -> bool {
let Ok(mut controls) = self.controls.lock() else {
return false;
};
let Some(index) = controls
.iter()
.position(|queued| queued.pid == pid && &queued.control == control)
else {
return false;
};
controls.remove(index);
true
}
fn active_count(&self) -> usize {
self.records
.lock()
.map_or(0, |records| records.connections.len())
}
/// Test read of the record's stamped mount (design §10).
#[cfg(test)]
fn connection_mount(&self, pid: u64) -> Option<MountKind> {
self.records
.lock()
.ok()?
.connections
.get(&pid)
.map(|record| record.mount)
}
/// Test read of whether the record holds an fd guard.
#[cfg(test)]
fn connection_has_fd_guard(&self, pid: u64) -> Option<bool> {
self.records
.lock()
.ok()?
.connections
.get(&pid)
.map(|record| record.fd_guard.is_some())
}
/// Removes the connection record for `pid` and, in the same close step, drops
/// every push reply slot that connection still owns so each waiting
/// [`PushReplyAwaiter`] wakes immediately with a disconnected error. This runs
/// on every close route — `finish`, `mark_crashed`, and `reap_crashed` all
/// remove through here — and fires regardless of whether the connection ever
/// registered a worker, so a plain push target is covered too.
///
/// ORDER MATTERS (S3/S7): the record is removed BEFORE the push sweep. A
/// push registering concurrently runs INSERT -> CONFIRM -> PUBLISH
/// (`confirm_push_registration` reads the record after inserting its slot
/// and before publishing its control), so with this ordering exactly one
/// side always observes a racing slot: a confirm that ran before this
/// removal implies the slot was inserted before the sweep below (which then
/// reaps it — a control published after that confirm is answered into a
/// swept slot, read as the truthful disconnected outcome); a confirm after
/// this removal sees the absence, rolls the slot back itself, and never
/// publishes. Sweeping first (the original order) left a window — sweep,
/// then insert+confirm, then record removal — where NEITHER side observed
/// the slot and it leaked past connection close. The two locks are taken
/// strictly sequentially (never nested), so no lock-order inversion.
fn remove(&self, pid: u64) -> Option<ConnectionRecord> {
let mut removed = self.records.lock().ok().and_then(|mut records| {
let removed = records.connections.remove(&pid);
// SRV-027 R1: the directory entry leaves with its record, in
// this same lock take.
if let Some(registration) = removed
.as_ref()
.and_then(|record| record.registration.as_ref())
{
records.directory.forget(pid, ®istration.task_queue);
}
removed
});
#[cfg(test)]
let host_fd = removed
.as_ref()
.and_then(|record| record.fd_guard.as_ref())
.map(std::os::fd::AsRawFd::as_raw_fd);
self.cancel_pushes_for_connection(pid);
if let Some(registration) = removed.as_mut().and_then(|record| record.readiness.take()) {
if let Some(scheduler) = self.scheduler.upgrade() {
// This call is ACK'd: it returns only after the poll owner has
// removed the registration. `fd_guard` is still live here.
scheduler.readiness_deregister(registration.token);
tracing::debug!(
registered_fd = registration.fd,
"connection readiness deregistration acknowledged"
);
}
}
if let Some(record) = removed.as_mut() {
// Explicit after-deregister drop documents and enforces the fd wall.
drop(record.fd_guard.take());
}
// Decrement only when a record was actually present so a double-remove
// (e.g. `finish` after `reap_crashed`) cannot drive the gauge negative.
// The §5 admission slot is released on the same guard: the reservation
// acquired in `spawn_connection` converted into this record at
// `register`, so its removal is exactly one release per reservation.
if removed.is_some() {
crate::metrics::connection_closed();
self.release_admission();
// ACCESS-005 R6: the connection's grant-index membership is
// retired on this same once-per-record guard, so revoke, EOF,
// crash and force-close all release it exactly once.
if let Some(revocation) = self.revocation.get()
&& revocation.release(pid)
{
tracing::debug!(connection_pid = pid, "grant-decision binding released");
}
if let Some(signals) = self.signals.get() {
#[cfg(test)]
self.probe_close_event_fd(host_fd);
signals.connection(pid, false);
signals.topology(crate::console::TopologyChange::ConnectionClosed { id: pid });
}
}
// TOLD drain-completion tell (W4 leg 3, §4.3): the record map above already
// reflects this removal, so bump the removal generation and wake the
// drain/settle waiter AFTER the observed state is updated. Ordering the
// state update before the generation bump — paired with the waiter arming
// its snapshot before observing `active_count` — is the arm-before-observe
// barrier that makes a concurrently delivered exit un-losable (oracle 18).
// Only a real removal tells, so a double-remove drives no spurious wake.
if removed.is_some() {
self.signal_connection_removed();
// Removal can complete delivery quiescence without another park.
// Tell the earlier flush waiter as well as the later drain waiter.
if self.settle_armed.load(Ordering::Acquire) {
self.signal_settle_changed();
}
}
removed
}
#[cfg(test)]
fn probe_close_event_fd(&self, host_fd: Option<RawFd>) {
let mut probe = match self.close_event_fd_probe.lock() {
Ok(probe) => probe,
Err(error) => {
tracing::error!(%error, "close-event fd probe lock poisoned");
return;
}
};
if !matches!(*probe, CloseEventFdProbe::Armed) {
return;
}
let observed = host_fd.map_or_else(
|| Err(std::io::Error::other("close-event probe has no owned fd")),
|fd| match std::fs::File::open(format!("/dev/fd/{fd}")) {
Ok(duplicate) => {
drop(duplicate);
Ok(false)
}
Err(error) if matches!(error.raw_os_error(), Some(2 | 9)) => Ok(true),
Err(error) => Err(error),
},
);
*probe = CloseEventFdProbe::Observed(observed);
}
/// Bumps the drain-completion generation and wakes the drain/settle waiter.
/// Called from [`Self::remove`] on every route that actually drops a record.
fn signal_connection_removed(&self) {
// Bump the generation under the lock, release it, THEN notify. A waiter
// holds this lock continuously from its generation re-check through the
// atomic release inside `wait_timeout`, so it can never miss a bump
// published before the notify — the Condvar lost-wakeup contract holds
// without notifying under the guard.
{
let mut generation = recover_lock(&self.drain_generation);
*generation = generation.wrapping_add(1);
}
self.drain_removed.notify_all();
}
/// Parks the calling thread until every tracked connection has been removed
/// or `deadline` elapses, returning `true` when the drain completed and
/// `false` when the single admitted deadline won. This is the TOLD
/// replacement (W4 leg 3, §4.3) for the retired reap/count/sleep drain loop:
/// it never samples completion on a timer. Completion is observed only on a
/// delivered connection-removal wake (composed from the one `remove()` funnel,
/// so a Died/Detached/crash exit and an orderly close decrement through the
/// same path — oracle 15) or the one deadline. Force-close settle reuses this
/// same waiter with its own deadline rather than a second poll loop (oracle
/// 14).
pub(super) fn wait_for_active_connections_drained(&self, deadline: Instant) -> bool {
loop {
// ARM before OBSERVE: snapshot the removal generation first, so an exit
// delivered after the completion observation below and before the park
// bumps a generation the park detects — it is never lost (oracle 18).
let snapshot = self.drain_generation_snapshot();
// OBSERVE completion first: a last exit that reaches zero wins a tie
// with a simultaneously elapsed deadline (oracle 19).
if self.active_count() == 0 {
return true;
}
let Some(remaining) = deadline.checked_duration_since(Instant::now()) else {
#[cfg(test)]
self.drain_deadline_hits.fetch_add(1, Ordering::SeqCst);
return false;
};
#[cfg(test)]
self.run_drain_park_barrier();
self.park_until_removed_or(snapshot, remaining);
}
}
/// Reads the current removal generation under its mutex.
fn drain_generation_snapshot(&self) -> u64 {
*recover_lock(&self.drain_generation)
}
/// The removal generation, read as a departure count. A poisoned lock is
/// an error here, not recovered: a caller waiting on departures must not
/// read a count a panicking holder may have left half-written.
pub(super) fn departures(&self) -> Result<u64, ServerError> {
Ok(*lock(&self.drain_generation, "connection departures")?)
}
/// Parks on the removal `Condvar` until the generation has advanced by
/// `count` since `since`, or until `deadline`. `wait_timeout_while` checks
/// the predicate under the lock before it parks, so departures already
/// counted return at once, and spurious wakes park again inside the call.
pub(super) fn await_departures(
&self,
since: u64,
count: u64,
deadline: Instant,
) -> Result<bool, ServerError> {
let remaining = deadline.saturating_duration_since(Instant::now());
let (generation, _timed_out) = self
.drain_removed
.wait_timeout_while(
lock(&self.drain_generation, "connection departures")?,
remaining,
|current| current.wrapping_sub(since) < count,
)
.map_err(|error| ServerError::ListenerAccept {
message: format!("connection departures unavailable: {error}"),
})?;
let departed = generation.wrapping_sub(since) >= count;
drop(generation);
Ok(departed)
}
/// Parks on the removal `Condvar` for at most `timeout`, but only while no
/// removal has bumped the generation since `snapshot` — the arm-before-observe
/// barrier. `wait_timeout_while` evaluates the predicate under the lock BEFORE
/// waiting, so a generation already advanced (an exit landed between the
/// observation and here) returns immediately without sleeping; spurious wakes
/// re-wait inside the call and never return early.
fn park_until_removed_or(&self, snapshot: u64, timeout: Duration) {
let outcome = self
.drain_removed
.wait_timeout_while(recover_lock(&self.drain_generation), timeout, |current| {
*current == snapshot
})
.unwrap_or_else(PoisonError::into_inner);
// A non-timed-out return means the predicate went false — a real removal
// bumped the generation and woke this park (as opposed to the deadline).
#[cfg(test)]
if !outcome.1.timed_out() {
self.drain_exit_wakes.fetch_add(1, Ordering::SeqCst);
}
// Release the guard promptly; the caller re-loops unlocked.
drop(outcome);
}
}
/// A reply either settles its recipient's slot or names why it was discarded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[must_use]
pub(super) enum PushReplyDisposition {
Resolved,
SenderMismatch,
UnknownCorrelation,
ReceiverDropped,
}
/// What `pid`'s reply slot retains for a reply's access decision.
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use]
pub(super) enum PushBinding {
/// No slot for this correlation id is owned by `pid`; the settle names the
/// exact disposition.
Unbound,
/// The push was made with no subject ([`ConnectionSupervisor::push_to_connection`]).
Subjectless,
/// The subject the push was made on ([`ConnectionSupervisor::push_to_subject`]).
Subject(String),
}
/// One in-flight server-push reply slot, associating the awaiter's reply `sender`
/// with the `pid` of the connection that owns the push. The pid lets the close
/// path drop exactly that connection's slots; the correlation id (the map key)
/// still drives [`ConnectionRuntime::resolve_push`] and
/// [`ConnectionRuntime::cancel_push`].
#[derive(Debug)]
struct PendingPush {
pid: u64,
/// The subject the push was made on, recorded at push time by
/// [`ConnectionSupervisor::push_to_subject`] and read back by
/// [`ConnectionRuntime::push_binding`] when the reply is decided. `None`
/// for a push made without one.
subject: Option<String>,
sender: Sender<PushSlotResolution>,
/// Absolute reply deadline for this push, when one was requested via
/// [`ConnectionSupervisor::push_to_connection_with_deadline`]. `None` is the
/// default 0.2.3 shape: the slot has no per-slot deadline and is reclaimed
/// only by reply-consumed or connection-close. `Some` is evaluated host-side
/// and lazily in [`ConnectionRuntime::expire_push_if_due`].
deadline: Option<Instant>,
/// SRV-027 R2: the requester connection a routed push answers, woken once
/// when the slot resolves (a reply, a refusal, or the worker's close) so
/// its next slice relays the outcome. `None` for a hosting application's
/// push, whose awaiter is received on the caller's own thread.
wake: Option<super::wake::ReadyWaker>,
}
/// What a reply slot resolves TO when it is woken through its channel.
///
/// Distinct from [`PushSlotDisposition`], which is what a host-side deadline
/// touch FOUND. Every OTHER way a slot dies — connection close, the close sweep,
/// the publication rollback — drops the `Sender` instead of sending one of these,
/// and so keeps reading as the retryable [`ServerError::PushReplyDisconnected`].
/// That is deliberate: only a frame the connection can NEVER carry gets a named
/// terminal outcome here.
enum PushSlotResolution {
/// The client's correlated reply payload.
Reply(Vec<u8>),
/// The client's correlated reply arrived and was refused by the access
/// decision on the push's retained subject; `reason` is the refusal as the
/// route would have carried it. TERMINAL: the reply was never delivered.
ReplyRefused {
/// The refusal, rendered as the four-field access refusal.
reason: String,
},
/// The push was never queued for the wire: its encoded frame is larger than
/// the whole outbound buffer, so draining could never make room for it.
/// CERTAIN, and therefore terminal. Congestion never arrives here.
OutboundFrameTooLarge {
/// Encoded size of the rejected frame; exceeds `capacity` on its own.
needed: usize,
/// The outbound buffer's whole capacity.
capacity: usize,
/// Bytes queued when the frame was rejected (log context only).
queued: usize,
},
}
/// Host-side disposition of a reply slot at an elapsed `receive` quantum.
enum PushSlotDisposition {
/// The slot carried an explicit deadline that has passed; this call removed
/// it (releasing its §5 cap admission).
Expired,
/// The slot is present with no deadline, or a deadline still in the future:
/// the elapsed quantum is a benign re-arm and the slot is untouched.
Live,
/// No slot for this correlation id — a concurrent resolve or connection close
/// already removed it.
Absent,
}
/// The connection records and the service directory built from them, under
/// one lock (SRV-027 R1): a directory entry is added when its record stores a
/// registration and removed in the same lock take that removes or replaces
/// the record, so no lookup names a connection whose record is gone.
#[derive(Debug, Default)]
struct Registry {
connections: HashMap<u64, ConnectionRecord>,
directory: super::service_directory::ServiceDirectory,
}
#[derive(Debug)]
struct ConnectionRecord {
peer_addr: Option<SocketAddr>,
/// Which door admitted this connection (design §10). Written once, by the
/// spawn path, from the server's own knowledge of which path it is; never
/// read from, or influenced by, anything the client sends.
mount: MountKind,
/// Durable pair allocated and flushed before the process was spawned.
connection_incarnation: Option<ConnectionIncarnation>,
/// Worker registration declared on this connection, set by `set_registration`
/// when a `WorkerRegister` frame is accepted. `Some` marks a connection whose
/// close must fire `on_worker_unregistered`.
registration: Option<WorkerRegistration>,
/// Registry principal a pass-stamped `Connect` verified, set by
/// `attach_pass_principal` once the handshake succeeded. `Some` marks a
/// connection whose close must fire `on_pass_detached` with it.
pass_principal: Option<PassPrincipal>,
/// Host-reachable identity for ACK'd deregistration after external death.
readiness: Option<ReadinessRegistration>,
/// Shared edge set before READY enters beamr's process-table pending queue;
/// the executing process reads it at its final probe.
ready_pending: Arc<AtomicBool>,
/// FIX A-ii: `true` while this connection is parked (its last slice returned
/// `Wait`). A parked connection with no `ready_pending` edge has fanned out
/// every accepted publish to its socket, so the shutdown flush barrier reads
/// this with `ready_pending` to know delivery has quiesced before it lets the
/// shutdown Disconnect be broadcast.
parked: AtomicBool,
/// Keeps the fd alive until deregistration has been acknowledged, preventing
/// stale registration delivery to a subsequently reused descriptor number.
fd_guard: Option<TcpStream>,
}
#[derive(Debug, Clone, Copy)]
struct ReadinessRegistration {
token: ReadinessToken,
fd: RawFd,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct QueuedConnectionControl {
pid: u64,
control: ConnectionControl,
}
fn lock<'a, T>(mutex: &'a Mutex<T>, context: &str) -> Result<MutexGuard<'a, T>, ServerError> {
mutex.lock().map_err(|error| ServerError::ListenerAccept {
message: format!("{context} unavailable: {error}"),
})
}
/// Locks `mutex`, RECOVERING a poisoned guard instead of failing (S4). For
/// lifecycle-cleanup paths only (reply delivery, expiry, cancellation, the
/// close sweep): removal-style operations are sound on a recovered map, and a
/// cleanup that silently skipped its removal would strand slots and their §5
/// cap admissions forever. Admission paths keep the fail-closed [`lock`].
fn recover_lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[test]
fn host_fd_is_closed_before_connection_close_event_handoff()
-> Result<(), Box<dyn std::error::Error>> {
use std::os::fd::AsRawFd;
let fixture = crate::server::self_streams::tests::R3Fixture::new()?;
let services: Arc<dyn ConnectionServices> = fixture.services;
let runtime = ConnectionRuntime::for_tests(services);
runtime
.signals
.set(ServerSignals::default())
.map_err(|_| "close-event signals already installed")?;
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
let client = TcpStream::connect(listener.local_addr()?)?;
let (server, address) = listener.accept()?;
let host_fd = server.as_raw_fd();
let positive_control = std::fs::File::open(format!("/dev/fd/{host_fd}"))?;
drop(positive_control);
runtime.register_record(1, Some(address), None, MountKind::Tcp, Some(server))?;
*runtime
.close_event_fd_probe
.lock()
.map_err(|error| error.to_string())? = CloseEventFdProbe::Armed;
let removed = runtime
.remove(1)
.ok_or("fd-owning connection was not removed")?;
let mut probe = runtime
.close_event_fd_probe
.lock()
.map_err(|error| error.to_string())?;
let CloseEventFdProbe::Observed(observed) =
std::mem::replace(&mut *probe, CloseEventFdProbe::Off)
else {
return Err("close-event handoff was not observed".into());
};
drop(probe);
assert!(
observed?,
"connection-close event was handed off while its host fd remained open"
);
assert!(removed.fd_guard.is_none());
drop(removed);
drop(client);
drop(listener);
Ok(())
}
/// ACCESS-003 R1: the context watch drains its own subscription the way the
/// connection pump does; each reading carries its message id, the stable
/// event id Lys charges it under.
impl crate::services::context_watch::ContextFeed for super::services::ConnectionSubscription {
fn next_reading(&mut self) -> Option<(String, Vec<u8>)> {
self.try_next()
.map(|envelope| (envelope.message_id.as_uuid().to_string(), envelope.payload))
}
}
/// Starts the context watch over the `context-watch` channel when the
/// service bindings ask for it (ACCESS-003 R1).
///
/// One subscription whose inbox
/// wakes the watcher on every admitted reading, bounded by the same §5
/// limits a connection's subscription is. `Ok(None)` when the bindings do not
/// watch.
///
/// # Errors
/// The `context-watch` channel refused the subscription (it must be
/// configured), or the watcher thread did not start.
pub fn start_context_watch(
services: &dyn ConnectionServices,
bindings: &crate::services::production::ServiceBindings,
limits: &LimitsConfig,
) -> Result<Option<crate::services::context_watch::ContextWatch>, ServerError> {
if !bindings.watches_context() {
return Ok(None);
}
let wake = crate::services::context_watch::ContextWake::new();
let install = liminal::channel::InboxInstall {
budget: liminal::channel::ConnectionInboxBudget::new(limits.max_connection_inbox_bytes),
depth_cap: limits.max_subscription_inbox_depth,
notifier: Some(wake.notifier()),
capacity: None,
};
let subscription = services.subscribe(
crate::services::ServiceKind::ContextWatch.subject_shape(),
&[],
Some(install),
)?;
crate::services::context_watch::ContextWatch::start(
subscription,
wake,
bindings.context_reporter(),
)
.map(Some)
.map_err(|error| ServerError::ConfigValidation {
message: error.to_string(),
})
}