epics-ca-rs 0.20.2

EPICS Channel Access protocol client and server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
use epics_base_rs::runtime::sync::{Mutex, RwLock};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufWriter};
use tokio::net::TcpListener;
use tokio::sync::broadcast;

/// Maximum accumulated TCP read buffer per client (DoS guard).
///
/// This MUST be >= the largest legal single frame, otherwise a valid
/// large waveform (e.g. a 2 MB array, well under the 16 MB
/// `max_payload_size()` default) would push `accumulated` past the cap
/// and the connection would be closed before the frame could be
/// dispatched — a permanent failure that survives reconnect.
///
/// Largest legal frame = extended header (24 bytes) + `max_payload_size()`
/// payload. We add a 64 KiB slack so a partially-received *next* frame
/// pipelined behind a full one in the same read burst does not trip the
/// guard before the first frame is drained. `max_payload_size()` honours
/// `EPICS_CA_MAX_ARRAY_BYTES`, so the cap tracks any operator override.
/// Mirrors the client-side cap in `client/transport.rs`.
fn max_accumulated() -> usize {
    crate::protocol::max_payload_size()
        .saturating_add(24)
        .saturating_add(64 * 1024)
}

/// Optional application-level idle timeout before forcibly closing a TCP
/// client. Disabled by default — OS-level TCP keepalive (set in `accept_loop`,
/// 15s idle + 5s probes) is the primary half-open detector and matches C
/// epics-base rsrv (`caservertask.c:1456` sets only `SO_KEEPALIVE`, with no
/// application-level idle timeout).
///
/// A C client receiving a continuous monitor stream may never send
/// `CA_PROTO_ECHO` (libca resets its echo timer on every received frame from
/// the server), so an inactivity timeout based purely on incoming reads
/// produces false-positive disconnects on healthy connections — the bug
/// archaeology REVIEW for this is in `archaeology/REVIEWS/`. Operators who
/// want a defensive cap (e.g., NAT environments where TCP keepalive is
/// unreliable) can set `EPICS_CAS_INACTIVITY_TMO` to a positive value;
/// values < 30 are clamped to 30 to avoid pathological short timeouts.
fn inactivity_timeout() -> Option<Duration> {
    epics_base_rs::runtime::env::get("EPICS_CAS_INACTIVITY_TMO")
        .and_then(|s| s.parse::<f64>().ok())
        .filter(|v| *v > 0.0)
        .map(|v| Duration::from_secs_f64(v.max(30.0)))
}

/// Read into `buf` with an optional idle cap. If `cap` is `None`, the read
/// is unbounded (matches C `recv()` blocking semantics in `camsgtask.c`);
/// if `cap` is `Some(d)`, returns `Err(d)` after `d` of inactivity.
async fn read_with_optional_timeout<R: tokio::io::AsyncReadExt + Unpin>(
    reader: &mut R,
    buf: &mut [u8],
    cap: Option<Duration>,
) -> Result<std::io::Result<usize>, Duration> {
    match cap {
        None => Ok(reader.read(buf).await),
        Some(d) => match tokio::time::timeout(d, reader.read(buf)).await {
            Ok(r) => Ok(r),
            Err(_) => Err(d),
        },
    }
}

/// Parse an opt-in resource cap from an env value. `None` (variable
/// unset, empty, or unparseable) means **unbounded** — C rsrv imposes
/// no per-client channel count limit in `claim_ciu_action`
/// (`camessage.c:1182-1291`) and no per-channel subscription count
/// limit in `event_add_action` (`camessage.c:1762-1823`); both refuse
/// only on genuine memory exhaustion (`casCreateChannel` /
/// `freeListCalloc` / `db_add_event` returning NULL → `ECA_ALLOCMEM`),
/// never on a fixed count. A default cap diverged from this: a single
/// legitimate client (e.g. `caget` over a 5000-PV database) creating
/// more than the cap on one circuit was refused with `ECA_ALLOCMEM`,
/// producing a hard latency cliff at the cap boundary. A present value
/// clamps to `>= 1` (a zero cap would refuse every request).
fn parse_opt_cap(raw: Option<String>) -> Option<usize> {
    raw.and_then(|s| s.parse::<usize>().ok()).map(|n| n.max(1))
}

/// Optional per-client channel cap (`EPICS_CAS_MAX_CHANNELS`).
/// Default-unbounded (C `claim_ciu_action` parity); opt-in only.
fn max_channels_per_client() -> Option<usize> {
    parse_opt_cap(epics_base_rs::runtime::env::get("EPICS_CAS_MAX_CHANNELS"))
}

/// Optional per-channel subscription cap (`EPICS_CAS_MAX_SUBS_PER_CHAN`).
/// Default-unbounded (C `event_add_action` parity); opt-in only.
fn max_subs_per_channel() -> Option<usize> {
    parse_opt_cap(epics_base_rs::runtime::env::get(
        "EPICS_CAS_MAX_SUBS_PER_CHAN",
    ))
}

#[cfg(test)]
mod cap_parse_tests {
    use super::parse_opt_cap;

    /// C rsrv parity: with the env var unset there is **no** cap, so a
    /// legitimate client can create unboundedly many channels /
    /// subscriptions on one circuit. This is the regression guard for
    /// the 4096-channel (and 100-subscription) latency cliff: the prior
    /// code returned a fixed default (`4096` / `100`) here.
    #[test]
    fn unset_env_is_unbounded() {
        assert_eq!(parse_opt_cap(None), None);
    }

    /// An unparseable / empty value is treated as "no valid cap
    /// configured" → unbounded, consistent with unset.
    #[test]
    fn unparseable_or_empty_is_unbounded() {
        assert_eq!(parse_opt_cap(Some(String::new())), None);
        assert_eq!(parse_opt_cap(Some("not-a-number".into())), None);
    }

    /// An explicit value still opts into a cap and clamps to `>= 1` so a
    /// stray `0` cannot refuse every request.
    #[test]
    fn explicit_value_caps_and_clamps_to_one() {
        assert_eq!(parse_opt_cap(Some("4096".into())), Some(4096));
        assert_eq!(parse_opt_cap(Some("1".into())), Some(1));
        assert_eq!(parse_opt_cap(Some("0".into())), Some(1));
    }
}

/// Forward-DNS verification for `EPICS_CAS_USE_HOST_NAMES=YES`.
///
/// Resolve `claimed` (the client-supplied hostname) to a list of IPs
/// and require `peer` (the actual TCP peer IP) to appear among them.
/// Returns `true` only when a match is found, `false` on resolution
/// failure or mismatch — fail closed.
///
/// Done via `tokio::net::lookup_host` which dispatches to the
/// platform resolver (getaddrinfo), so honours `/etc/hosts`, NIS,
/// LDAP, etc. The DNS lookup is per-HOST_NAME-message so the cost
/// is paid once per CA client connection, not per put / per
/// channel.
async fn host_resolves_to_peer(claimed: &str, peer: std::net::IpAddr) -> bool {
    if claimed.is_empty() {
        return false;
    }
    // `lookup_host` requires a port — a sentinel `:0` is fine since
    // we discard everything except the IP.
    let target = format!("{claimed}:0");
    match tokio::net::lookup_host(target).await {
        Ok(mut iter) => iter.any(|sa| sa.ip() == peer),
        Err(_) => false,
    }
}

/// Per-socket send timeout. Without this, a client that stops
/// reading (frozen GUI, dead viewer holding the socket open) causes
/// every server `write` to block once the kernel send buffer fills,
/// stalling the whole per-client dispatcher task. C rsrv defaults
/// SO_SNDTIMEO to 5 s; we honour the same default and let
/// `EPICS_CAS_SEND_TMO` override.
fn send_timeout() -> Duration {
    epics_base_rs::runtime::env::get("EPICS_CAS_SEND_TMO")
        .and_then(|s| s.parse::<f64>().ok())
        .map(|v| Duration::from_secs_f64(v.max(0.1)))
        .unwrap_or(Duration::from_secs(5))
}

/// Cap on `TlsAcceptor::accept` duration. Without this
/// a peer that completes TCP but stalls during ClientHello holds a
/// connection slot until OS-level keepalive (15s/5s probes) reaps it
/// (~30s); coordinated peers can tie up listener resources. Default
/// 10 s, override via `EPICS_CAS_TLS_HANDSHAKE_TMO`. Floored at 1s.
#[cfg(feature = "experimental-rust-tls")]
fn tls_handshake_timeout() -> Duration {
    epics_base_rs::runtime::env::get("EPICS_CAS_TLS_HANDSHAKE_TMO")
        .and_then(|s| s.parse::<f64>().ok())
        .map(|v| Duration::from_secs_f64(v.max(1.0)))
        .unwrap_or(Duration::from_secs(10))
}

/// Connection lifecycle event broadcast by the TCP listener.
///
/// Marked `#[non_exhaustive]` so subsequent variants (e.g. per-monitor
/// events) can be added without breaking downstream `match` arms.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ServerConnectionEvent {
    /// New client connection accepted.
    Connected(SocketAddr),
    /// Client connection closed.
    Disconnected(SocketAddr),
    /// `CA_PROTO_CREATE_CHAN` succeeded for `pv_name` on `peer`. The
    /// `cid` is the client-supplied channel id from the request — pass
    /// it through to consumers so multiple channels for the same
    /// `(peer, pv_name)` pair don't collapse into one refcount slot.
    /// Used by the CA gateway to drive per-PV `Inactive` → `Active`
    /// transitions (see `ca_gateway::cache::GwPvEntry::add_subscriber`).
    ChannelCreated {
        peer: SocketAddr,
        pv_name: String,
        cid: u32,
    },
    /// `CA_PROTO_CLEAR_CHANNEL` (or implicit teardown) closed a channel
    /// for `pv_name` on `peer`. The `cid` matches the corresponding
    /// [`Self::ChannelCreated`] event one-to-one. Reverse of that event.
    ChannelCleared {
        peer: SocketAddr,
        pv_name: String,
        cid: u32,
    },
    /// `CA_PROTO_EVENT_ADD` accepted; a new subscription is live.
    /// Drives `ServerStats::subscriptions_opened_total` (PR #592's
    /// `caServerSubscriptionCount`).
    ///
    /// `mask` is the validated `DBE_*` event-select mask the client
    /// requested (`1..=255`). The CA gateway consults `mask & DBE_PROPERTY`
    /// to decide, in no-cache mode, whether to spawn the upstream property
    /// monitor for this PV — mirroring C ca-gateway gating `propMonitor()`
    /// on `needPosting() && client_mask == DBE_PROPERTY`
    /// (`gatePv.cc:1749-1752`).
    SubscriptionOpened {
        peer: SocketAddr,
        pv_name: String,
        sub_id: u32,
        mask: u16,
    },
    /// `CA_PROTO_EVENT_CANCEL` or channel teardown closed a
    /// subscription. Drives `ServerStats::subscriptions_closed_total`.
    /// Subtract from the opened counter for the live subscription
    /// count.
    SubscriptionClosed {
        peer: SocketAddr,
        pv_name: String,
        sub_id: u32,
    },
}

use super::LongStringMode;
use crate::protocol::*;
use crate::server::monitor::{FlowControlGate, spawn_monitor_sender};
use epics_base_rs::error::CaResult;
use epics_base_rs::server::access_security::{AccessLevel, AccessSecurityConfig};
use epics_base_rs::server::database::{PvDatabase, PvEntry, parse_pv_name};
use epics_base_rs::server::pv::ProcessVariable;
use epics_base_rs::server::record::RecordInstance;
use epics_base_rs::types::{DbFieldType, EpicsValue, encode_dbr, native_type_for_dbr};

#[derive(Clone)]
enum ChannelTarget {
    SimplePv(Arc<ProcessVariable>),
    RecordField {
        record: Arc<RwLock<RecordInstance>>,
        field: String,
    },
}

/// One async `CA_PROTO_WRITE_NOTIFY` put-callback awaiting record
/// processing completion, owned by [`PutNotifySlot`].
struct InFlightPutNotify {
    /// Cancels the completion task's wait when this put-callback is
    /// superseded by a newer WRITE_NOTIFY on the same channel
    /// (C `dbNotifyCancel`, `camessage.c:1686`).
    abort: tokio::task::AbortHandle,
    /// Owns this put-callback's single client reply. The first of
    /// {completion task, superseding request} to swap this `true`
    /// sends the reply; the loser skips. Closes the race where a put
    /// completes at the exact moment it is superseded — without it the
    /// one ioid would get two replies (a success *and* an
    /// ECA_PUTCBINPROG).
    responded: Arc<AtomicBool>,
    /// Reply shape echoed in the superseded request's ECA_PUTCBINPROG
    /// (C `putNotifyErrorReply(client, &pPutNotify->msg, …)` preserves
    /// the original `m_dataType`/`m_count`/ioid, `camessage.c:1703`).
    ioid: u32,
    dbr_type: u16,
    count: u32,
}

/// Single owner of a channel's in-flight `CA_PROTO_WRITE_NOTIFY`
/// put-callback.
///
/// C `write_notify_action` (`rsrv/camessage.c:1660-1707`) keeps one
/// `pciu->pPutNotify` per channel. A second WRITE_NOTIFY arriving while
/// it is still busy does NOT reject the new request: it waits on
/// `blockSem` for natural completion (up to 60s) and, only if the
/// previous is still running, `dbNotifyCancel`s it and replies
/// ECA_PUTCBINPROG to the *previous* request — then runs the new put.
/// The new request is never refused.
///
/// The async port supersedes the previous put-callback immediately
/// rather than parking the connection's dispatch task on a 60s blocking
/// wait (which would stall every later message on the connection). This
/// matches C's force-cancel branch: a still-in-flight put-callback is
/// aborted and its request gets ECA_PUTCBINPROG, while a put that has
/// already completed naturally keeps its real reply (the `responded`
/// CAS makes the late supersede a no-op). Only `is_notify` puts occupy
/// the slot; a put that completes synchronously within the handler
/// never installs an entry.
#[derive(Clone, Default)]
struct PutNotifySlot {
    inner: Arc<std::sync::Mutex<Option<InFlightPutNotify>>>,
}

impl PutNotifySlot {
    /// Remove and return the channel's current in-flight put-callback
    /// so the caller can supersede it. Leaves the slot empty.
    fn take(&self) -> Option<InFlightPutNotify> {
        self.inner.lock().expect("put-notify slot poisoned").take()
    }

    /// Install a freshly spawned put-callback as the channel's
    /// in-flight one (replacing any stale completed entry the slot
    /// still held).
    fn install(&self, inflight: InFlightPutNotify) {
        *self.inner.lock().expect("put-notify slot poisoned") = Some(inflight);
    }
}

/// Supersede a previously in-flight put-callback, if any: cancel its
/// completion-wait and, when this path wins the response-ownership
/// race, reply ECA_PUTCBINPROG to the superseded request. C
/// `write_notify_action` cancel branch (`camessage.c:1686-1704`). The
/// new WRITE_NOTIFY then proceeds — it is never rejected.
async fn supersede_put_notify<W: AsyncWrite + Unpin + Send + 'static>(
    prev: Option<InFlightPutNotify>,
    writer: &Arc<Mutex<BufWriter<W>>>,
) -> CaResult<()> {
    if let Some(prev) = prev {
        prev.abort.abort();
        if !prev.responded.swap(true, Ordering::AcqRel) {
            send_put_notify_response(
                writer,
                prev.dbr_type,
                prev.count,
                ECA_PUTCBINPROG,
                prev.ioid,
            )
            .await?;
        }
    }
    Ok(())
}

struct ChannelEntry {
    target: ChannelTarget,
    cid: u32,
    /// PV name as the client originally requested it (with any
    /// `.FIELD` suffix). Retained so the `ChannelCleared` lifecycle
    /// event can emit the same name as `ChannelCreated`.
    pv_name: String,
    /// Raw channel-filter JSON suffix the client appended after the
    /// record (epics-base 3.15.7). `None` for ordinary channels;
    /// `Some` when the client requested `REC.{"dbnd":{"d":0.5}}`
    /// etc. Validated by `try_parse_filter_chain` at
    /// `CA_PROTO_CREATE_CHAN` (a bad suffix is rejected with
    /// `CREATE_CH_FAIL` and no `ChannelEntry` is stored), then re-parsed
    /// per delivery via `ChannelEntry::filter_chain` so each subscriber
    /// and the READ path get a fresh stateful chain.
    filter_suffix: Option<String>,
    /// Single owner of this channel's in-flight `CA_PROTO_WRITE_NOTIFY`
    /// put-callback. C `write_notify_action`
    /// (`rsrv/camessage.c:1660-1707`) keeps one `pciu->pPutNotify` per
    /// channel; a second WRITE_NOTIFY supersedes (cancels) the previous
    /// one rather than rejecting the new request. See [`PutNotifySlot`].
    /// `Arc`-backed so the async completion task and a superseding
    /// request share it without re-borrowing `state.channels`.
    put_notify_slot: PutNotifySlot,
    /// long-string boundary conversion this channel applies on every
    /// GET/monitor delivery (and the matching native-type override set
    /// at channel-create time). `DollarChar` = client appended `$` to a
    /// `DBF_STRING` field (C `dbChannel.c:483-507`): delivered as a
    /// `DBR_CHAR[40]` array. `NativeString` = plain access to a
    /// long-string *record* field (lsi/lso VAL & OVAL, printf VAL),
    /// which C `cvt_dbaddr` presents as a scalar `DBF_STRING`. `Plain`
    /// for every other channel.
    long_string_mode: LongStringMode,
}

impl ChannelEntry {
    /// parse a FRESH channel-filter chain from this channel's
    /// stored `.{...}` suffix. A fresh chain per call is REQUIRED:
    /// stateful filters (`dbnd` last-value, `dec` counter, `sync` state)
    /// must not share state across the READ path and each monitor
    /// subscriber, nor across two subscribers on one channel.
    ///
    /// Uses the STRICT `try_parse_filter_chain`. The suffix stored on a
    /// `ChannelEntry` was already validated by the same strict parser at
    /// `CA_PROTO_CREATE_CHAN` (a `ChannelEntry` exists only if its suffix
    /// parsed — a bad suffix is rejected with `CREATE_CH_FAIL` and no
    /// entry is inserted). Parsing is deterministic, so this re-parse
    /// always succeeds; the empty fallback is unreachable, kept only so a
    /// delivery path never panics. This holds the invariant by
    /// construction — delivery never silently downgrades to an unfiltered
    /// stream the way the permissive parser would.
    ///
    /// This is the single owner of filter parsing for every delivery
    /// path — READ / READ_NOTIFY, the monitor initial snapshot, and
    /// monitor updates — so the chain is applied uniformly instead of
    /// only on the record-field `EVENT_ADD` path (the prior gap).
    fn filter_chain(&self) -> epics_base_rs::server::database::filters::FilterChain {
        match self.filter_suffix.as_deref() {
            Some(json) => epics_base_rs::server::database::filters::try_parse_filter_chain(json)
                .unwrap_or_default(),
            None => epics_base_rs::server::database::filters::FilterChain::new(),
        }
    }
}

struct SubscriptionEntry {
    target: ChannelTarget,
    channel_sid: u32,
    sub_id: u32,
    data_type: u16,
    /// Original requested element count from the EVENT_ADD that
    /// installed this subscription. C `event_add_action` stores
    /// `pevext->msg.m_count`; monitor delivery and the
    /// EVENT_CANCEL ack both echo it.
    data_count: u32,
    /// Gate flipped by `reeval_access_rights` when read access is
    /// revoked / restored for `channel_sid`. While `true`, the
    /// producer task drops events at the send step (matches C
    /// `casAccessRightsCB`, `rsrv/camessage.c:1080-1095`, which
    /// calls `db_event_disable` rather than tearing the
    /// subscription down — so an ACF reload that later restores
    /// access can resume the same camonitor).
    denied: Arc<AtomicBool>,
    task: tokio::task::JoinHandle<()>,
    /// mirrors `ChannelEntry::long_string_mode`; stored here so the
    /// access-restore path and `reeval_access_rights` can apply the
    /// same boundary conversion without re-borrowing the channel entry.
    long_string_mode: LongStringMode,
}

struct ClientState {
    channels: HashMap<u32, ChannelEntry>,
    subscriptions: HashMap<u32, SubscriptionEntry>,
    channel_access: HashMap<u32, AccessLevel>,
    /// per-SID write-trap mask of the ACF rule that resolved
    /// the channel's access level. Kept parallel to `channel_access`
    /// (same key set, inserted/removed together) because the trap
    /// flag has no `CA_PROTO_ACCESS_RIGHTS` wire representation — it
    /// is consumed only by TRAPWRITE put-logging dispatch, never
    /// diffed for access-rights transition frames. Mirrors C
    /// `pasgclient->trapMask` (`asLibRoutines.c:1048`).
    channel_trap: HashMap<u32, bool>,
    next_sid: AtomicU32,
    /// Recycled SIDs from channels destroyed via CLEAR_CHANNEL —
    /// without recycling, `next_sid` would wrap after 2³² channel
    /// creations and start handing out SIDs that collide with live
    /// channels. epics-base `rsrv/camessage.c` uses
    /// `freeListItemPvt` for the same reason. We use a Vec stack
    /// (LIFO) so the most-recently-freed SID is reused first —
    /// keeps the active set's SIDs clustered near the low end.
    free_sids: Vec<u32>,
    hostname: String,
    username: String,
    /// Authentication method for ACF `METHOD()` clause matching.
    /// `"x509"` for mTLS-authenticated peers (epics-base PR #641);
    /// `"ca"` (or empty for backwards compat) for plaintext peers.
    /// ACF rules without a `METHOD()` clause ignore this field
    /// — the legacy `check_access_asl()` codepath continues to work.
    auth_method: String,
    /// Authority for ACF `AUTHORITY()` clause matching. mTLS peers
    /// carry their cert's *issuer* DN here so rules like
    /// `RULE(1, WRITE) { METHOD("x509") AUTHORITY("CN=ops-ca, …") }`
    /// can pin write access to certs minted by a specific CA.
    /// Empty for plaintext peers.
    auth_authority: String,
    acf: Arc<tokio::sync::RwLock<Option<AccessSecurityConfig>>>,
    /// record database, for resolving ACF `INP*` links to live
    /// values when evaluating CALC-gated rules in `compute_access`.
    db: Arc<PvDatabase>,
    tcp_port: u16,
    client_minor_version: u16,
    flow_control: Arc<FlowControlGate>,
    /// One-shot flag — set when channels.len() crosses 90% of the
    /// per-client cap. Prevents log spam on every subsequent
    /// CREATE_CHAN once the warning has fired.
    channel_limit_warned: bool,
    /// Peer address as a string, retained for audit events.
    peer: String,
    /// Optional audit logger. When None the audit hot path is a single
    /// branch test and no allocation.
    audit: Option<crate::audit::AuditLogger>,
    /// Optional per-client token bucket. None disables rate limiting.
    rate_limiter: Option<crate::server::rate_limit::RateLimiter>,
    /// Consecutive denied messages — disconnect when this exceeds the
    /// configured strike threshold.
    rate_limit_strikes: u32,
    rate_limit_strike_threshold: u32,
    /// Capability-token verifier shared across all clients on this
    /// listener. When set, CLIENT_NAME payloads beginning with `cap:`
    /// are verified before the resolved subject is used as the ACF
    /// username.
    #[cfg(feature = "cap-tokens")]
    cap_token_verifier: Option<Arc<crate::cap_token::TokenVerifier>>,
    /// TLS channel binding (SHA-256 of the peer's leaf certificate DER)
    /// for this connection. `Some(..)` only when the peer connected
    /// over mTLS and presented a client certificate; `None` for
    /// plaintext circuits. A cap-token presented over a plaintext
    /// circuit (`None`) is rejected by `TokenVerifier::verify` —
    /// mTLS-gating, so a stolen token cannot be replayed off-channel.
    #[cfg(feature = "cap-tokens")]
    tls_channel_binding: Option<crate::cap_token::ChannelBinding>,
    /// Pending WRITE_NOTIFY completion tasks. Each entry is the channel
    /// `sid`-tagged AbortHandle of a task awaiting `put_notify_tx` for
    /// an async record write. Aborted on connection drop so a stuck
    /// async device doesn't leak the task forever, and also aborted
    /// when the owning channel is freed via `CA_PROTO_CLEAR_CHANNEL`
    /// (C parity: `clear_channel_reply` calls `rsrvFreePutNotify`
    /// per-channel — `camessage.c:1889`). The sid tag lets us drain
    /// only the channel-scoped tasks on CLEAR_CHANNEL without
    /// disturbing other channels' in-flight WRITE_NOTIFYs.
    write_notify_tasks: Vec<(u32, tokio::task::AbortHandle)>,
    /// Server-wide stats handle, cloned into each monitor task so the
    /// `subscription_events_posted` / `subscription_events_processed`
    /// counters (PCAS `caServer` parity, feeding the gateway's
    /// `serverPostRate` / `serverEventRate`) advance from the delivery
    /// layer. `None` in unit tests that drive the TCP path without a
    /// full `ServerStats` wired up.
    stats: Option<Arc<super::ca_server::ServerStats>>,
}

impl ClientState {
    fn new(
        acf: Arc<tokio::sync::RwLock<Option<AccessSecurityConfig>>>,
        tcp_port: u16,
        db: Arc<PvDatabase>,
    ) -> Self {
        Self {
            channels: HashMap::new(),
            subscriptions: HashMap::new(),
            channel_access: HashMap::new(),
            channel_trap: HashMap::new(),
            next_sid: AtomicU32::new(1),
            free_sids: Vec::new(),
            hostname: String::new(),
            username: String::new(),
            auth_method: String::new(),
            auth_authority: String::new(),
            acf,
            db,
            tcp_port,
            client_minor_version: 0,
            flow_control: Arc::new(FlowControlGate::default()),
            channel_limit_warned: false,
            peer: String::new(),
            audit: None,
            rate_limiter: None,
            rate_limit_strikes: 0,
            rate_limit_strike_threshold: 0,
            #[cfg(feature = "cap-tokens")]
            cap_token_verifier: None,
            #[cfg(feature = "cap-tokens")]
            tls_channel_binding: None,
            write_notify_tasks: Vec::new(),
            stats: None,
        }
    }

    async fn audit(&self, event: &str, pv: &str, value: &str, result: &str) {
        if let Some(ref logger) = self.audit {
            logger
                .log(crate::audit::AuditEvent {
                    event,
                    peer: &self.peer,
                    user: &self.username,
                    host: &self.hostname,
                    pv,
                    value,
                    result,
                })
                .await;
        }
    }

    fn alloc_sid(&mut self) -> u32 {
        // prefer recycled SIDs from CLEAR_CHANNEL'd channels.
        // Falls back to monotonic counter only when the free list is
        // empty, which prevents wraparound collisions on long-uptime
        // high-churn servers (epics-base rsrv `freeListItemPvt`
        // parity).
        if let Some(sid) = self.free_sids.pop() {
            return sid;
        }
        self.next_sid.fetch_add(1, Ordering::Relaxed)
    }

    /// Return a SID to the free list when its channel is destroyed.
    fn release_sid(&mut self, sid: u32) {
        self.free_sids.push(sid);
    }

    /// Return the type-state-wrapped access token for a
    /// SID. Op handlers MUST consult this — direct reads of the
    /// underlying `channel_access` HashMap bypass the typed gate
    /// and recreate the missed-path defects fixed in rounds 38-39.
    /// Missing SIDs map to a "denied" token so a corrupted
    /// channel-table state can never silently grant access.
    fn lookup_access(&self, sid: u32) -> crate::server::access_token::CaAccessChecked {
        use crate::server::access_token::CaAccessChecked;
        match self.channel_access.get(&sid).copied() {
            Some(level) => {
                // the trap mask is kept in a parallel map
                // populated alongside `channel_access`. A missing
                // entry means the rule carried no trap option.
                let rule_was_trap = self.channel_trap.get(&sid).copied().unwrap_or(false);
                CaAccessChecked::from_level(level, rule_was_trap)
            }
            None => CaAccessChecked::denied(),
        }
    }

    /// Compute access rights bits for a channel target, together with
    /// the write-trap mask of the ACF rule that resolved the level
    ///. The trap flag is `false` for `SimplePv`/`RecordField`
    /// targets whose access was not resolved through a `TRAPWRITE`
    /// rule — including the no-ACF permissive fallback.
    /// resolve an ASG's `INP*` links to live numeric values
    /// (A..U) from the record database. `None` when a declared link is
    /// unresolvable / bad — the CALC-gated rule then fails closed.
    /// Caller must NOT hold a record read-guard that a link could point
    /// back to (would re-read the same lock).
    async fn calc_inputs(
        &self,
        cfg: &AccessSecurityConfig,
        asg_name: &str,
    ) -> Option<epics_base_rs::calc::NumericInputs> {
        let group = cfg.asg.get(asg_name).or_else(|| cfg.asg.get("DEFAULT"))?;
        let mut inputs = epics_base_rs::calc::NumericInputs::new();
        for inp in &group.inp {
            let idx = inp.index as usize;
            if idx >= epics_base_rs::calc::CALC_NARGS {
                continue;
            }
            let (base, field) = parse_pv_name(&inp.link);
            let field = if field.is_empty() { "VAL" } else { field };
            let rec = self.db.get_record(base).await?;
            let inst = rec.read().await;
            match inst.resolve_field(field).and_then(|v| v.to_f64()) {
                Some(v) => inputs.vars[idx] = v,
                None => return None,
            }
        }
        Some(inputs)
    }

    /// evaluate `cfg`'s rules for `asg_name`, with CALC clauses
    /// gated against the resolved `INP*` values.
    async fn access_for_asg(
        &self,
        cfg: &AccessSecurityConfig,
        asg_name: &str,
        asl: u8,
    ) -> (AccessLevel, bool) {
        let calc_inputs = self.calc_inputs(cfg, asg_name).await;
        let calc_ok = |expr: &str| -> bool {
            match calc_inputs {
                Some(ref i) => match epics_base_rs::calc::compile(expr) {
                    Ok(c) => epics_base_rs::calc::eval(&c, &mut i.clone())
                        .map(|r| r != 0.0)
                        .unwrap_or(false),
                    Err(_) => false,
                },
                None => false,
            }
        };
        cfg.compute_for_name(
            asg_name,
            &self.hostname,
            &self.username,
            &[],
            asl,
            &self.auth_method,
            &self.auth_authority,
            &calc_ok,
        )
    }

    async fn compute_access(&self, target: &ChannelTarget) -> (u32, bool) {
        match target {
            ChannelTarget::SimplePv(pv) => {
                // a gateway shadow PV carries an access
                // hook routing the decision through the gateway's own
                // ACF (`.pvlist` ASG + `AccessConfig::can_read/write`)
                // for this downstream `(user, host)`. When present it
                // is authoritative for this PV — the server's own ACF
                // never saw the `.pvlist` ASG, so consulting `self.acf`
                // with a hardcoded "DEFAULT" would mis-report read
                // access. The gateway audits/traps writes in its own
                // write hook, so no TRAPWRITE rule resolves here.
                if let Some(hook) = pv.access_hook() {
                    let decision = hook(&self.username, &self.hostname);
                    let bits = match (decision.read, decision.write) {
                        (_, true) => 3,
                        (true, false) => 1,
                        (false, false) => 0,
                    };
                    return (bits, false);
                }
                let guard = self.acf.read().await;
                if let Some(ref acf_cfg) = *guard {
                    // Simple PVs have no per-record ASL field; treat
                    // them as ASL=0 so the most-restrictive rule
                    // applies. Matches the C IOC's behaviour for
                    // names that never went through `dbAddMember`.
                    // PR #641: pass auth method/authority so
                    // METHOD("x509") / AUTHORITY(<issuer>) rules
                    // can gate mTLS-authenticated peers. CALC
                    // rules are evaluated against resolved INP* links.
                    let (level, rule_was_trap) = self.access_for_asg(acf_cfg, "DEFAULT", 0).await;
                    let bits = match level {
                        AccessLevel::ReadWrite => 3,
                        AccessLevel::Read => 1,
                        AccessLevel::NoAccess => 0,
                    };
                    (bits, rule_was_trap)
                } else {
                    // No ACF attached: permissive ReadWrite, no rule
                    // resolved access, so no TRAPWRITE applies.
                    (3, false)
                }
            }
            ChannelTarget::RecordField { record, field: f } => {
                // extract is_ro/asg/asl and DROP the record
                // read-guard before resolving ACF INP* links, so a CALC
                // input pointing back at this record can't re-acquire the
                // same lock.
                let (is_ro, asg, asl) = {
                    let instance = record.read().await;
                    let is_ro = instance
                        .record
                        .field_list()
                        .iter()
                        .find(|fd| fd.name == f.as_str())
                        .map(|fd| fd.read_only)
                        .unwrap_or(false);
                    (is_ro, instance.common.asg.clone(), instance.common.asl)
                };
                // Read-only field-ness must AND
                // with ACF, never replace it. Pre-fix the read-only
                // branch returned `Read`(1) unconditionally — a
                // peer whose ACF resolved to `NoAccess` could still
                // READ / EVENT_ADD on every read-only field because
                // the cached access_rights skipped the ACF check
                // entirely. Now ACF runs first; the read-only flag
                // only strips the WRITE bit from the result.
                let guard = self.acf.read().await;
                let (acf_level, rule_was_trap) = if let Some(ref acf_cfg) = *guard {
                    // Thread the per-record ASL so
                    // `RULE(N, …)` gates correctly. PR #641: method/
                    // authority for mTLS rules. CALC rules are
                    // evaluated against resolved INP* links.
                    self.access_for_asg(acf_cfg, &asg, asl).await
                } else {
                    (AccessLevel::ReadWrite, false)
                };
                let bits = match (acf_level, is_ro) {
                    (AccessLevel::NoAccess, _) => 0,
                    (AccessLevel::Read, _) => 1,
                    (AccessLevel::ReadWrite, true) => 1,
                    (AccessLevel::ReadWrite, false) => 3,
                };
                // The trap mask reflects the rule that granted access;
                // a read-only field stripping the WRITE bit does not
                // change which rule matched.
                (bits, rule_was_trap)
            }
        }
    }
}

/// Run the TCP listener for CA connections.
/// Tries to bind to the configured port first; falls back to an ephemeral port
/// (port 0) if the configured port is already in use.
///
/// Notifies `beacon_reset` on each client connect/disconnect so the beacon
/// emitter restarts its fast beacon cycle. This is a Rust enhancement, NOT
/// C parity: C `rsrv` resets the beacon interval only on `ctlPause`, never
/// on connect/disconnect. The extra fast beacons are benign and help
/// clients notice server state changes promptly.
#[allow(clippy::too_many_arguments)]
pub async fn run_tcp_listener(
    db: Arc<PvDatabase>,
    port: u16,
    acf: Arc<tokio::sync::RwLock<Option<AccessSecurityConfig>>>,
    acf_reload_tx: broadcast::Sender<()>,
    tcp_port_tx: tokio::sync::oneshot::Sender<u16>,
    beacon_reset: std::sync::Arc<tokio::sync::Notify>,
    conn_events: Option<broadcast::Sender<ServerConnectionEvent>>,
    audit: Option<crate::audit::AuditLogger>,
    drain: Arc<std::sync::atomic::AtomicBool>,
    // PR #592 dbServerStats: per-connection byte counters feed the
    // `casr` iocsh command's `bytes in=… out=…` line. Optional so unit
    // tests of the TCP path don't need a full ServerStats wired up.
    stats: Option<Arc<super::ca_server::ServerStats>>,
    #[cfg(feature = "experimental-rust-tls")] tls: Option<
        Arc<std::sync::RwLock<Arc<tokio_rustls::rustls::ServerConfig>>>,
    >,
    #[cfg(feature = "cap-tokens")] cap_token_verifier: Option<Arc<crate::cap_token::TokenVerifier>>,
) -> CaResult<()> {
    // honour every interface in `EPICS_CAS_INTF_ADDR_LIST`,
    // not just the first. C `rsrv_init` (caservertask.c:603-712) iterates
    // `casIntfAddrList` and spawns one `CAS-TCP` accept thread per
    // entry, all bound to the same TCP port. Binding to a *specific*
    // interface IP (vs `INADDR_ANY`) and binding to a *different*
    // specific IP on the same port is allowed by POSIX; only two
    // 0.0.0.0 binds collide. Empty list → single `0.0.0.0` listener
    // (default), preserving the current single-NIC behaviour.
    //
    // First successful bind decides `actual_port` (honouring the
    // existing AddrInUse → ephemeral-fallback path). All subsequent
    // binds must use that same port; if a per-interface bind fails
    // it is logged and skipped (matches C `cleanup:` / `continue;` in
    // `caservertask.c:744-749`, which frees the conf and proceeds).
    let intf_addrs: Vec<std::net::Ipv4Addr> = {
        let cfg = super::addr_list::from_env()?;
        if cfg.intf_addrs.is_empty() {
            vec![std::net::Ipv4Addr::UNSPECIFIED]
        } else {
            cfg.intf_addrs
        }
    };

    let mut listeners: Vec<(TcpListener, std::net::Ipv4Addr)> = Vec::new();
    let mut actual_port: Option<u16> = None;
    for ip in &intf_addrs {
        let target_port = actual_port.unwrap_or(port);
        let bind_ip = std::net::IpAddr::V4(*ip);
        let listener = match TcpListener::bind((bind_ip, target_port)).await {
            Ok(l) => l,
            Err(e) if e.kind() == std::io::ErrorKind::AddrInUse && actual_port.is_none() => {
                // Only fall back to ephemeral on the FIRST bind. Once
                // a port has been chosen all subsequent interfaces
                // MUST share it — otherwise a multi-NIC server would
                // advertise a different TCP port per interface in its
                // SEARCH replies (which already carry a single port).
                TcpListener::bind((bind_ip, 0)).await?
            }
            Err(e) => {
                if actual_port.is_some() {
                    // Subsequent bind on chosen port failed: log and
                    // skip (C parity, `cleanup:` path frees + continues).
                    tracing::warn!(
                        target: "epics_ca_rs::server::tcp",
                        intf = %ip,
                        port = target_port,
                        error = %e,
                        "TCP listener bind failed on this interface — skipping"
                    );
                    continue;
                }
                return Err(e.into());
            }
        };
        let chosen = listener.local_addr()?.port();
        if actual_port.is_none() {
            actual_port = Some(chosen);
        }
        listeners.push((listener, *ip));
    }

    let actual_port = match actual_port {
        Some(p) => p,
        None => {
            // C `cantProceed("CAS: No TCP server started\n")` at
            // `caservertask.c:752`. Every configured interface failed
            // to bind — there's nothing to serve.
            return Err(epics_base_rs::error::CaError::Io(std::io::Error::new(
                std::io::ErrorKind::AddrNotAvailable,
                "CAS: No TCP server started — all configured interfaces failed to bind",
            )));
        }
    };
    let _ = tcp_port_tx.send(actual_port);

    // One accept-loop task per bound interface. When the parent
    // `run_tcp_listener` future is dropped (CaServer shutdown via
    // `tcp_abort.abort()`), this JoinSet is dropped which aborts all
    // accept loops as a unit. First task to error wins; the rest
    // are aborted via JoinSet::Drop.
    let mut accept_tasks: tokio::task::JoinSet<CaResult<()>> = tokio::task::JoinSet::new();

    // ASG-field-change forwarder. C
    // `database/src/ioc/as/asDbLib.c:107-110,144` `asSpcAsCallback`
    // is wired by `asInitCommon` as the per-record `ASG` field
    // special callback and re-evaluates access rights for every
    // affected client on `dbPut record.ASG NEW_ASG`. Re-using the
    // existing `acf_reload_tx` broadcast is coarser than libca's
    // per-client dispatch but the downstream `oldaccess != access`
    // filter in `reeval_access_rights` keeps wire traffic bounded.
    //
    // the forwarder is spawned INTO the `accept_tasks`
    // JoinSet so it's cancelled together with the accept loops on
    // `run_tcp_listener` cancellation. Pre-fix Rust did
    // `tokio::spawn(...)` and dropped the JoinHandle, leaving the
    // task running forever (its `recv()` loop only exits on
    // `RecvError::Closed`, which the process-lifetime `OnceLock`
    // Sender can never raise). Long-running processes that restart
    // their CA server (test fixtures, fault-tolerant supervisors)
    // accumulated one zombie forwarder per restart cycle, each
    // holding a stale `acf_reload_tx_t` clone.
    {
        let mut asg_rx = epics_base_rs::server::access_security::subscribe_asg_changes();
        let acf_reload_tx_t = acf_reload_tx.clone();
        accept_tasks.spawn(async move {
            loop {
                match asg_rx.recv().await {
                    Ok(()) => {
                        let _ = acf_reload_tx_t.send(());
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
                        // Coalesce lagged events into one re-eval; the
                        // downstream `oldaccess != access` filter
                        // makes a single re-eval sufficient.
                        tracing::debug!(
                            target: "epics_ca_rs::server::tcp",
                            lagged = n,
                            "ASG-change notifier lagged — issuing one coalesced re-eval"
                        );
                        let _ = acf_reload_tx_t.send(());
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                }
            }
            Ok(())
        });
    }

    for (listener, intf) in listeners {
        let db_t = db.clone();
        let acf_t = acf.clone();
        let acf_reload_tx_t = acf_reload_tx.clone();
        let beacon_reset_t = beacon_reset.clone();
        let conn_events_t = conn_events.clone();
        let audit_t = audit.clone();
        let drain_t = drain.clone();
        let stats_t = stats.clone();
        #[cfg(feature = "experimental-rust-tls")]
        let tls_t = tls.clone();
        #[cfg(feature = "cap-tokens")]
        let cap_token_verifier_t = cap_token_verifier.clone();
        accept_tasks.spawn(async move {
            accept_loop(
                listener,
                intf,
                actual_port,
                db_t,
                acf_t,
                acf_reload_tx_t,
                beacon_reset_t,
                conn_events_t,
                audit_t,
                drain_t,
                stats_t,
                #[cfg(feature = "experimental-rust-tls")]
                tls_t,
                #[cfg(feature = "cap-tokens")]
                cap_token_verifier_t,
            )
            .await
        });
    }

    // Wait for the first error (or for all loops to exit cleanly via
    // drain). On error, JoinSet::Drop aborts the surviving loops.
    while let Some(res) = accept_tasks.join_next().await {
        match res {
            Ok(Ok(())) => continue,
            Ok(Err(e)) => return Err(e),
            Err(join_err) if join_err.is_cancelled() => continue,
            Err(join_err) => {
                return Err(epics_base_rs::error::CaError::Io(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    join_err.to_string(),
                )));
            }
        }
    }
    Ok(())
}

/// Per-interface accept loop. Owned by `run_tcp_listener` via a
/// `JoinSet` — one task per `EPICS_CAS_INTF_ADDR_LIST` entry. Drains
/// when the shared `drain` flag is set; otherwise spawns a
/// `handle_client` task into the local `conn_tasks` `JoinSet` per
/// accepted connection.
///
/// `intf` is the bound interface IP; recorded on accept-error logs so
/// multi-NIC hosts can tell which listener saw the failure. The
/// `actual_port` parameter is the TCP port shared across all
/// listeners (decided in `run_tcp_listener`).
#[allow(clippy::too_many_arguments)]
async fn accept_loop(
    listener: TcpListener,
    intf: std::net::Ipv4Addr,
    actual_port: u16,
    db: Arc<PvDatabase>,
    acf: Arc<tokio::sync::RwLock<Option<AccessSecurityConfig>>>,
    acf_reload_tx: broadcast::Sender<()>,
    beacon_reset: std::sync::Arc<tokio::sync::Notify>,
    conn_events: Option<broadcast::Sender<ServerConnectionEvent>>,
    audit: Option<crate::audit::AuditLogger>,
    drain: Arc<std::sync::atomic::AtomicBool>,
    stats: Option<Arc<super::ca_server::ServerStats>>,
    #[cfg(feature = "experimental-rust-tls")] tls: Option<
        Arc<std::sync::RwLock<Arc<tokio_rustls::rustls::ServerConfig>>>,
    >,
    #[cfg(feature = "cap-tokens")] cap_token_verifier: Option<Arc<crate::cap_token::TokenVerifier>>,
) -> CaResult<()> {
    // track per-connection tasks in a JoinSet so they're
    // aborted as a unit when this accept-loop future is dropped (e.g.
    // CaServer shutdown via tcp_abort.abort()). Without this, every
    // per-conn task ran detached and lingered until its internal
    // idle/op timeout. The select! arm on `conn_tasks.join_next()`
    // also reaps completed tasks so the set doesn't accumulate
    // finished JoinHandles.
    let mut conn_tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();

    loop {
        // Drain mode: stop accepting new connections. Existing
        // connections continue to be served by their own tasks; the
        // CaServer::run() loop coordinates the grace period and the
        // ultimate exit.
        if drain.load(std::sync::atomic::Ordering::Acquire) {
            tracing::info!(intf = %intf, "TCP listener: drain mode set, exiting accept loop");
            return Ok(());
        }
        let (stream, peer) = tokio::select! {
            biased;
            res = listener.accept() => res?,
            // Drain finished connection tasks. Returns None when the
            // set is empty — that branch resolves immediately, but
            // `biased` makes the listener arm preferred so we never
            // starve incoming accepts.
            Some(_) = conn_tasks.join_next() => continue,
        };
        // Reap finished connection tasks promptly. The select! arm on
        // `conn_tasks.join_next()` only fires when `listener.accept()`
        // is Pending, but `biased` makes the accept arm strictly
        // preferred — so under a sustained connect storm completed
        // `JoinHandle`s would accumulate in the set unbounded. A
        // non-blocking `try_join_next` drain after every accept caps
        // the set at the count of genuinely in-flight connections.
        while conn_tasks.try_join_next().is_some() {}
        if drain.load(std::sync::atomic::Ordering::Acquire) {
            tracing::info!(peer = %peer, "drain mode: rejecting new connection");
            drop(stream);
            continue;
        }
        tracing::info!(peer = %peer, intf = %intf, "CA client connected");
        metrics::counter!("ca_server_accepts_total").increment(1);
        metrics::gauge!("ca_server_clients_active").increment(1.0);
        let db = db.clone();
        let acf = acf.clone();
        let beacon_reset = beacon_reset.clone();
        // Rust enhancement (NOT C parity): C `rsrv` never resets the
        // beacon interval on connect — only on `ctlPause`. We restart
        // the fast beacon cycle here so clients notice the new server
        // state quickly; the extra beacons are benign.
        beacon_reset.notify_one();
        if let Some(tx) = &conn_events {
            let _ = tx.send(ServerConnectionEvent::Connected(peer));
        }
        let conn_events = conn_events.clone();
        let acf_reload_rx = acf_reload_tx.subscribe();
        let audit = audit.clone();
        let stats_for_client = stats.clone();
        // Read the latest server config under the RwLock so a
        // concurrent reload_tls() takes effect for the *next* accept
        // without restarting the listener. Cheap read lock — only
        // contended against rare reload write locks.
        #[cfg(feature = "experimental-rust-tls")]
        let tls_acceptor = tls.as_ref().and_then(|slot| {
            slot.read()
                .ok()
                .map(|guard| tokio_rustls::TlsAcceptor::from(guard.clone()))
        });

        // Enable OS-level TCP keepalive on accepted socket so half-open
        // connections (e.g. NAT timeout, gateway down) are detected within
        // ~30s. Mirrors client-side keepalive in client/transport.rs.
        {
            let sock = socket2::SockRef::from(&stream);
            let keepalive = socket2::TcpKeepalive::new()
                .with_time(Duration::from_secs(15))
                .with_interval(Duration::from_secs(5));
            let _ = sock.set_keepalive(true);
            let _ = sock.set_tcp_keepalive(&keepalive);
            // SO_SNDTIMEO is set as a defence-in-depth (matches C
            // rsrv default 5s, configurable via EPICS_CAS_SEND_TMO),
            // but on a non-blocking tokio socket the kernel does NOT
            // apply it — a stuck client where the kernel send buffer
            // fills would still leave `poll_write` Pending forever.
            // The actual stall guard is the `tokio::time::timeout`
            // wrapping `dispatch_message` in `handle_client`'s read
            // loop (search for "send_timeout()" below).
            let _ = sock.set_write_timeout(Some(send_timeout()));
        }
        let _ = stream.set_nodelay(true);

        #[cfg(feature = "cap-tokens")]
        let cap_token_verifier_for_client = cap_token_verifier.clone();
        conn_tasks.spawn(async move {
            // TLS dispatch: when configured, wrap the accepted TCP
            // stream in a TlsAcceptor handshake. The client cert (if
            // any) is harvested afterwards for mTLS identity.
            let result: CaResult<()> = {
                #[cfg(feature = "experimental-rust-tls")]
                {
                    if let Some(acceptor) = tls_acceptor {
                        // cap the TLS handshake. A peer that
                        // completes TCP but stalls during ClientHello
                        // would otherwise hold a connection slot until
                        // OS keepalive reaps it (~30s).
                        let hs =
                            tokio::time::timeout(tls_handshake_timeout(), acceptor.accept(stream))
                                .await;
                        match hs {
                            Err(_) => {
                                tracing::warn!(peer = %peer,
                                    timeout = ?tls_handshake_timeout(),
                                    "TLS handshake timed out");
                                Err(epics_base_rs::error::CaError::Protocol(
                                    "TLS handshake timeout".into(),
                                ))
                            }
                            Ok(Ok(tls_stream)) => {
                                // Extract verified peer identity + issuer
                                // from the client certificate, if presented.
                                let leaf_cert = tls_stream
                                    .get_ref()
                                    .1
                                    .peer_certificates()
                                    .and_then(|chain| chain.first().cloned());
                                let (identity, authority) = leaf_cert
                                    .as_ref()
                                    .map(|cert| {
                                        (
                                            crate::tls::identity_from_cert(cert),
                                            crate::tls::issuer_from_cert(cert),
                                        )
                                    })
                                    .map(|(id, auth)| (Some(id), auth))
                                    .unwrap_or((None, None));
                                // TLS channel binding: SHA-256 of the
                                // peer's leaf certificate DER. Threaded
                                // into `handle_client` so cap-token
                                // verification is bound to this circuit.
                                #[cfg(feature = "cap-tokens")]
                                let tls_channel_binding = leaf_cert.as_ref().map(|cert| {
                                    crate::cap_token::ChannelBinding::from_peer_cert_der(
                                        cert.as_ref(),
                                    )
                                });
                                if let Some(ref id) = identity {
                                    tracing::info!(
                                        peer = %peer,
                                        identity = %id,
                                        authority = authority.as_deref().unwrap_or("<none>"),
                                        "mTLS identity verified"
                                    );
                                }
                                handle_client(
                                    tls_stream,
                                    peer,
                                    db,
                                    acf,
                                    acf_reload_rx,
                                    actual_port,
                                    identity,
                                    authority,
                                    audit,
                                    conn_events.clone(),
                                    stats_for_client.clone(),
                                    #[cfg(feature = "cap-tokens")]
                                    cap_token_verifier_for_client.clone(),
                                    #[cfg(feature = "cap-tokens")]
                                    tls_channel_binding,
                                )
                                .await
                            }
                            Ok(Err(e)) => {
                                tracing::warn!(peer = %peer, error = %e,
                                    "TLS handshake failed");
                                Err(epics_base_rs::error::CaError::Io(e))
                            }
                        }
                    } else {
                        handle_client(
                            stream,
                            peer,
                            db,
                            acf,
                            acf_reload_rx,
                            actual_port,
                            None,
                            None,
                            audit,
                            conn_events.clone(),
                            stats_for_client.clone(),
                            #[cfg(feature = "cap-tokens")]
                            cap_token_verifier_for_client.clone(),
                            // Plaintext circuit: no channel binding.
                            #[cfg(feature = "cap-tokens")]
                            None,
                        )
                        .await
                    }
                }
                #[cfg(not(feature = "experimental-rust-tls"))]
                {
                    handle_client(
                        stream,
                        peer,
                        db,
                        acf,
                        acf_reload_rx,
                        actual_port,
                        None,
                        None,
                        audit,
                        conn_events.clone(),
                        stats_for_client.clone(),
                        #[cfg(feature = "cap-tokens")]
                        cap_token_verifier_for_client.clone(),
                        // No TLS compiled in: never a channel binding.
                        #[cfg(feature = "cap-tokens")]
                        None,
                    )
                    .await
                }
            };
            // Rust enhancement (NOT C parity): C `rsrv` never resets
            // the beacon interval on disconnect — only on `ctlPause`.
            // Restarting the fast beacon cycle here is a deliberate,
            // benign addition.
            beacon_reset.notify_one();
            if let Some(tx) = &conn_events {
                let _ = tx.send(ServerConnectionEvent::Disconnected(peer));
            }
            metrics::gauge!("ca_server_clients_active").decrement(1.0);
            metrics::counter!("ca_server_disconnects_total").increment(1);
            if let Err(e) = result {
                // Suppress normal disconnection errors (client closed connection)
                let is_disconnect = matches!(
                    e,
                    epics_base_rs::error::CaError::Io(ref io) if matches!(
                        io.kind(),
                        std::io::ErrorKind::ConnectionReset
                            | std::io::ErrorKind::BrokenPipe
                            | std::io::ErrorKind::UnexpectedEof
                    )
                );
                if is_disconnect {
                    tracing::debug!(peer = %peer, "client disconnected");
                } else {
                    tracing::warn!(peer = %peer, error = %e, "client handler error");
                }
            } else {
                tracing::debug!(peer = %peer, "client disconnected cleanly");
            }
        });
    }
}

/// Handle one CA client over the supplied stream.
///
/// `initial_hostname` is the verified peer identity from the TLS
/// handshake (mTLS only). When `Some`, it takes precedence over
/// `peer.ip()` for the `state.hostname` ACF key — the
/// cryptographically authenticated identity is always more
/// trustworthy than the network address.
#[allow(clippy::too_many_arguments)]
async fn handle_client<S>(
    stream: S,
    peer: SocketAddr,
    db: Arc<PvDatabase>,
    acf: Arc<tokio::sync::RwLock<Option<AccessSecurityConfig>>>,
    mut acf_reload_rx: broadcast::Receiver<()>,
    tcp_port: u16,
    initial_hostname: Option<String>,
    // PR #641 — mTLS issuer DN of the peer's cert. `Some(...)` only
    // when the peer was authenticated via mTLS; gets paired with
    // `auth_method = "x509"` on the ClientState so ACF
    // METHOD()/AUTHORITY() rules can gate by issuer.
    tls_authority: Option<String>,
    audit: Option<crate::audit::AuditLogger>,
    conn_events: Option<broadcast::Sender<ServerConnectionEvent>>,
    // PR #592 dbServerStats: bytes_in/bytes_out counters. Incremented
    // post-read (per accepted UDP/TCP buffer) and at each BufWriter
    // flush (by inspecting `BufWriter::buffer().len()` before flush).
    // `None` skips all counter bookkeeping — used by the unit-test
    // dispatch fixtures that don't spin up a full CaServer.
    stats: Option<Arc<super::ca_server::ServerStats>>,
    #[cfg(feature = "cap-tokens")] cap_token_verifier: Option<Arc<crate::cap_token::TokenVerifier>>,
    // TLS channel binding (SHA-256 of the peer's leaf cert DER),
    // computed at the mTLS accept site. `None` for plaintext peers —
    // a cap-token presented on a `None` circuit is rejected by
    // `TokenVerifier::verify`, so the token is cryptographically
    // bound to the TLS channel it was issued for.
    #[cfg(feature = "cap-tokens")] tls_channel_binding: Option<crate::cap_token::ChannelBinding>,
) -> CaResult<()>
where
    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
    let (reader, writer) = tokio::io::split(stream);
    // Bigger BufWriter so a 100-PV batched response burst (~3 KB) fits
    // without auto-flushing mid-batch. The dispatch hot-path no longer
    // calls `flush()` per message — `handle_client` flushes once per
    // outer read iteration after the inner message-drain loop, which
    // turns N small TCP writes into one. Default 8 KB was hit at ~330
    // responses; 64 KB covers the common bulk_caget(100) case with
    // headroom for follow-on monitor events queued in the same tick.
    let writer = Arc::new(Mutex::new(BufWriter::with_capacity(64 * 1024, writer)));
    let mut state = ClientState::new(acf, tcp_port, db.clone());
    state.stats = stats.clone();
    #[cfg(feature = "cap-tokens")]
    {
        state.cap_token_verifier = cap_token_verifier;
        state.tls_channel_binding = tls_channel_binding;
    }
    // Default hostname: verified TLS identity if present, otherwise the
    // peer IP. Matches C rsrv default with EPICS_CAS_USE_HOST_NAMES=NO,
    // upgraded transparently when mTLS is in effect.
    state.hostname = initial_hostname.unwrap_or_else(|| peer.ip().to_string());
    // PR #641: surface the mTLS authentication context to the ACF
    // check. Plaintext peers stay with empty fields — every legacy
    // rule (no METHOD/AUTHORITY clause) ignores them.
    if let Some(authority) = tls_authority {
        state.auth_method = "x509".to_string();
        state.auth_authority = authority;
    }
    state.peer = peer.to_string();
    state.audit = audit;
    let rl_cfg = crate::server::rate_limit::RateLimitConfig::from_env();
    state.rate_limiter = rl_cfg.build();
    state.rate_limit_strike_threshold = rl_cfg.strike_threshold;
    state.audit("connect", "", "", "ok").await;

    // C `rsrv/caservertask.c::create_tcp_client:1525` calls
    // `rsrv_version_reply(client)` immediately after `db_start_events`,
    // so the server's first wire frame on any new TCP connection is
    // an unsolicited `CA_PROTO_VERSION` (cmmd=0, count=
    // CA_MINOR_PROTOCOL_REVISION, all other fields zero). libca's
    // `tcpRecvWatchdog::messageArrivalNotify` uses every received
    // frame as a liveness beat; without this, the server's first byte
    // is delayed until the client sends its own CA_PROTO_VERSION,
    // which can drift slow handshakes toward CA_ECHO_TIMEOUT. Also
    // restores wire-trace parity with rsrv (the first byte from the
    // server matches).
    {
        let mut hdr = CaHeader::new(CA_PROTO_VERSION);
        hdr.count = CA_MINOR_VERSION;
        let mut w = writer.lock().await;
        w.write_all(&hdr.to_bytes()).await?;
        w.flush().await?;
    }

    let mut reader = reader;

    let mut buf = vec![0u8; 8192];
    let mut accumulated = Vec::new();
    let inactivity = inactivity_timeout();

    // CRITICAL: every exit path from the read loop — graceful EOF
    // (`break`), propagated I/O / protocol error, rate-limit disconnect,
    // send-timeout disconnect — MUST pass through the single teardown
    // block below (subscription cancel, write-notify abort,
    // SubscriptionClosed / ChannelCleared emission). Previously the
    // in-loop `return Ok(())` / `return Err(..)` sites bypassed the
    // teardown, leaking write-notify tasks and inflating consumer
    // refcounts permanently after any non-graceful disconnect.
    //
    // The loop is wrapped in a labeled block: in-loop exits use
    // `break 'client_loop <CaResult>` so control always reaches the
    // teardown, and the captured result is returned only afterwards.
    //
    // `disconnect_reason` carries the specific cause (rate_limited /
    // send_timeout / error / ok) to the single post-teardown audit
    // call — replacing the per-path `state.audit("disconnect", ..)`
    // calls that previously had to live next to each `return`.
    let mut disconnect_reason: &str = "ok";
    let loop_result: CaResult<()> = 'client_loop: {
        loop {
            // Bound read with inactivity timeout so a fully-silent half-open
            // connection eventually gets cleaned up even if OS keepalive failed.
            // Race the read against ACF reload notifications so a `reload_acf*()`
            // call promptly re-pushes CA_PROTO_ACCESS_RIGHTS for every open
            // channel — RSRV's `sendAllUpdateAS` analog.
            let n = tokio::select! {
                biased;
                reload = acf_reload_rx.recv() => {
                    match reload {
                        Ok(()) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
                            // Lagged is fine — even one missed notification still
                            // means "rules changed", so we always recompute. A
                            // re-push failure must still pass through teardown.
                            if let Err(e) = reeval_access_rights(&mut state, &writer).await {
                                break 'client_loop Err(e);
                            }
                            continue;
                        }
                        Err(tokio::sync::broadcast::error::RecvError::Closed) => {
                            // Sender dropped — the server is going away.
                            break 'client_loop Ok(());
                        }
                    }
                }
                read = read_with_optional_timeout(&mut reader, &mut buf, inactivity) => {
                    match read {
                        Ok(Ok(n)) => n,
                        Ok(Err(e)) => break 'client_loop Err(e.into()),
                        Err(idle) => {
                            // Inactivity timeout — close the connection.
                            // Disabled by default (matches C rsrv); fires only
                            // when EPICS_CAS_INACTIVITY_TMO is set explicitly.
                            tracing::warn!(
                                target: "epics_ca_rs::server",
                                peer = %state.peer,
                                idle_secs = idle.as_secs(),
                                "CA server: client idle, closing"
                            );
                            break 'client_loop Ok(());
                        }
                    }
                }
            };
            if n == 0 {
                break 'client_loop Ok(());
            }

            // PR #592 dbServerStats: bytes_in mirrors RSRV's
            // `caServerBytes_in`. Counted on every successful read of `n`
            // wire bytes, regardless of whether the inner dispatch
            // accepts or rejects the message.
            if let Some(ref s) = stats {
                s.bytes_in
                    .fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed);
            }

            // Chaos: optional stall + simulated read drop. Compiles to a
            // single branch when EPICS_CA_RS_CHAOS is unset.
            if crate::chaos::enabled() {
                crate::chaos::maybe_stall().await;
                if crate::chaos::should_drop_read() {
                    continue;
                }
            }

            accumulated.extend_from_slice(&buf[..n]);

            // DoS guard: a malformed or hostile client could declare a huge
            // postsize and stream nothing more, growing this Vec unbounded.
            let accum_cap = max_accumulated();
            if accumulated.len() > accum_cap {
                eprintln!(
                    "CA server: client accumulated buffer exceeded {accum_cap} bytes, closing"
                );
                break 'client_loop Ok(());
            }

            let mut offset = 0;
            while offset + CaHeader::SIZE <= accumulated.len() {
                // C `camessage` dispatcher (camessage.c:2471-2489): if
                // msgsize > maxstk (recv buffer ceiling, =
                // rsrvSizeofLargeBufTCP after expand), emit ECA_TOLARGE
                // via send_err and drain the rest of the message. Rust
                // `CaHeader::from_bytes_extended` returns
                // CaError::Protocol("payload too large") when the
                // extended postsize exceeds `max_payload_size()`
                // (default 16 MiB), and the `?` propagation silently
                // closes the connection. C clients waiting on the
                // ECA_TOLARGE error callback see only EOF. Pre-check
                // the extended postsize here and emit the wire reply
                // before propagating the error.
                //
                // Normal-form headers can't overflow `max_payload_size()`
                // because their postsize is u16 (max 0xfffe < 16 MiB),
                // so the check only triggers on extended frames.
                let buf = &accumulated[offset..];
                if buf.len() >= 24 && buf[2] == 0xFF && buf[3] == 0xFF {
                    let ext_post =
                        u32::from_be_bytes([buf[16], buf[17], buf[18], buf[19]]) as usize;
                    if ext_post > crate::protocol::max_payload_size() {
                        // Build a stand-in header for the error reply
                        // (cmmd echoed from the malformed frame; cid
                        // sentinel 0xFFFFFFFF per `vsend_err`
                        // non-channel-scoped convention).
                        let mut probe_hdr = CaHeader::new(u16::from_be_bytes([buf[0], buf[1]]));
                        probe_hdr.data_type = u16::from_be_bytes([buf[4], buf[5]]);
                        let _ = send_ca_error(
                            &writer,
                            &probe_hdr,
                            ECA_TOLARGE,
                            0xFFFF_FFFF,
                            "CAS: Server unable to load large request message",
                        )
                        .await;
                        let _ = writer.lock().await.flush().await;
                        break 'client_loop Err(epics_base_rs::error::CaError::Protocol(format!(
                            "CA payload too large: ext_post={} > max={} \
                         (matches C dispatcher ECA_TOLARGE wire reply + drop)",
                            ext_post,
                            crate::protocol::max_payload_size()
                        )));
                    }
                }
                // C `rsrv/camessage.c:~2410`: when the buffer holds a
                // partial extended-form header (16..24 bytes of a message
                // whose `m_postsize == 0xffff`), C does `status = RSRV_OK;
                // break;` to await the remaining bytes — it does NOT
                // disconnect. Without this guard, `from_bytes_extended`
                // returns `Err("extended header incomplete")` and the `?`
                // below closes the connection on a benign TCP segment
                // boundary. The ECA_TOLARGE pre-check above is gated on
                // `buf.len() >= 24`, so it never masks this 16..24 window.
                if buf.len() < 24 && buf[2] == 0xFF && buf[3] == 0xFF {
                    break;
                }
                let (hdr, hdr_size) = match CaHeader::from_bytes_extended(&accumulated[offset..]) {
                    Ok(v) => v,
                    Err(e) => break 'client_loop Err(e),
                };
                let actual_post = hdr.actual_postsize();
                // C `rsrv/camessage.c:2452` rejects misaligned payloads
                // ("CAS: Missaligned protocol rejected") with an
                // ECA_INTERNAL error and disconnects the client. Our
                // previous code silently rounded up via `align8`, which on
                // a hostile peer would cause us to read into the next
                // message's header and de-sync the stream. Now: emit
                // CA_PROTO_ERROR + drop the connection (match C).
                if actual_post & 0x7 != 0 {
                    tracing::warn!(
                        peer = %state.peer,
                        cmmd = hdr.cmmd,
                        postsize = actual_post,
                        "CAS: Missaligned protocol rejected"
                    );
                    let _ = send_ca_error(
                        &writer,
                        &hdr,
                        ECA_INTERNAL,
                        0xFFFF_FFFF,
                        "CAS: Missaligned protocol rejected",
                    )
                    .await;
                    let _ = writer.lock().await.flush().await;
                    break 'client_loop Err(epics_base_rs::error::CaError::Protocol(
                        "misaligned CA payload".into(),
                    ));
                }
                let msg_len = hdr_size + actual_post;

                if offset + msg_len > accumulated.len() {
                    break;
                }

                let payload = if actual_post > 0 {
                    accumulated[offset + hdr_size..offset + hdr_size + actual_post].to_vec()
                } else {
                    Vec::new()
                };

                // Rate-limit gate: drop messages when the bucket is empty;
                // disconnect the client once it accumulates enough strikes.
                if let Some(ref limiter) = state.rate_limiter {
                    if limiter.try_acquire().is_err() {
                        metrics::counter!("ca_server_rate_limit_drops_total").increment(1);
                        state.rate_limit_strikes = state.rate_limit_strikes.saturating_add(1);
                        if state.rate_limit_strike_threshold > 0
                            && state.rate_limit_strikes >= state.rate_limit_strike_threshold
                        {
                            tracing::warn!(peer = %state.peer, strikes = state.rate_limit_strikes,
                            "rate limit exceeded; closing connection");
                            metrics::counter!("ca_server_rate_limit_disconnects_total")
                                .increment(1);
                            disconnect_reason = "rate_limited";
                            break 'client_loop Ok(());
                        }
                        offset += msg_len;
                        continue;
                    } else if state.rate_limit_strikes > 0 {
                        state.rate_limit_strikes = 0;
                    }
                }

                // Wrap dispatch in send_timeout so a stuck-reader client
                // (kernel send buffer full → `write_all` Pending forever)
                // can be detected and disconnected. Without this, one
                // misbehaving client could deadlock its own per-client
                // task indefinitely. On timeout we drop the connection;
                // any in-flight reply is discarded.
                match tokio::time::timeout(
                    send_timeout(),
                    dispatch_message(
                        &hdr,
                        &payload,
                        &mut state,
                        &db,
                        &writer,
                        peer,
                        conn_events.as_ref(),
                    ),
                )
                .await
                {
                    Ok(Ok(())) => {}
                    Ok(Err(e)) => {
                        // Regression defence: dispatch_message no longer
                        // flushes per response (batched at the bottom of
                        // this outer loop). On a propagated dispatch
                        // error, exit-via-`?` would drop the BufWriter
                        // before the outer flush fires, so any responses
                        // queued by earlier successful handlers in this
                        // batch — or by an error-path `send_cmd_error`
                        // call inside the failing handler — would be
                        // lost. Best-effort flush before propagating so
                        // the client sees them; ignore errors here
                        // because the underlying TCP is most likely
                        // already broken (which is why dispatch failed).
                        let _ = writer.lock().await.flush().await;
                        break 'client_loop Err(e);
                    }
                    Err(_) => {
                        // send_timeout fires — dispatch_message future is
                        // cancelled mid-flight. BufWriter may hold a
                        // partial frame (e.g., header without payload if
                        // cancellation landed between the two write_alls
                        // of a READ_NOTIFY response). Flushing here would
                        // ship the orphan header to the client and leave
                        // it parsing an incomplete frame, so we skip the
                        // flush and let BufWriter drop discard the
                        // partial bytes — same behaviour as before the
                        // batch-flush refactor.
                        tracing::warn!(
                            peer = %peer,
                            "CA server: dispatch send-timeout (stuck client?), closing"
                        );
                        disconnect_reason = "send_timeout";
                        break 'client_loop Ok(());
                    }
                }
                offset += msg_len;
            }

            if offset > 0 {
                accumulated.drain(..offset);
                // Batched flush: dispatch_message buffered all responses for
                // this read iteration into BufWriter without flushing. Flush
                // once now so the kernel sees a single TCP write per inbound
                // burst. Cuts e2e_bulk_get_many(100) from ~225µs → batched
                // single write (server-side throughput floor was ~2.2µs/PV
                // due to per-message flush; this collapses it to one syscall).
                //
                // Errors here mean the TCP write stalled / peer closed —
                // surface as the read loop's normal disconnect path.
                let mut w = writer.lock().await;
                // PR #592 dbServerStats: bytes_out mirrors RSRV's
                // `caServerBytes_out`. Capture the buffered size *before*
                // flush so we know exactly how many wire bytes leave on
                // this syscall. CA-over-TLS counts post-decrypt plaintext
                // since the rustls layer wraps the BufWriter externally —
                // matches what the comment on ServerStats::bytes_out
                // already documents.
                let pending_out = w.buffer().len() as u64;
                if let Err(e) = w.flush().await {
                    break 'client_loop Err(e.into());
                }
                if let Some(ref s) = stats {
                    s.bytes_out
                        .fetch_add(pending_out, std::sync::atomic::Ordering::Relaxed);
                }
                drop(w);
            }
        }
    };

    // Cleanup: cancel all subscriptions. PR #592 dbServerStats —
    // emit `SubscriptionClosed` for each so the running close-count
    // matches the open-count when a client disconnects without
    // explicit EVENT_CANCEL (TCP RST, network drop, panic). Without
    // this, `active_subscriptions` reports a permanent leak after
    // every ungraceful disconnect.
    let pending_subs: Vec<SubscriptionEntry> =
        state.subscriptions.drain().map(|(_, sub)| sub).collect();
    for sub in pending_subs {
        sub.task.abort();
        match &sub.target {
            ChannelTarget::SimplePv(pv) => {
                pv.remove_subscriber(sub.sub_id).await;
            }
            ChannelTarget::RecordField { record, .. } => {
                record.write().await.remove_subscriber(sub.sub_id);
            }
        }
        if let Some(tx) = &conn_events {
            let pv_name = state
                .channels
                .get(&sub.channel_sid)
                .map(|e| e.pv_name.clone())
                .unwrap_or_default();
            let _ = tx.send(ServerConnectionEvent::SubscriptionClosed {
                peer,
                pv_name,
                sub_id: sub.sub_id,
            });
        }
    }

    // Abort any in-flight WRITE_NOTIFY completion tasks. A
    // stuck async record (motor hung, asyn device unresponsive) would
    // otherwise hold the spawned task and its captured writer Arc
    // forever after the client disconnects.
    for (_sid, handle) in state.write_notify_tasks.drain(..) {
        handle.abort();
    }

    // Emit a `ChannelCleared` event for every channel still open at
    // disconnect time. Without this, a client that drops without
    // sending `CA_PROTO_CLEAR_CHANNEL` (TCP RST, network drop, panic)
    // leaks its channel refcount in any consumer that uses these
    // events for refcounting (e.g. ca_gateway's per-PV `Active` →
    // `Inactive` transition). Done here so the events fire BEFORE
    // the listener emits `Disconnected(peer)`, preserving the
    // ordering invariant "clears precede disconnect".
    if let Some(tx) = &conn_events {
        for (_sid, entry) in state.channels.drain() {
            let _ = tx.send(ServerConnectionEvent::ChannelCleared {
                peer,
                pv_name: entry.pv_name,
                cid: entry.cid,
            });
        }
    }

    // Audit with the outcome the loop exited on, then return that
    // outcome. The teardown above ran unconditionally regardless of
    // whether `loop_result` is Ok or Err. An Err exit that did not set
    // a more specific reason is reported as "error".
    if loop_result.is_err() && disconnect_reason == "ok" {
        disconnect_reason = "error";
    }
    state.audit("disconnect", "", "", disconnect_reason).await;
    loop_result
}

async fn dispatch_message<W: AsyncWrite + Unpin + Send + 'static>(
    hdr: &CaHeader,
    payload: &[u8],
    state: &mut ClientState,
    db: &Arc<PvDatabase>,
    writer: &Arc<Mutex<BufWriter<W>>>,
    peer: SocketAddr,
    conn_events: Option<&broadcast::Sender<ServerConnectionEvent>>,
) -> CaResult<()> {
    // C dispatcher (camessage.c:2427-2440): any non-VERSION command
    // from a client whose minor_version_number is below
    // CA_MINIMUM_SUPPORTED_VERSION (= 4) gets ECA_DEFUNCT via
    // send_err and the message is drained (status = RSRV_OK,
    // connection stays open). The intent is "let new clients
    // identify themselves but tell pre-V4.4 peers they're too old".
    //
    // Rust's `state.client_minor_version` defaults to 0 (set only
    // by the VERSION handler). Pre-fix Rust would dispatch any
    // non-VERSION command on a fresh connection with minor=0,
    // bypassing the gate. The CREATE_CHAN / READ / WRITE wire
    // formats may differ for ancient clients; the C IOC's
    // ECA_DEFUNCT hint lets the client decide whether to upgrade.
    //
    // Note: TCP VERSION with minor<4 already disconnects via
    // dbb4b28, so this gate only triggers on clients
    // that skipped the VERSION handshake entirely OR on a peer
    // explicitly identifying as pre-V4.4.
    if hdr.cmmd != CA_PROTO_VERSION && state.client_minor_version < 4 {
        send_ca_error(
            writer,
            hdr,
            ECA_DEFUNCT,
            0xFFFF_FFFF,
            "CAS: Client version too old",
        )
        .await?;
        return Ok(());
    }

    match hdr.cmmd {
        CA_PROTO_VERSION => {
            // C `tcp_version_action` (camessage.c:366-369): rejects
            // clients whose minor version < CA_MINIMUM_SUPPORTED_VERSION
            // (=4) with RSRV_ERROR, which tears the connection down.
            // Without this gate, an ancient client could complete the
            // VERSION handshake and proceed to CREATE_CHAN with a
            // wire format we no longer fully support — silently
            // diverging from C IOC behaviour.
            const CA_MINIMUM_SUPPORTED_VERSION: u16 = 4;
            if hdr.count < CA_MINIMUM_SUPPORTED_VERSION {
                tracing::warn!(
                    peer = ?peer,
                    minor = hdr.count,
                    "CAS: Ignore version from unsupported client (minor < 4); dropping"
                );
                return Err(epics_base_rs::error::CaError::Protocol(format!(
                    "unsupported CA minor version {} (matches C tcp_version_action drop)",
                    hdr.count
                )));
            }
            // C `tcp_version_action` (`rsrv/camessage.c:371-373`) drops
            // the connection (`return RSRV_ERROR`) when the client's
            // requested priority (`m_dataType`) exceeds
            // `CA_PROTO_PRIORITY_MAX` (= 99u in `caProto.h:71`). The
            // priority drives the IOC's per-client epicsThread
            // scheduling-priority assignment downstream, so a value
            // outside the legal 0..=99 range is rejected hard rather
            // than silently clamped. Pre-fix Rust accepted any
            // priority and emitted the VERSION reply normally —
            // benign on the wire but diverges from libca's expected
            // close-on-bad-priority behaviour, which a strict CAC
            // peer would notice.
            const CA_PROTO_PRIORITY_MAX: u16 = 99;
            if hdr.data_type > CA_PROTO_PRIORITY_MAX {
                tracing::warn!(
                    peer = ?peer,
                    priority = hdr.data_type,
                    "CAS: VERSION with priority > CA_PROTO_PRIORITY_MAX; dropping"
                );
                return Err(epics_base_rs::error::CaError::Protocol(format!(
                    "VERSION priority {} > {} (matches C tcp_version_action drop)",
                    hdr.data_type, CA_PROTO_PRIORITY_MAX
                )));
            }
            state.client_minor_version = hdr.count;
            // C `rsrv_version_reply` (camessage.c:2115) emits VERSION
            // with all fields zero except `m_count = CA_MINOR_PROTOCOL_REVISION`.
            // The previous Rust defaults (`data_type=1, cid=1`) drifted
            // from byte-exact parity — C clients only consult `m_count`
            // (`tcpiiu.cpp::versionRespNotify`) so it was harmless in
            // practice, but a strict peer or wire trace would diverge.
            let mut resp = CaHeader::new(CA_PROTO_VERSION);
            resp.count = CA_MINOR_VERSION;
            let mut w = writer.lock().await;
            w.write_all(&resp.to_bytes()).await?;
            // flush deferred to handle_client outer loop (batched)
        }

        CA_PROTO_HOST_NAME => {
            // C `camessage.c::host_name_action` (line ~795 onward)
            // rejects HOST_NAME messages that arrive after the first
            // channel has been created — once the client claims any
            // channel, the host identity is fixed for the connection.
            // Reuse the same wire response: CA_PROTO_ERROR with
            // ECA_INTERNAL and a descriptive message.
            if !state.channels.is_empty() {
                send_ca_error(
                    writer,
                    hdr,
                    ECA_INTERNAL,
                    0xFFFF_FFFF,
                    "attempts to use protocol to set host name \
                     after creating first channel ignored by server",
                )
                .await?;
                return Ok(());
            }
            // C `camessage.c:824-825`: `size = strnlen(pName, m_postsize)
            // + 1; if (size > 512 || size > m_postsize) reject`.
            // The second condition rejects payloads with no null
            // terminator within m_postsize bytes (strnlen returns
            // m_postsize, then +1 overflows). Rust's
            // `position(|&b| b == 0)` returns Some(idx) for
            // terminated names and `None` (mapped to payload.len())
            // for unterminated ones — check explicitly so we don't
            // silently accept unterminated names that C would
            // reject as "very long".
            let null_pos = payload.iter().position(|&b| b == 0);
            let end = null_pos.unwrap_or(payload.len());
            if null_pos.is_none() || end >= 512 {
                // C `host_name_action` (camessage.c:825-836): a name
                // longer than 511 bytes is a protocol violation —
                // send_err + return RSRV_ERROR (disconnect). The
                // post-claim freeze branch above returns RSRV_OK
                // (recoverable misuse), but the size cap is a
                // wire-malformation reject.
                send_ca_error(
                    writer,
                    hdr,
                    ECA_INTERNAL,
                    0xFFFF_FFFF,
                    "bad (very long) host name",
                )
                .await?;
                return Err(epics_base_rs::error::CaError::Protocol(
                    "HOST_NAME exceeds 511-byte cap (matches C host_name_action RSRV_ERROR)".into(),
                ));
            }

            // EPICS_CAS_USE_HOST_NAMES (default NO) controls whether we
            // trust the client-supplied hostname for ACF matching. When NO,
            // the peer IP set during accept() is authoritative.
            let trust_client_hostname =
                epics_base_rs::runtime::env::get_or("EPICS_CAS_USE_HOST_NAMES", "NO")
                    .eq_ignore_ascii_case("YES");
            if trust_client_hostname {
                let claimed = String::from_utf8_lossy(&payload[..end]).to_string();

                // Forward-DNS verification: resolve the client-supplied
                // hostname back to IPs and require one of them to match
                // the actual peer address. Without this check a hostile
                // client could spoof an arbitrary hostname (e.g. that
                // of a privileged operator console) and gain whatever
                // ACF rights the ACL grants to that host. C rsrv has
                // historically deferred this verification to operators
                // (relying on USE_HOST_NAMES=NO in untrusted networks);
                // we fail closed here for stricter defaults.
                let verified = host_resolves_to_peer(&claimed, peer.ip()).await;
                if verified {
                    state.hostname = claimed;
                    // Re-evaluate access rights for all existing channels
                    reeval_access_rights(state, writer).await?;
                } else {
                    tracing::warn!(
                        peer = %peer,
                        claimed_host = %claimed,
                        "CAS_USE_HOST_NAMES: forward-DNS mismatch, ignoring HOST_NAME"
                    );
                    state.audit("host_name", "", &claimed, "dns_mismatch").await;
                    // Keep state.hostname as the peer IP fallback set
                    // at accept(); ACL rules continue to evaluate
                    // against the IP rather than the spoofed hostname.
                }
            }
        }

        CA_PROTO_CLIENT_NAME => {
            // C `camessage.c::client_name_action` rejects CLIENT_NAME
            // after the first channel has been created (line ~898).
            if !state.channels.is_empty() {
                send_ca_error(
                    writer,
                    hdr,
                    ECA_INTERNAL,
                    0xFFFF_FFFF,
                    "attempts to use protocol to set user name \
                     after creating first channel ignored by server",
                )
                .await?;
                return Ok(());
            }
            // C `camessage.c:911-912`: same 512-byte cap as host
            // name, AND same null-termination requirement. C
            // computes `size = strnlen(pName, m_postsize) + 1`
            // then rejects on `size > m_postsize`, which catches
            // names with no null terminator within m_postsize
            // bytes. Match by treating "no null found" as a
            // reject.
            let null_pos = payload.iter().position(|&b| b == 0);
            let end = null_pos.unwrap_or(payload.len());
            if null_pos.is_none() || end >= 512 {
                // C `client_name_action` (camessage.c:912-923): same
                // 511-byte cap as host_name; send_err + RSRV_ERROR
                // (disconnect). Post-claim freeze branch returns
                // RSRV_OK; size cap returns RSRV_ERROR.
                send_ca_error(
                    writer,
                    hdr,
                    ECA_INTERNAL,
                    0xFFFF_FFFF,
                    "a very long user name was specified",
                )
                .await?;
                return Err(epics_base_rs::error::CaError::Protocol(
                    "CLIENT_NAME exceeds 511-byte cap (matches C client_name_action RSRV_ERROR)"
                        .into(),
                ));
            }
            let raw = String::from_utf8_lossy(&payload[..end]).to_string();
            // When a capability-token verifier is configured AND the
            // payload arrives in `cap:<token>` form, verify the token
            // and store the resolved subject. Unverifiable tokens are
            // logged and replaced with a fixed `unverified` sentinel
            // that ACF rules can deliberately deny. Plain (non-`cap:`)
            // usernames pass through unchanged for backwards compat.
            #[cfg(feature = "cap-tokens")]
            {
                // M1: TokenVerifier::verify expects the full `cap:`-
                // prefixed form (it strips the prefix internally).
                // The previous double-strip yielded MissingPrefix on
                // every well-formed token; cap-tokens was non-
                // functional whenever a verifier was configured.
                state.username = match (&state.cap_token_verifier, raw.starts_with("cap:")) {
                    (Some(v), true) => match v.verify(&raw, state.tls_channel_binding.as_ref()) {
                        Ok(claims) => {
                            tracing::debug!(peer = %state.peer, sub = %claims.sub,
                                "cap-token verified");
                            // propagate auth_method / authority so
                            // ACF rules of the form
                            // `RULE(1, WRITE) { METHOD("cap-token")
                            //                   AUTHORITY("ops-issuer-1") }`
                            // can scope by authenticator subsystem and
                            // issuer key id. Pre-fix only `state.username
                            // = claims.sub` was set, leaving auth_method
                            // empty (or `"x509"` if mTLS is also active),
                            // so cap-token METHOD/AUTHORITY clauses
                            // could not match a verified token.
                            state.auth_method = "cap-token".to_string();
                            state.auth_authority = claims.iss.clone();
                            claims.sub
                        }
                        Err(e) => {
                            // Do NOT fold the raw token into the username:
                            // it then lands in the ACF identity and the
                            // audit log. A structurally valid but rejected
                            // token (aud/binding/expiry mismatch) is a real
                            // bearer credential, and a garbage token is
                            // attacker-controlled bytes — neither belongs
                            // there. A fixed sentinel is enough for ACF to
                            // deny; the reason is in the warn log.
                            tracing::warn!(peer = %state.peer, error = %e,
                                "cap-token verification failed");
                            "unverified".to_string()
                        }
                    },
                    _ => raw,
                };
            }
            #[cfg(not(feature = "cap-tokens"))]
            {
                state.username = raw;
            }
            // Re-evaluate access rights for all existing channels
            reeval_access_rights(state, writer).await?;
        }

        CA_PROTO_CREATE_CHAN => {
            // Pre-CA-4.4 clients send claims with no PV name (postsize=0).
            // Silently ignore these, matching C server behavior (camessage.c:1204).
            // The client will retry with v4.4+ format after receiving our VERSION.
            if hdr.actual_postsize() <= 1 {
                return Ok(());
            }
            // C `rsrv/camessage.c:1190-1199` `claim_ciu_action`
            // unconditionally executes `client->minor_version_number
            // = mp->m_available;` — the protocol comment is explicit:
            // "The available field is used (abused) here to
            // communicate the minor version number starting with
            // CA 4.1". A client that handshakes v4.4 then upgrades on
            // CREATE_CHAN to v4.13 gets the upgrade applied through
            // this branch, which downstream `CA_V49` checks (extended-
            // form headers for nElem >= 0xffff) then honour. Pre-fix
            // Rust ignored `hdr.available` here, so a peer using the
            // upgrade pattern saw truncated counts on large arrays.
            if (hdr.available as u16) > state.client_minor_version {
                state.client_minor_version = hdr.available as u16;
            }

            // DoS guard: refuse new channels once an opt-in per-client
            // cap is hit. Default-unbounded (`None`) — C `claim_ciu_action`
            // imposes no per-client channel count limit (see
            // `max_channels_per_client`). When no cap is configured the
            // whole block is inert, so a legitimate large-fan-out client
            // (e.g. `caget` over thousands of PVs on one circuit) is never
            // refused at a fixed boundary.
            if let Some(cap) = max_channels_per_client() {
                // Pre-warning at 90% — fired once per crossing, not once per
                // CREATE_CHAN, to avoid log spam.
                let warn_threshold = (cap * 9) / 10;
                if !state.channel_limit_warned && state.channels.len() >= warn_threshold {
                    tracing::warn!(
                        channels = state.channels.len(),
                        cap,
                        "approaching per-client channel limit (90%)"
                    );
                    metrics::counter!("ca_server_channel_limit_warnings_total").increment(1);
                    state.channel_limit_warned = true;
                }
                if state.channels.len() >= cap {
                    tracing::warn!(
                        channels = state.channels.len(),
                        cap,
                        "rejecting CREATE_CHAN: per-client channel limit reached"
                    );
                    metrics::counter!("ca_server_channel_limit_rejects_total").increment(1);
                    // C parity: `claim_ciu_action` (rsrv/camessage.c:1229-1239)
                    // routes channel-allocation failure through
                    // `send_err(mp, ECA_ALLOCMEM, …)`, NOT
                    // CREATE_CH_FAIL. CREATE_CH_FAIL is reserved for the
                    // `dbChannel_create` (PV/field not found) branch
                    // (camessage.c:1212-1219). libca
                    // `exceptionRespAction` surfaces the ECA_ALLOCMEM
                    // status to the user-level callback so the client
                    // knows "server out of resources" vs CREATE_CH_FAIL's
                    // "PV does not exist on this server" — the existing
                    // Rust path conflated the two, leading clients to
                    // remove our address from their resolution cache on
                    // a transient server saturation. Per `vsend_err`'s
                    // switch, CA_PROTO_CREATE_CHAN falls to `default`
                    // and uses `0xffffffff` for `m_cid`.
                    send_ca_error(writer, hdr, ECA_ALLOCMEM, u32::MAX, "channel limit reached")
                        .await?;
                    // C `claim_ciu_action` (camessage.c:1229-1240): when
                    // the server's channel-allocation pool is exhausted,
                    // send_err(ECA_ALLOCMEM) is followed by RSRV_ERROR
                    // which tears the connection down. The Rust per-
                    // client cap is the closest analogue: same root
                    // cause (this client requested more channels than
                    // the server is willing to hold) and the same
                    // ECA_ALLOCMEM wire byte. Match C by dropping the
                    // connection so a misbehaving client doesn't sit
                    // and spam CREATE_CHAN frames against a saturated
                    // cap; the next reconnect re-baselines.
                    return Err(epics_base_rs::error::CaError::Protocol(
                        "CREATE_CHAN per-client cap reached \
                         (matches C claim_ciu_action ECA_ALLOCMEM + RSRV_ERROR)"
                            .into(),
                    ));
                }
            }

            // C `claim_ciu_action` (`rsrv/camessage.c`) forces
            // `pName[mp->m_postsize - 1] = '\0'` after rejecting
            // `m_postsize <= 1`. Effect: an unterminated name of
            // exactly `postsize` non-NUL bytes is treated as a
            // `postsize - 1` byte name. Pre-fix Rust used all
            // `payload.len()` bytes on the unterminated path, so a
            // malformed peer could resolve a different name than
            // rsrv would.
            let scan_end = payload.len().saturating_sub(1).max(0);
            let end = payload[..scan_end]
                .iter()
                .position(|&b| b == 0)
                .unwrap_or(scan_end);
            let pv_name = String::from_utf8_lossy(&payload[..end]).to_string();
            let client_cid = hdr.cid;
            // epics-base 3.15.7 channel-filter suffix
            // (`REC.{"dbnd":{"d":0.5}}`). Split the JSON suffix off
            // for the record lookup, but keep `pv_name` verbatim so
            // the audit log and `ChannelCreated`/`ChannelCleared`
            // events still surface the literal string the client
            // used. `filter_suffix` is stashed on the channel so
            // EVENT_ADD can build a `FilterChain` from it later.
            let parsed_channel =
                epics_base_rs::server::database::filters::split_channel_name(&pv_name);
            let record_path_raw = parsed_channel.record_path;
            let filter_suffix = parsed_channel.json_suffix;
            // detect the `$` long-string modifier (C dbChannel.c:482-507).
            // C strips it AFTER the record/field name lookup, so it modifies
            // the resolved field — the explicit `.FIELD` or, for a bare
            // `REC$`, the default VAL. Strip it from the whole channel name
            // first so a record-level `REC$` (no explicit `.FIELD`) is handled
            // too, not only `REC.FIELD$`: leaving `$` on the record key made
            // `find_entry_from` miss the record and return CREATE_CH_FAIL,
            // where C serves the field's long string. `long_string` makes
            // every delivery path convert the value to DBR_CHAR with a NUL
            // terminator.
            let long_string = record_path_raw.ends_with('$');
            let record_path = if long_string {
                &record_path_raw[..record_path_raw.len() - 1]
            } else {
                record_path_raw.as_str()
            };
            let (_base, field_raw) = parse_pv_name(record_path);
            let field = field_raw.to_ascii_uppercase();

            // thread the connection peer into the search
            // resolver so the CA gateway applies host-scoped `.pvlist`
            // `DENY FROM host` admission on CREATE_CHANNEL (parity with C
            // `pvExistTest` → `gateAs::findEntry(pvname, hostname)`).
            if let Some(entry) = db.find_entry_from(record_path, Some(peer)).await {
                let sid = state.alloc_sid();

                let (dbr_type, element_count, target, long_string_mode) = match entry {
                    PvEntry::Simple(pv) => {
                        let value = pv.get().await;
                        // `$` long-string — C dbChannel.c:486-503 requires the
                        // field to be DBF_STRING; other types get
                        // S_dbLib_fieldNotFound (CREATE_CH_FAIL). When it is a
                        // string C overrides the channel to DBF_CHAR with
                        // `no_elements = field_size` (= 40). This must match the
                        // RecordField arm below, because the channel stores
                        // its `LongStringMode` and every delivery path runs
                        // `apply_long_string` to convert the value to CHAR[40];
                        // advertising the native DBR_STRING/1 here would
                        // mis-size the client buffer against the delivered data.
                        if long_string && !matches!(value, EpicsValue::String(_)) {
                            let mut fail = CaHeader::new(CA_PROTO_CREATE_CH_FAIL);
                            fail.cid = client_cid;
                            let mut w = writer.lock().await;
                            w.write_all(&fail.to_bytes()).await?;
                            return Ok(());
                        }
                        let (dbr_type_val, element_count, mode) = if long_string {
                            (DbFieldType::Char, 40u32, LongStringMode::DollarChar)
                        } else {
                            (
                                value.dbr_type(),
                                value.count() as u32,
                                LongStringMode::Plain,
                            )
                        };
                        (
                            dbr_type_val,
                            element_count,
                            ChannelTarget::SimplePv(pv),
                            mode,
                        )
                    }
                    PvEntry::Record(rec) => {
                        let instance = rec.read().await;
                        // `client_field_value` = resolve_field (3-level
                        // priority) with a DBF_MENU field promoted to its
                        // DBR_ENUM form, so the channel's announced native
                        // type matches the GET/MONITOR data
                        // (`value.dbr_type()` below).
                        let value = instance.client_field_value(&field);
                        match value {
                            Some(v) => {
                                // `$` long-string — C dbChannel.c:483-507
                                // requires the field to be DBF_STRING
                                // (EpicsValue::String). Other field types get
                                // S_dbLib_fieldNotFound (CREATE_CH_FAIL parity).
                                if long_string && !matches!(v, EpicsValue::String(_)) {
                                    let mut fail = CaHeader::new(CA_PROTO_CREATE_CH_FAIL);
                                    fail.cid = client_cid;
                                    let mut w = writer.lock().await;
                                    w.write_all(&fail.to_bytes()).await?;
                                    return Ok(());
                                }
                                // override type and count for `$` channels.
                                // C sets `paddr->field_type = DBF_CHAR`,
                                // `paddr->dbr_field_type = DBR_CHAR`, and
                                // `paddr->no_elements = paddr->field_size` (= 40).
                                let (dbr_type_val, element_count, mode) = if long_string {
                                    (DbFieldType::Char, 40u32, LongStringMode::DollarChar)
                                } else if instance
                                    .record
                                    .long_string_fields()
                                    .contains(&field.as_str())
                                {
                                    // Long-string *record* field (lsi/lso VAL &
                                    // OVAL, printf VAL). C `cvt_dbaddr` presents
                                    // it as a scalar `DBF_STRING` with
                                    // `no_elements = 1` (lsiRecord.c:141-143,
                                    // lsoRecord.c:183-185, printfRecord.c:411-413);
                                    // the full long value is reachable only via
                                    // the `$` modifier (handled above). The record
                                    // stores the value as a CHAR-array carrier, so
                                    // every delivery path decodes it to a scalar
                                    // string with `apply_native_long_string`.
                                    (DbFieldType::String, 1u32, LongStringMode::NativeString)
                                } else if field == "VAL"
                                    && instance.record.record_type() == "waveform"
                                {
                                    // For waveform records, get_field("VAL") returns
                                    // NORD elements (valid data) but the channel's
                                    // native count must be NELM (max capacity) so
                                    // clients allocate the right buffer.
                                    let nelm = instance
                                        .resolve_field("NELM")
                                        .and_then(|n| match n {
                                            EpicsValue::Long(n) => Some(n.max(0) as u32),
                                            _ => None,
                                        })
                                        .unwrap_or(v.count() as u32);
                                    (v.dbr_type(), nelm, LongStringMode::Plain)
                                } else {
                                    (v.dbr_type(), v.count() as u32, LongStringMode::Plain)
                                };
                                (
                                    dbr_type_val,
                                    element_count,
                                    ChannelTarget::RecordField {
                                        record: rec.clone(),
                                        field: field.clone(),
                                    },
                                    mode,
                                )
                            }
                            None => {
                                // Field not found — send CREATE_CH_FAIL
                                let mut fail = CaHeader::new(CA_PROTO_CREATE_CH_FAIL);
                                fail.cid = client_cid;
                                let mut w = writer.lock().await;
                                w.write_all(&fail.to_bytes()).await?;
                                // flush deferred to handle_client outer loop (batched)
                                return Ok(());
                            }
                        }
                    }
                };

                // Parse the channel-filter suffix STRICTLY at channel
                // creation — EPICS `dbChannelCreate()` parity. C runs
                // `chf_parse()` while building the channel; a malformed /
                // non-object suffix, an unknown filter name, or a filter
                // whose own `parse_end()` rejects its config sets `status`,
                // and at `finish:` `dbChannelCreate()` does
                // `dbChannelDelete(chan); chan = NULL` and returns NULL —
                // i.e. CREATE_CH_FAIL on the CA wire (dbChannel.c:176-179,
                // 266-279, 512-526). The earlier CA path used the
                // permissive `parse_filter_chain`, which fails OPEN to an
                // unfiltered channel on a bad suffix, so a typo in a filter
                // used to throttle / slice / synchronize exposure read the
                // raw stream where C refuses the channel.
                //
                // On success the validated chain also yields the
                // filter-FINAL element count (C `dbChannelFinalElements`):
                // a count-reshaping filter (`arr` slice) shrinks how many
                // elements the channel can ever deliver, and the client
                // must learn that count so its READ / monitor request count
                // — and buffer allocation — match the filtered payload. An
                // empty / value-gating-only chain folds to the identity, so
                // unfiltered channels keep their native count unchanged.
                let element_count = match &filter_suffix {
                    Some(json) => {
                        match epics_base_rs::server::database::filters::try_parse_filter_chain(json)
                        {
                            Ok(chain) => chain.final_element_count(element_count as usize) as u32,
                            Err(e) => {
                                tracing::debug!(
                                    pv = %pv_name,
                                    error = %e,
                                    "rejecting CREATE_CHAN: invalid channel-filter suffix",
                                );
                                let mut fail = CaHeader::new(CA_PROTO_CREATE_CH_FAIL);
                                fail.cid = client_cid;
                                let mut w = writer.lock().await;
                                w.write_all(&fail.to_bytes()).await?;
                                // flush deferred to handle_client outer loop (batched)
                                drop(w);
                                state
                                    .audit("create_chan", &pv_name, "", "filter_parse_fail")
                                    .await;
                                return Ok(());
                            }
                        }
                    }
                    None => element_count,
                };

                let (access, rule_was_trap) = state.compute_access(&target).await;
                let access_level = match access {
                    3 => AccessLevel::ReadWrite,
                    1 => AccessLevel::Read,
                    _ => AccessLevel::NoAccess,
                };

                state.channels.insert(
                    sid,
                    ChannelEntry {
                        target,
                        cid: client_cid,
                        pv_name: pv_name.clone(),
                        filter_suffix: filter_suffix.clone(),
                        put_notify_slot: PutNotifySlot::default(),
                        long_string_mode,
                    },
                );
                state.channel_access.insert(sid, access_level);
                // keep the trap-mask map in lockstep with
                // `channel_access` so `lookup_access` always finds a
                // consistent pair for this SID.
                state.channel_trap.insert(sid, rule_was_trap);

                let mut ar = CaHeader::new(CA_PROTO_ACCESS_RIGHTS);
                ar.cid = client_cid;
                ar.available = access;

                // C `claim_ciu_reply` (camessage.c:1157-1167): clients
                // whose minor version is below CA_V49 (= 9) cannot parse
                // extended-form headers. For those peers, `nElem` is
                // capped at 0xfffe so the CREATE_CHAN reply stays in
                // normal-form (16-byte) layout; V4.9+ clients receive
                // the true count via the extended header.
                let nelem = if state.client_minor_version < 9 && element_count >= 0xffff {
                    0xfffe
                } else {
                    element_count
                };
                let mut resp = CaHeader::new(CA_PROTO_CREATE_CHAN);
                resp.data_type = dbr_type as u16;
                resp.cid = client_cid;
                resp.available = sid;
                resp.set_payload_size(0, nelem);

                let mut w = writer.lock().await;
                w.write_all(&ar.to_bytes()).await?;
                w.write_all(&resp.to_bytes_extended()).await?;
                // flush deferred to handle_client outer loop (batched)
                drop(w);

                let result = match access_level {
                    AccessLevel::NoAccess => "denied",
                    _ => "ok",
                };
                state.audit("create_chan", &pv_name, "", result).await;

                // Notify subscribers (e.g. ca_gateway tracking PV → client
                // attachments for `Active`/`Inactive` state transitions).
                // `cid` is included so consumers can refcount per
                // (peer, pv_name, cid) — same client opening N channels
                // to the same PV must increment N times.
                if let Some(tx) = &conn_events {
                    let _ = tx.send(ServerConnectionEvent::ChannelCreated {
                        peer,
                        pv_name: pv_name.clone(),
                        cid: client_cid,
                    });
                }
            } else {
                // PV not found — send CREATE_CH_FAIL
                let mut fail = CaHeader::new(CA_PROTO_CREATE_CH_FAIL);
                fail.cid = client_cid;
                let mut w = writer.lock().await;
                w.write_all(&fail.to_bytes()).await?;
                // flush deferred to handle_client outer loop (batched)
                drop(w);

                state.audit("create_chan", &pv_name, "", "not_found").await;
            }
        }

        CA_PROTO_READ | CA_PROTO_READ_NOTIFY => {
            let is_notify = hdr.cmmd == CA_PROTO_READ_NOTIFY;
            let sid = hdr.cid;
            let ioid = hdr.available;
            let requested_type = hdr.data_type;
            let requested_count = hdr.actual_count();

            // the two read commands differ in WHERE the
            // `INVALID_DB_REQ(m_dataType)` type check sits relative to
            // the channel lookup.
            //
            // C `read_notify_action` (`rsrv/camessage.c:693-697`) checks
            // the type BEFORE the lookup and returns RSRV_ERROR with no
            // wire frame, so READ_NOTIFY is handled here, silently.
            //
            // C `read_action` (`rsrv/camessage.c:608-619`) resolves the
            // channel FIRST (`if(!pciu){logBadId;return}` — `logBadId`
            // sends an ECA_INTERNAL "Bad Resource ID" frame with a
            // cid=0xFFFFFFFF sentinel) and only THEN, if the type is
            // invalid, sends ECA_BADTYPE carrying the channel's real cid
            // + record name. So the deprecated-READ bad-type frame must
            // be gated on the channel existing: it is emitted below,
            // after the lookup, never with a `u32::MAX` sentinel here.
            // Otherwise an unknown SID + bad type drew a spurious
            // ECA_BADTYPE where C sends the bad-SID ECA_INTERNAL frame.
            //
            // `LAST_BUFFER_TYPE = 38` (caProto.h); request types above
            // that are not encodable.
            const LAST_BUFFER_TYPE: u16 = 38;
            if is_notify && requested_type > LAST_BUFFER_TYPE {
                return Err(epics_base_rs::error::CaError::Protocol(format!(
                    "READ_NOTIFY with unsupported DBR type {} > LAST_BUFFER_TYPE \
                     (matches C read_notify_action INVALID_DB_REQ RSRV_ERROR)",
                    requested_type
                )));
            }

            let entry = match state.channels.get(&sid) {
                Some(e) => e,
                None => {
                    // C `read_action` (camessage.c:608-610) and
                    // `read_notify_action` (700-703) bad-SID:
                    // `if (!pciu) { logBadId; return RSRV_ERROR; }`.
                    // `logBadId` (camessage.c:307-320) is NOT log-only —
                    // it calls `send_err(ECA_INTERNAL, "Bad Resource ID
                    // at %s.%d")`, buffering a CA_PROTO_ERROR frame that
                    // camsgtask.c:142 flushes ("flush any queued messages
                    // before shutdown") before the disconnect. Since
                    // `MPTOPCIU` returned NULL, `vsend_err` stamps
                    // cid=0xFFFFFFFF (camessage.c:163-167). So C emits one
                    // ECA_INTERNAL frame, then drops the connection.
                    send_ca_error(writer, hdr, ECA_INTERNAL, 0xFFFF_FFFF, "Bad Resource ID")
                        .await?;
                    return Err(epics_base_rs::error::CaError::Protocol(format!(
                        "READ on unknown SID {} (matches C read_action logBadId + RSRV_ERROR)",
                        sid
                    )));
                }
            };

            // Deprecated READ: C `read_action` (`rsrv/camessage.c:616-619`)
            // checks `INVALID_DB_REQ` AFTER resolving the channel and
            // BEFORE the access check, sending ECA_BADTYPE with the
            // channel's real cid + record name (`vsend_err` uses
            // `pciu->cid`). READ_NOTIFY already returned above (its type
            // check is pre-lookup and silent), so reaching here with a
            // bad type means the deprecated READ command.
            // `LAST_BUFFER_TYPE = 38`.
            if requested_type > LAST_BUFFER_TYPE {
                let audit_pv = match &entry.target {
                    ChannelTarget::SimplePv(pv) => pv.name.clone(),
                    ChannelTarget::RecordField { record, field } => {
                        format!("{}.{}", record.read().await.name, field)
                    }
                };
                send_ca_error(writer, hdr, ECA_BADTYPE, entry.cid, &audit_pv).await?;
                return Err(epics_base_rs::error::CaError::Protocol(format!(
                    "READ with unsupported DBR type {} > LAST_BUFFER_TYPE \
                     (matches C read_action INVALID_DB_REQ ECA_BADTYPE)",
                    requested_type
                )));
            }

            // Type-state:
            // `state.lookup_access(sid)` is the only path to the
            // access cache. `require_read()` returns a witness on
            // success and an `AccessDenied` carrying the matching
            // ECA code on failure — no `if access ==` ad-hoc
            // comparison, no missing-entry default to argue about.
            let _read_grant = match state.lookup_access(sid).require_read() {
                Ok(g) => g,
                Err(denied) => {
                    if is_notify {
                        // C `read_notify_action` →
                        // `read_reply` → `no_read_access_event`
                        // (`rsrv/camessage.c:450-480`) builds a
                        // CA_PROTO_READ_NOTIFY frame with the
                        // ORIGINAL requested count and a
                        // `dbr_size_n`-sized zero payload, abusing
                        // `m_cid` to carry the ECA status. Pre-fix
                        // Rust used `send_cmd_error` which always
                        // emits `count = 0` + zero-byte payload — a
                        // libca-style client validating callback
                        // metadata saw the wrong shape for the same
                        // no-read-access `caget` path. The helper
                        // mirrors the C wire format.
                        send_no_read_access_event(
                            writer,
                            CA_PROTO_READ_NOTIFY,
                            requested_type,
                            requested_count,
                            ioid,
                            denied.eca_code(),
                        )
                        .await?;
                    } else {
                        // C `read_action` (`rsrv/camessage.c:636-642`)
                        // sends `send_err(mp, ECA_NORDACCESS, client,
                        // RECORD_NAME(pciu->dbch))` — i.e.
                        // CA_PROTO_ERROR — for the deprecated
                        // CA_PROTO_READ on read denial. Pre-fix Rust
                        // silently returned, so a libca client saw a
                        // timeout instead of the C error callback.
                        // outer cid is `pciu->cid` per
                        // `vsend_err` (camessage.c:160-170).
                        let audit_pv = match &entry.target {
                            ChannelTarget::SimplePv(pv) => pv.name.clone(),
                            ChannelTarget::RecordField { record, field } => {
                                format!("{}.{}", record.read().await.name, field)
                            }
                        };
                        send_ca_error(writer, hdr, denied.eca_code(), entry.cid, &audit_pv).await?;
                    }
                    return Ok(());
                }
            };

            // GET path consults the target's optional read hook
            // (`get_read_snapshot`): a no-cache CA-gateway shadow PV
            // forwards this read to a fresh upstream fetch. An `Err` is
            // the forwarded upstream get failing — surface ECA_GETFAIL
            // to the client, the IOC get-callback error C ca-gateway
            // would propagate. READ_NOTIFY carries the status in its
            // reply frame; the deprecated READ uses the CA_PROTO_ERROR
            // channel like its read-denial path above.
            let snapshot = match get_read_snapshot(&entry.target).await {
                Ok(s) => s,
                Err(e) => {
                    tracing::debug!(error = %e, "ca server: read hook (no-cache get) failed");
                    if is_notify {
                        // C `read_reply` get-failure branch
                        // (`rsrv/camessage.c:548-562`): on
                        // `dbChannel_get_count() < 0` it keeps the
                        // CA_PROTO_READ_NOTIFY reply, abuses `m_cid` to
                        // carry ECA_GETFAIL, and commits a
                        // `dbr_size_n(type, count)` ZEROED body at the
                        // requested count (autosize `m_count==0` resets
                        // count to 0 and sizes `dbr_size_n(type, 0)`).
                        // Same abused-cid wire shape as the no-read-access
                        // frame, so it shares the builder below; the prior
                        // `send_cmd_error` emitted `count=0` + an empty
                        // body, which diverged from the C wire form.
                        send_no_read_access_event(
                            writer,
                            CA_PROTO_READ_NOTIFY,
                            requested_type,
                            requested_count,
                            ioid,
                            ECA_GETFAIL,
                        )
                        .await?;
                    } else {
                        let audit_pv = match &entry.target {
                            ChannelTarget::SimplePv(pv) => pv.name.clone(),
                            ChannelTarget::RecordField { record, field } => {
                                format!("{}.{}", record.read().await.name, field)
                            }
                        };
                        send_ca_error(writer, hdr, ECA_GETFAIL, entry.cid, &audit_pv).await?;
                    }
                    return Ok(());
                }
            };
            let Some(mut snapshot) = snapshot else {
                if is_notify {
                    // No snapshot (no-cache shadow PV with no upstream
                    // value): surface ECA_BADCHID through the same C
                    // `read_reply` abused-cid frame as the get-failure
                    // branch above — requested count + `dbr_size_n` zeroed
                    // body — not the prior `count=0`/empty `send_cmd_error`.
                    send_no_read_access_event(
                        writer,
                        CA_PROTO_READ_NOTIFY,
                        requested_type,
                        requested_count,
                        ioid,
                        ECA_BADCHID,
                    )
                    .await?;
                }
                return Ok(());
            };
            // run the channel filter chain on the read value
            // before DBR encoding. epics-base `dbChannelRunPreChain`
            // (db_access.c:160-167 / dbChannel.c:640-649) runs the same
            // pre-chain on a filtered read channel. `apply_to_read_value`
            // uses read context, so stream-only filters (`dec`/`sync`)
            // pass through while `arr`/`ts`/`dbnd` transform; an empty
            // chain (no suffix / malformed) is the identity. Applied
            // BEFORE the requested-count truncate so the client's `-#`
            // count caps the FILTERED result, matching C (arr slices
            // first, then the count limits).
            let read_chain = entry.filter_chain();
            if !read_chain.is_empty() {
                if let Some(v) = read_chain.apply_to_read_value(snapshot.value.clone()) {
                    snapshot.value = v;
                }
            }
            // convert String → CharArray of exactly 40 elements BEFORE the
            // requested-count clamp. C read_reply sizes the payload to
            // dbr_size_n(DBR_CHAR, request_count) after the channel reports
            // no_elements=40; the clamp must see the 40-element array so
            // `caget -# N PV.DESC$` trims to N chars (not the pre-convert
            // count of 1 that EpicsValue::String::count() returns).
            // `NativeString` is the inverse — a long-string record field
            // (printf/lsi/lso) decoded from its CHAR carrier to a scalar
            // string so plain access ships one DBR_STRING (C cvt_dbaddr).
            super::apply_long_string_mode(&mut snapshot, entry.long_string_mode);
            // Respect client's requested element count (e.g. caget -# 10)
            if requested_count > 0 && requested_count < snapshot.value.count() {
                snapshot.value.truncate(requested_count as usize);
            }

            // For DBR_STSACK_STRING populate ackt/acks from the record so
            // alarm-handler clients see the current acknowledge state.
            if requested_type == epics_base_rs::types::DBR_STSACK_STRING {
                if let ChannelTarget::RecordField { record, .. } = &entry.target {
                    let inst = record.read().await;
                    if let Some(EpicsValue::Short(v)) = inst.resolve_field("ACKT") {
                        snapshot.alarm.ackt = Some(v as u16);
                    }
                    if let Some(EpicsValue::Short(v)) = inst.resolve_field("ACKS") {
                        snapshot.alarm.acks = Some(v as u16);
                    }
                }
            }

            // For DBR_CLASS_NAME (38) substitute the record's recordType
            // into the response. SimplePv channels have no record-type
            // identity so they receive an empty string (which matches
            // what the C IOC does for in-process DBR_CLASS_NAME reads
            // against synthetic channels).
            if requested_type == epics_base_rs::types::DBR_CLASS_NAME {
                if let ChannelTarget::RecordField { record, .. } = &entry.target {
                    let inst = record.read().await;
                    snapshot.class_name = Some(inst.record.record_type().to_string());
                }
            }

            let data = match encode_dbr(requested_type, &snapshot) {
                Ok(d) => d,
                Err(_) => {
                    // C `read_action` (camessage.c:616-620) checks
                    // `INVALID_DB_REQ(m_dataType)` (type >
                    // LAST_BUFFER_TYPE = 38) BEFORE any DB lookup and
                    // returns `RSRV_ERROR` which tears the connection
                    // down. Other read-path failures (cas_copy_in_header
                    // budget, access denied, dbChannel_get, caNetConvert
                    // host-net) all return RSRV_OK and keep the
                    // connection — those don't apply here.
                    //
                    // Rust `encode_dbr` failure with `UnsupportedType`
                    // is the direct parallel of INVALID_DB_REQ —
                    // emit the error + drop the connection.
                    //
                    // C `read_notify_action`
                    // (`rsrv/camessage.c:693-697`) returns
                    // `RSRV_ERROR` on `INVALID_DB_REQ` WITHOUT
                    // emitting any wire frame — only the deprecated
                    // `read_action` (camessage.c:616-620) calls
                    // `send_err(ECA_BADTYPE)` here. Pre-fix Rust
                    // sent a CA_PROTO_READ_NOTIFY error frame for
                    // the notify path too, an extra wire frame
                    // before EOF that rsrv never produces. Mirror C:
                    // notify path is silent; only the deprecated
                    // READ path emits CA_PROTO_ERROR.
                    // outer cid is `pciu->cid`.
                    if !is_notify {
                        send_ca_error(writer, hdr, ECA_BADTYPE, entry.cid, "bad READ data type")
                            .await?;
                    }
                    return Err(epics_base_rs::error::CaError::Protocol(format!(
                        "READ with unsupported DBR type {} (matches C read_action RSRV_ERROR)",
                        requested_type
                    )));
                }
            };
            // C `read_reply` (`rsrv/camessage.c:507-571`) keeps
            // the request count in the header and zero-fills the
            // payload when fewer elements are returned than requested
            // (`autosize = mp->m_count == 0` is the exception:
            // request count 0 means "all available"; otherwise the
            // response carries the requested count and pads with
            // zeros). Pre-fix Rust dropped the requested count on
            // a short array, so a `ca_array_get_callback(type,
            // count > native, ...)` saw a shorter response from
            // Rust than from rsrv.
            let mut data = data;
            let actual_count = snapshot.value.count() as u32;
            // ORDER MATTERS: the deprecated-READ count==0 branch MUST
            // precede the DBR_CLASS_NAME normalization. C `read_action`
            // (rsrv/camessage.c:622-645) sizes EVERY type — including
            // DBR_CLASS_NAME — with `dbr_size_n(type, m_count)` and writes
            // the header count as `m_count` VERBATIM, with no class-name
            // special case. `dbr_size_n(DBR_CLASS_NAME, 0) = dbr_size[38]
            // - dbr_value_size[38] = 40 - 40 = 0`, so a deprecated READ of
            // DBR_CLASS_NAME at count==0 ships count=0 and a 0-byte
            // payload. Only the READ_NOTIFY / EVENT_ADD path (`read_reply`)
            // forces the fixed 40-byte class string at count 1 (CA-268).
            let element_count = if !is_notify && requested_count == 0 {
                // The deprecated synchronous CA_PROTO_READ (cmd 3) does
                // NOT treat m_count==0 as autosize. C `read_action`
                // (rsrv/camessage.c:622-645) sizes the reply with
                // `dbr_size_n(type, m_count)`, writes the header count as
                // `m_count`, and calls `dbChannel_get(.., m_count, ..)`
                // — all VERBATIM. Only `read_reply` (READ_NOTIFY /
                // EVENT_ADD, camessage.c:507-509) interprets m_count==0 as
                // "all available elements". So a deprecated READ with
                // count==0 must ship count=0 and a value-less payload of
                // `dbr_size_n(type, 0)` bytes == the type's metadata only
                // (0 bytes for a plain DBR type; the STS/TIME/GR/CTRL
                // header for a compound type, since `dbr_size_n(t,0)` ==
                // `dbr_size[t] - dbr_value_size[t]`). Pre-fix Rust shared
                // the autosize path for both opcodes and returned the full
                // native array with count=actual_native_count, diverging
                // from rsrv on both the wire count field and the payload
                // length.
                match epics_base_rs::types::native_type_for_dbr(requested_type) {
                    Ok(native) => {
                        // `dbr_buffer_size(.., 0)` equals `dbr_size_n(t, 0)`
                        // for every type EXCEPT DBR_CLASS_NAME, where it
                        // reports the fixed 40-byte string (the count>=1
                        // framing size) rather than `dbr_size_n(38,0)=0`.
                        // Use 0 for CLASS_NAME to match C's value-less
                        // count==0 payload.
                        let meta_size = if requested_type == epics_base_rs::types::DBR_CLASS_NAME {
                            0
                        } else {
                            epics_base_rs::types::dbr_buffer_size(requested_type, native, 0)
                        };
                        if data.len() > meta_size {
                            data.truncate(meta_size);
                        }
                        0
                    }
                    // Unreachable for a type that already encoded above
                    // (<= LAST_BUFFER_TYPE). If it ever weren't, fall back
                    // to the autosize sizing so the header count still
                    // matches the payload rather than shipping count=0
                    // with a value-bearing body.
                    Err(_) => pad_dbr_to_requested_count(
                        &mut data,
                        actual_count,
                        requested_count,
                        requested_type,
                    ),
                }
            } else if requested_type == epics_base_rs::types::DBR_CLASS_NAME {
                // CA-268: DBR_CLASS_NAME wire payload is always one fixed
                // 40-byte string. element_count must be 1 regardless of
                // the underlying record's value count — for waveform
                // records, snapshot.value.count() can be N, which would
                // make C clients parse 40 * N bytes of body and fail.
                // This applies to the READ_NOTIFY / EVENT_ADD path and to
                // ordinary deprecated reads with count!=0; the deprecated
                // count==0 case is handled above (C ships count=0).
                1
            } else {
                pad_dbr_to_requested_count(&mut data, actual_count, requested_count, requested_type)
            };
            // Deprecated CA_PROTO_READ (cmd 3) contracts a scalar
            // DBR_STRING payload to its NUL-terminated length before the
            // 8-byte alignment. C `read_action` (rsrv/camessage.c:666-680)
            // recomputes `payloadSize = epicsStrnLen(pStr, 40) + 1` for
            // `DBR_STRING && m_count == 1` when a NUL is found within the
            // 40-byte slot (otherwise it force-terminates byte 39 and keeps
            // the full 40), then `cas_commit_msg` (caserverio.c:350-365)
            // aligns the shortened size to 8 and rewrites m_postsize while
            // leaving the header count at 1. So `"OK"` commits an 8-byte
            // payload, not the fixed 40-byte slot. READ_NOTIFY / EVENT_ADD
            // never run this branch — C `read_reply` keeps the full slot —
            // so gate on `!is_notify`. `element_count == 1` is the scalar
            // case; arrays / count!=1 keep their full per-element slots.
            if !is_notify
                && requested_type == epics_base_rs::types::DBR_STRING
                && element_count == 1
            {
                // epicsStrnLen(pStr, 40): the first NUL index, capped at the
                // 40-byte slot. Trim to value + its NUL only when a NUL
                // exists within the slot; the encoder always NUL-bounds a
                // scalar string at <= 39 chars (value.rs to_bytes), so the
                // no-NUL else-branch C guards against cannot arise here and
                // the full 40-byte slot is kept untouched if it ever did.
                let slot = data.len().min(40);
                if let Some(nul) = data[..slot].iter().position(|&b| b == 0) {
                    data.truncate(nul + 1);
                }
            }
            let mut padded = data;
            padded.resize(align8(padded.len()), 0);

            // For deprecated CA_PROTO_READ (cmd=3), the response carries
            // the *client-side* CID (`pciu->cid` in C `read_action`
            // — `camessage.c:622-624` passes `pciu->cid`, NOT
            // `pciu->sid`, to `cas_copy_in_header`). Modern libca's
            // `readRespAction` demuxes by ioid (`m_available`) and
            // ignores `m_cid` for READ responses, but pre-3.14 clients
            // and stricter wire validators (Wireshark CA dissector,
            // packet-level fuzzers) cross-check the field. Notify
            // clients (cmd=15) get ECA_NORMAL since READ_NOTIFY's cid
            // slot carries status, not the channel CID.
            let mut resp = if is_notify {
                let mut r = CaHeader::new(CA_PROTO_READ_NOTIFY);
                r.cid = ECA_NORMAL;
                r
            } else {
                let mut r = CaHeader::new(CA_PROTO_READ);
                r.cid = entry.cid;
                r
            };
            // C client TCP parser requires 8-byte aligned postsize
            resp.set_payload_size(padded.len(), element_count);
            resp.data_type = requested_type;
            resp.available = ioid;

            // Abort-safety: a `send_timeout` cancel landing between a
            // separate header and payload `write_all` would leave an
            // orphan header in the shared BufWriter and mis-frame every
            // following message. Build the whole READ/READ_NOTIFY frame
            // as ONE contiguous buffer and issue a single `write_all`,
            // so a cancel can only land at a frame boundary. Same fix
            // already applied to the monitor path (`monitor.rs`).
            let hdr_bytes = resp.to_bytes_extended();
            let mut frame = Vec::with_capacity(hdr_bytes.len() + padded.len());
            frame.extend_from_slice(&hdr_bytes);
            frame.extend_from_slice(&padded);
            let mut w = writer.lock().await;
            w.write_all(&frame).await?;
            // flush deferred to handle_client outer loop (batched)
        }

        CA_PROTO_WRITE | CA_PROTO_WRITE_NOTIFY => {
            let sid = hdr.cid;
            let ioid = hdr.available;
            let is_notify = hdr.cmmd == CA_PROTO_WRITE_NOTIFY;

            // DBR_PUT_ACKT (35) and DBR_PUT_ACKS (36) are alarm-acknowledge
            // writes — payload is a single u16 routed to the record's
            // ACKT/ACKS field. Handle before the regular DbFieldType
            // dispatch so we don't reject the type as unsupported.
            if hdr.data_type == epics_base_rs::types::DBR_PUT_ACKT
                || hdr.data_type == epics_base_rs::types::DBR_PUT_ACKS
            {
                let entry = match state.channels.get(&sid) {
                    Some(e) => e,
                    None => {
                        // C `write_action` (camessage.c:736-738) +
                        // `write_notify_action` (camessage.c:1642-1645):
                        // `if (!pciu) { logBadId; return RSRV_ERROR; }`.
                        // `logBadId` emits an ECA_INTERNAL "Bad Resource
                        // ID" frame (cid=0xFFFFFFFF), flushed before the
                        // disconnect — same family as the EVENT_ADD bad-SID
                        // and the matching READ branch below.
                        send_ca_error(writer, hdr, ECA_INTERNAL, 0xFFFF_FFFF, "Bad Resource ID")
                            .await?;
                        return Err(epics_base_rs::error::CaError::Protocol(format!(
                            "WRITE (ACKT/ACKS) on unknown SID {} \
                             (matches C write_action logBadId + RSRV_ERROR)",
                            sid
                        )));
                    }
                };
                // Alarm-acknowledge PUTs travel
                // the same WRITE wire opcodes but pre-fix bypassed
                // the access_rights check that the regular WRITE
                // path performs below. ACKT/ACKS mutate alarm-handler
                // state — a `NoAccess` peer could silence alarms on
                // any record they could open. Mirror the regular
                // WRITE gate.
                // Type-state: alarm-ack PUTs go
                // through the same gate as regular WRITE. Token's
                // `require_write` returns the matching ECA code on
                // denial.
                let entry_cid = entry.cid;
                let _write_grant = match state.lookup_access(sid).require_write() {
                    Ok(g) => g,
                    Err(denied) => {
                        if is_notify {
                            send_put_notify_response(
                                writer,
                                hdr.data_type,
                                hdr.actual_count(),
                                denied.eca_code(),
                                ioid,
                            )
                            .await?;
                        } else {
                            // C `write_action` (`rsrv/camessage.c:741-751`)
                            // sends `send_err(mp, ECA_NOWTACCESS, client,
                            // RECORD_NAME(pciu->dbch))` even for the no-
                            // notify WRITE. DBR_PUT_ACKT/DBR_PUT_ACKS
                            // travel the same WRITE opcodes, so this
                            // branch covers alarm-acknowledge PUTs too.
                            // outer cid is `pciu->cid`.
                            let audit_pv = match &entry.target {
                                ChannelTarget::SimplePv(pv) => pv.name.clone(),
                                ChannelTarget::RecordField { record, field } => {
                                    format!("{}.{}", record.read().await.name, field)
                                }
                            };
                            send_ca_error(writer, hdr, denied.eca_code(), entry_cid, &audit_pv)
                                .await?;
                        }
                        return Ok(());
                    }
                };
                let value_u16 = if payload.len() >= 2 {
                    u16::from_be_bytes([payload[0], payload[1]])
                } else {
                    0
                };
                let field_name = if hdr.data_type == epics_base_rs::types::DBR_PUT_ACKT {
                    "ACKT"
                } else {
                    "ACKS"
                };
                // DBR_PUT_ACKT/ACKS WRITE_NOTIFY travels C
                // `write_notify_action`, so it shares the same
                // per-channel put-callback serialisation as a regular
                // WRITE_NOTIFY. Supersede any in-flight put-callback on
                // this channel *before* the alarm-ack side effect — C
                // cancels the previous `pPutNotify` and replies
                // ECA_PUTCBINPROG to the superseded request rather than
                // rejecting this one (`camessage.c:1660-1707`). The
                // alarm-ack completes synchronously, so it never installs
                // an entry of its own. The deprecated fire-and-forget
                // CA_PROTO_WRITE path is not serialised in C.
                if is_notify {
                    let prev = entry.put_notify_slot.take();
                    supersede_put_notify(prev, writer).await?;
                }
                let result = match &entry.target {
                    ChannelTarget::RecordField { record, .. } => {
                        let name = record.read().await.name.clone();
                        // Alarm-ack puts are immediate in C even for the
                        // notify variant — `rsrv/camessage.c` writes ACKT/
                        // ACKS via `dbPutField` and replies straight away,
                        // never building a putNotify. Neither mode here
                        // awaits a completion receiver, so park nothing.
                        db.put_record_field_from_ca_no_notify(
                            &name,
                            field_name,
                            EpicsValue::Short(value_u16 as i16),
                        )
                        .await
                    }
                    ChannelTarget::SimplePv(_) => Err(epics_base_rs::error::CaError::Protocol(
                        "PUT_ACKT/PUT_ACKS only valid on record-backed channels".to_string(),
                    )),
                };
                if is_notify {
                    let eca = match result {
                        Ok(()) => ECA_NORMAL,
                        Err(_) => ECA_PUTFAIL,
                    };
                    send_put_notify_response(writer, hdr.data_type, hdr.actual_count(), eca, ioid)
                        .await?;
                } else if let Err(e) = &result {
                    // deprecated CA_PROTO_WRITE for DBR_PUT_ACKT/
                    // DBR_PUT_ACKS must surface put failure via
                    // CA_PROTO_ERROR per C `write_action`
                    // (`rsrv/camessage.c:781-789`). Pre-fix the
                    // non-notify alarm-ack path silently swallowed
                    // record-side write errors so the libca peer never
                    // saw the failure.
                    let audit_pv = match &entry.target {
                        ChannelTarget::SimplePv(pv) => pv.name.clone(),
                        ChannelTarget::RecordField { record, field } => {
                            format!("{}.{}", record.read().await.name, field)
                        }
                    };
                    let eca = e.to_eca_status();
                    send_ca_error(writer, hdr, eca, entry_cid, &audit_pv).await?;
                }
                return Ok(());
            }

            // C `write_action` (`rsrv/camessage.c:735-739`) and
            // `write_notify_action` (`camessage.c:1641-1645`) call
            // `MPTOPCIU(mp)` BEFORE any DBR-type check, so a bad SID
            // path goes through `logBadId` + RSRV_ERROR — emitting the
            // ECA_INTERNAL "Bad Resource ID" frame (cid=0xFFFFFFFF)
            // regardless of whether the type is also invalid. Pre-fix
            // Rust ran the type check first and emitted an ECA_BADTYPE
            // error frame for the SID+type combo where rsrv sends the
            // bad-SID ECA_INTERNAL frame instead. Reorder to match C.
            let entry = match state.channels.get(&sid) {
                Some(e) => e,
                None => {
                    // Same C logBadId + RSRV_ERROR family as the
                    // ACKT/ACKS branch above and the READ branch: an
                    // ECA_INTERNAL "Bad Resource ID" frame (cid=0xFFFFFFFF)
                    // is buffered then flushed ahead of the disconnect.
                    send_ca_error(writer, hdr, ECA_INTERNAL, 0xFFFF_FFFF, "Bad Resource ID")
                        .await?;
                    return Err(epics_base_rs::error::CaError::Protocol(format!(
                        "WRITE on unknown SID {} (matches C write_action logBadId + RSRV_ERROR)",
                        sid
                    )));
                }
            };
            // channel-scoped CA_PROTO_ERROR replies must echo
            // `pciu->cid` (the CLIENT cid the libca peer allocated),
            // not the server-side SID we received in `hdr.cid`. C
            // `vsend_err` (`rsrv/camessage.c:160-170`) looks up the
            // `channel_in_use` and uses its `cid` field for the outer
            // error header. Captured here as a Copy so the error sites
            // below can use it after the `entry` borrow ends.
            let entry_cid = entry.cid;
            // Clone the per-channel put-callback slot (Arc-backed) so the
            // supersede gate and the async-completion install below use it
            // without holding the `entry` borrow across them.
            let put_notify_slot = entry.put_notify_slot.clone();

            // Resolve the audit-friendly PV name once. Cheap when audit
            // is off because state.audit() is a single None check.
            let audit_pv = match &entry.target {
                ChannelTarget::SimplePv(pv) => pv.name.clone(),
                ChannelTarget::RecordField { record, field } => {
                    format!("{}.{}", record.read().await.name, field)
                }
            };

            // The DBR-type gate and the write-access gate run in
            // OPPOSITE orders for the two write opcodes, and the order is
            // observable when BOTH fail: a bad type tears the connection
            // down (RSRV_ERROR), denied access keeps it (RSRV_OK), and
            // only the gate that runs FIRST reports its error.
            //
            // * `write_notify_action` (camessage.c:1647-1656): TYPE first
            //   (ECA_BADTYPE → RSRV_ERROR/drop), THEN access
            //   (ECA_NOWTACCESS → RSRV_OK/keep).
            // * `write_action` (camessage.c:741-766): ACCESS first
            //   (ECA_NOWTACCESS → RSRV_OK/keep). There is NO standalone
            //   type pre-check — the type is validated only by
            //   `caNetConvert` (camessage.c:753) AFTER access passes
            //   (ECA_BADTYPE → RSRV_ERROR/drop).
            //
            // So a deprecated CA_PROTO_WRITE carrying an unsupported DBR
            // type to a channel the peer cannot write must reply
            // ECA_NOWTACCESS and KEEP the connection — not ECA_BADTYPE +
            // drop. Pre-fix Rust ran the type gate first for both
            // opcodes, inverting `write_action`. Each gate's witness type
            // (`write_type`, `write_grant`) flows to the write below.
            //
            // A type-state WRITE gate: `lookup_access` is the only path
            // to the cache; the witness ensures the matching ECA code
            // reaches the wire.
            let (write_type, write_grant) = if is_notify {
                let write_type = match DbFieldType::from_u16(hdr.data_type) {
                    Ok(t) => t,
                    Err(_) => {
                        // C `putNotifyErrorReply` (camessage.c:1482-1501)
                        // preserves `m_dataType`/`m_count` from the
                        // request, then returns RSRV_ERROR (drop) — a
                        // peer sending an unsupported DBR has a corrupted
                        // dispatcher or is probing, so C drops.
                        send_put_notify_response(
                            writer,
                            hdr.data_type,
                            hdr.actual_count(),
                            ECA_BADTYPE,
                            ioid,
                        )
                        .await?;
                        return Err(epics_base_rs::error::CaError::Protocol(format!(
                            "WRITE_NOTIFY with unsupported DBR type {} (matches C write_notify_action RSRV_ERROR)",
                            hdr.data_type
                        )));
                    }
                };
                let write_grant = match state.lookup_access(sid).require_write() {
                    Ok(g) => g,
                    Err(denied) => {
                        // route through the refinement helper so
                        // large-array put-callbacks refused by ACF carry
                        // the extended-form count instead of the u16
                        // marker.
                        send_put_notify_response(
                            writer,
                            write_type as u16,
                            hdr.actual_count(),
                            denied.eca_code(),
                            ioid,
                        )
                        .await?;
                        state.audit("caput", &audit_pv, "", "denied").await;
                        return Ok(());
                    }
                };
                (write_type, write_grant)
            } else {
                // C `write_action` (camessage.c:741-750) emits
                // `send_err(mp, ECA_NOWTACCESS, ...)` and returns RSRV_OK
                // (keep) BEFORE any type handling. Without surfacing this
                // the Rust server dropped denied PROTO_WRITEs silently —
                // libca's `cac::exception` never fired, so a `caput` from
                // a read-only peer looked like it had succeeded even
                // though the value never reached the DB.
                let write_grant = match state.lookup_access(sid).require_write() {
                    Ok(g) => g,
                    Err(denied) => {
                        send_ca_error(writer, hdr, denied.eca_code(), entry_cid, &audit_pv).await?;
                        state.audit("caput", &audit_pv, "", "denied").await;
                        return Ok(());
                    }
                };
                // Type validated only after access passes (C
                // `caNetConvert`, camessage.c:753) — a bad type here is a
                // protocol violation → RSRV_ERROR/drop.
                let write_type = match DbFieldType::from_u16(hdr.data_type) {
                    Ok(t) => t,
                    Err(_) => {
                        send_ca_error(writer, hdr, ECA_BADTYPE, entry_cid, "bad data type").await?;
                        return Err(epics_base_rs::error::CaError::Protocol(format!(
                            "WRITE with unsupported DBR type {} (matches C write_action RSRV_ERROR)",
                            hdr.data_type
                        )));
                    }
                };
                (write_type, write_grant)
            };

            // the write-trap mask of the ACF rule that
            // authorised this write. C `asTrapWriteWithData`
            // (`rsrv/camessage.c:768-779`) consults
            // `pasgclient->trapMask` so a `NOTRAPWRITE` rule — or a
            // rule with no trap option — is not reported to
            // put-logging listeners. Pre-fix Rust hard-coded
            // `rule_was_trap: true` for every accepted write.
            let rule_was_trap = write_grant.rule_was_trap();

            // Supersede any in-flight put-callback on this channel here —
            // after the SID/type/access checks and *before* any side
            // effect (payload conversion, trap-write `BeforeWrite`
            // dispatch, the database/PV write, or the async device
            // kickoff). C `write_notify_action`
            // (`rsrv/camessage.c:1660-1707`) reaches this boundary —
            // after `rsrvCheckPut` and before `caNetConvert` /
            // `asTrapWriteWithData` / `dbProcessNotify` — with the
            // channel's previous `pPutNotify` either already completed or
            // cancelled (`dbNotifyCancel` + ECA_PUTCBINPROG to the
            // superseded request). It never rejects the new request.
            // `supersede_put_notify` does exactly that: it cancels the
            // prior put-callback's completion-wait and replies
            // ECA_PUTCBINPROG to the superseded ioid (when this path wins
            // the response-ownership race), then this put proceeds. The
            // deprecated fire-and-forget CA_PROTO_WRITE path is not
            // serialised in C, so it is left untouched.
            if is_notify {
                let prev = put_notify_slot.take();
                supersede_put_notify(prev, writer).await?;
            }

            let count = hdr.actual_count() as usize;
            // Echo the FULL 32-bit count
            // (`hdr.actual_count()`); pre-fix used `hdr.count`
            // which is the 0 marker for extended requests and
            // therefore lost the count on large array put-callbacks.
            let write_count = hdr.actual_count();
            let new_value = match EpicsValue::from_bytes_array(write_type, payload, count) {
                Ok(v) => v,
                Err(_) => {
                    // Same C parity rule as the data_type gate above:
                    // bad payload bytes (wrong length, malformed wire
                    // bytes) is a protocol violation → emit error +
                    // drop the connection. C `caNetConvert` failure
                    // in `write_action` returns RSRV_ERROR.
                    if is_notify {
                        // Same `putNotifyErrorReply` shape.
                        send_put_notify_response(
                            writer,
                            hdr.data_type,
                            hdr.actual_count(),
                            ECA_BADTYPE,
                            ioid,
                        )
                        .await?;
                    } else {
                        send_ca_error(
                            writer,
                            hdr,
                            ECA_BADTYPE,
                            entry_cid,
                            "bad WRITE payload bytes",
                        )
                        .await?;
                    }
                    return Err(epics_base_rs::error::CaError::Protocol(format!(
                        "WRITE payload conversion failed for type {} count {} (matches C caNetConvert RSRV_ERROR)",
                        hdr.data_type, count
                    )));
                }
            };

            // Stringify the value once for the audit log; skipped when
            // audit is off. Use the truncated renderer so a malicious
            // peer can't pin the dispatch task on `format!`-ing a
            // peer-controlled array of millions of elements.
            //
            // TRAPWRITE listeners also need a string form. We
            // render once when *either* audit or a trap-write listener
            // is registered; the truncated form is cheap and lets
            // listeners avoid touching the raw `EpicsValue`.
            let trap_listeners_active =
                epics_base_rs::server::access_security::has_trap_write_listeners();
            let display_value = if state.audit.is_some() || trap_listeners_active {
                new_value.display_truncated(64)
            } else {
                String::new()
            };

            // pair the matching Before/After of this put with a
            // monotonic event_id so listeners can correlate without
            // racing on (peer, pv).
            let trap_event_id = if trap_listeners_active {
                epics_base_rs::server::access_security::next_trap_write_event_id()
            } else {
                0
            };

            // BeforeWrite notification.
            // Pre-fix BeforeWrite fired unconditionally before the
            // put was attempted, so write_hook rejections (and
            // pre-storage record rejections inside
            // `put_record_field_from_ca`) generated Before+After=fail
            // pairs that C would have silenced. The dispatch still
            // sits here because the alternative — moving inside each
            // match arm — would over-narrow the bracket around the
            // actual storage call without removing the over-log
            // (RecordField pre-rejections happen inside the called
            // function; we can't disentangle pre-vs-post without a
            // refactor). The AfterWrite `status` is now carried as
            // a specific code string (see below) so listeners can
            // filter.
            if trap_listeners_active {
                epics_base_rs::server::access_security::dispatch_trap_write(
                    &epics_base_rs::server::access_security::TrapWriteMessage {
                        op: epics_base_rs::server::access_security::TrapWriteOp::BeforeWrite,
                        pv_name: &audit_pv,
                        user: &state.username,
                        host: &state.hostname,
                        peer: &state.peer,
                        value_str: &display_value,
                        dbr_type: write_type as u16,
                        no_elements: write_count,
                        event_id: trap_event_id,
                        status: None,
                        rule_was_trap,
                    },
                );
            }

            let write_result = match &entry.target {
                ChannelTarget::SimplePv(pv) => {
                    if let Some(hook) = pv.write_hook() {
                        let ctx = epics_base_rs::server::pv::WriteContext {
                            user: state.username.clone(),
                            host: state.hostname.clone(),
                            peer: state.peer.clone(),
                        };
                        hook(new_value, ctx).await.map(|()| None)
                    } else {
                        pv.set(new_value).await;
                        Ok(None)
                    }
                }
                ChannelTarget::RecordField { record, field } => {
                    let name = record.read().await.name.clone();
                    if is_notify {
                        db.put_record_field_from_ca(&name, field, new_value).await
                    } else {
                        // C `write_action` (`rsrv/camessage.c:781-789`)
                        // routes CA_PROTO_WRITE through `dbPutField` —
                        // no putNotify is ever built. Parking a wait-set
                        // whose receiver this fire-and-forget arm drops
                        // would occupy the record's notify slot until
                        // any async processing it starts settles (a
                        // motor's whole motion), failing every
                        // legitimate WRITE_NOTIFY on the record with
                        // ECA_PUTCBINPROG in the meantime.
                        db.put_record_field_from_ca_no_notify(&name, field, new_value)
                            .await
                            .map(|()| None)
                    }
                }
            };

            let audit_result = if write_result.is_ok() { "ok" } else { "fail" };
            state
                .audit("caput", &audit_pv, &display_value, audit_result)
                .await;

            // for the SYNCHRONOUS write paths (no async record
            // completion pending), dispatch AfterWrite immediately
            // with the now-known status. The async path defers
            // AfterWrite into the background task that awaits
            // `rx.await` so caPutLog sees real device-side completion
            // timing, matching `write_notify_reply:1400` semantics.
            let needs_async_after = is_notify && matches!(&write_result, Ok(Some(_)));
            if trap_listeners_active && !needs_async_after {
                epics_base_rs::server::access_security::dispatch_trap_write(
                    &epics_base_rs::server::access_security::TrapWriteMessage {
                        op: epics_base_rs::server::access_security::TrapWriteOp::AfterWrite,
                        pv_name: &audit_pv,
                        user: &state.username,
                        host: &state.hostname,
                        peer: &state.peer,
                        value_str: &display_value,
                        dbr_type: write_type as u16,
                        no_elements: write_count,
                        event_id: trap_event_id,
                        status: Some(audit_result),
                        rule_was_trap,
                    },
                );
            }

            // C `write_action` (`rsrv/camessage.c:781-789`):
            // even the deprecated fire-and-forget `CA_PROTO_WRITE`
            // surfaces a failed `dbChannel_put` to the client via
            // `send_err(mp, ECA_PUTFAIL, ...)`. Pre-fix Rust dropped
            // the failure silently for the non-notify path, so a
            // `caput` against a read-only-by-rule field that bypassed
            // earlier access checks (e.g. record-side `PutDisabled`)
            // looked successful to the libca peer even though the
            // value never reached the DB. is_notify already replies
            // via WRITE_NOTIFY below.
            if !is_notify {
                if let Err(e) = &write_result {
                    let eca = e.to_eca_status();
                    send_ca_error(writer, hdr, eca, entry_cid, &audit_pv).await?;
                }
            }

            // CA_PROTO_WRITE (cmd=4) is fire-and-forget — no response
            if is_notify {
                let eca_status = match &write_result {
                    Ok(_) => ECA_NORMAL,
                    Err(e) => e.to_eca_status(),
                };

                // If async processing started (e.g. motor move), spawn a
                // background task to await completion and send the response.
                // This avoids blocking the client handler loop, which would
                // freeze all camonitor subscriptions on this connection.
                let completion_rx: Option<tokio::sync::oneshot::Receiver<()>> =
                    write_result.unwrap_or_default();

                if let Some(rx) = completion_rx {
                    // This put-callback is now async (record processing is
                    // still running). Mint its response-ownership token:
                    // whichever of {this completion task, a superseding
                    // WRITE_NOTIFY} swaps `responded` to `true` first owns
                    // the single client reply, so the two can never both
                    // reply for this ioid. The handler installs the
                    // matching `InFlightPutNotify` into the channel slot
                    // after the spawn so a later WRITE_NOTIFY can supersede
                    // it (C `dbNotifyCancel` + ECA_PUTCBINPROG).
                    let responded = Arc::new(AtomicBool::new(false));
                    let responded_task = responded.clone();
                    let writer_c = writer.clone();
                    // snapshot the trap-dispatch inputs so the
                    // async task can fire AfterWrite at *real*
                    // completion time (matches C
                    // `write_notify_reply:1400` semantics: the after-
                    // hook fires from the extra-labor task after
                    // `dbProcessNotify` invokes
                    // `write_notify_done_callback`). Pre-fix Rust
                    // dispatched AfterWrite synchronously with
                    // `status=ok` the moment the put kicked off, so
                    // caPutLog measured latency=0 and never observed
                    // device-side PUTFAIL.
                    let trap_inputs = trap_listeners_active.then(|| {
                        (
                            audit_pv.clone(),
                            state.username.clone(),
                            state.hostname.clone(),
                            state.peer.clone(),
                            display_value.clone(),
                            write_type as u16,
                            write_count,
                            trap_event_id,
                            rule_was_trap,
                        )
                    });
                    let join = tokio::spawn(async move {
                        // Wait indefinitely for record processing to complete,
                        // matching C EPICS rsrv behavior. RecvError means the
                        // Sender was dropped without firing — typically because
                        // record processing aborted. Surface as ECA_PUTFAIL so
                        // the client doesn't observe a false success.
                        let final_status = match rx.await {
                            Ok(()) => eca_status,
                            Err(_) => ECA_PUTFAIL,
                        };

                        // Claim this put-callback's single reply. If a
                        // superseding WRITE_NOTIFY already won the race it
                        // sent ECA_PUTCBINPROG for this ioid and aborted
                        // this task; skip both the AfterWrite log and the
                        // reply so the client never sees two replies for
                        // one ioid.
                        if responded_task.swap(true, Ordering::AcqRel) {
                            return;
                        }

                        // dispatch AfterWrite NOW, after real
                        // device-side completion. `status` carries
                        // "ok" for ECA_NORMAL or the ECA-code form
                        // for anything else so listeners can filter
                        // failed puts.
                        if let Some((pv, user, host, peer, val, dbr, ne, ev_id, rule_was_trap)) =
                            trap_inputs
                        {
                            let status_s = if final_status == ECA_NORMAL {
                                "ok".to_string()
                            } else {
                                format!("eca:0x{:04x}", final_status)
                            };
                            epics_base_rs::server::access_security::dispatch_trap_write(
                                &epics_base_rs::server::access_security::TrapWriteMessage {
                                    op:
                                        epics_base_rs::server::access_security::TrapWriteOp::AfterWrite,
                                    pv_name: &pv,
                                    user: &user,
                                    host: &host,
                                    peer: &peer,
                                    value_str: &val,
                                    dbr_type: dbr,
                                    no_elements: ne,
                                    event_id: ev_id,
                                    status: Some(&status_s),
                                    rule_was_trap,
                                },
                            );
                        }

                        let _ = send_put_notify_response(
                            &writer_c,
                            write_type as u16,
                            write_count,
                            final_status,
                            ioid,
                        )
                        .await;
                        let mut w = writer_c.lock().await;
                        let _ = w.flush().await;
                        drop(w);
                    });
                    // Publish as the channel's in-flight put-callback so a
                    // later WRITE_NOTIFY on this channel supersedes it (C
                    // `dbNotifyCancel` + ECA_PUTCBINPROG). Replaces any
                    // stale completed entry the slot still held; that
                    // entry's `responded` is already `true`, so superseding
                    // it is a harmless no-op.
                    put_notify_slot.install(InFlightPutNotify {
                        abort: join.abort_handle(),
                        responded,
                        ioid,
                        dbr_type: write_type as u16,
                        count: write_count,
                    });
                    // Track for connection-scoped cleanup: a stuck
                    // async record would otherwise pin this task and the
                    // captured writer Arc forever after the client drops.
                    // Reap finished handles opportunistically so the Vec
                    // doesn't grow unbounded over a long-lived connection
                    // that issues many WRITE_NOTIFYs. The `sid` tag
                    // also lets `CA_PROTO_CLEAR_CHANNEL` drain only the
                    // tasks owned by the cleared channel (C parity:
                    // `rsrvFreePutNotify` per-channel cleanup).
                    state.write_notify_tasks.retain(|(_, h)| !h.is_finished());
                    state.write_notify_tasks.push((sid, join.abort_handle()));
                } else {
                    // Synchronous completion — respond immediately
                    send_put_notify_response(
                        writer,
                        write_type as u16,
                        write_count,
                        eca_status,
                        ioid,
                    )
                    .await?;
                }
            }
        }

        CA_PROTO_EVENT_ADD => {
            let sid = hdr.cid;
            let sub_id = hdr.available;
            let requested_type = hdr.data_type;
            // store the request's element count so each monitor
            // delivery and the EVENT_CANCEL ack can echo it (matches
            // C `event_add_action` capturing `pevext->msg` for later
            // `read_reply` / `event_cancel_reply` use).
            let requested_count = hdr.actual_count();

            // DoS guard: cap subscriptions per channel. Default-unbounded
            // (`None`) — C `event_add_action` imposes no per-channel
            // subscription count limit (see `max_subs_per_channel`). The
            // O(n) count is only paid when an opt-in cap is configured.
            if let Some(cap) = max_subs_per_channel() {
                let subs_for_channel = state
                    .subscriptions
                    .values()
                    .filter(|s| s.channel_sid == sid)
                    .count();
                if subs_for_channel >= cap {
                    // C `event_add_action` sends admission
                    // failures through `send_err(ECA_ALLOCMEM, ...)`
                    // i.e. CA_PROTO_ERROR — libca's
                    // `cac::eventRespAction` returns immediately for
                    // zero-payload EVENT_ADD because that shape is the
                    // historical cancel-confirmation no-op. Pre-fix
                    // Rust used `send_cmd_error` which emits zero-
                    // payload EVENT_ADD, so a libca client treated the
                    // refusal as a cancel ack and waited forever for
                    // monitor updates that never arrived. Use
                    // CA_PROTO_ERROR so the exception path fires.
                    let entry_cid = state.channels.get(&sid).map(|e| e.cid).unwrap_or(u32::MAX);
                    send_ca_error(
                        writer,
                        hdr,
                        ECA_ALLOCMEM,
                        entry_cid,
                        "EVENT_ADD refused: per-channel subscription cap",
                    )
                    .await?;
                    return Ok(());
                }
            }

            let native_type = match native_type_for_dbr(requested_type) {
                Ok(t) => t,
                Err(_) => {
                    // C `event_add_action` (camessage.c:1769-1771):
                    // `INVALID_DB_REQ` (data_type > LAST_BUFFER_TYPE = 38)
                    // returns RSRV_ERROR with NO error reply — the
                    // connection just drops. Unlike WRITE / READ where
                    // C emits CA_PROTO_ERROR + drops, EVENT_ADD is
                    // silent. Match that wire shape: no send, just
                    // disconnect. Clients see EOF without an ECA hint;
                    // this matches C IOC behaviour exactly.
                    return Err(epics_base_rs::error::CaError::Protocol(format!(
                        "EVENT_ADD with unsupported DBR type {} (matches C event_add_action silent drop)",
                        requested_type
                    )));
                }
            };

            let mask = if payload.len() >= 14 {
                u16::from_be_bytes([payload[12], payload[13]])
            } else {
                DBE_VALUE | DBE_ALARM
            };
            let entry = match state.channels.get(&sid) {
                Some(e) => e,
                None => {
                    // C `event_add_action` (camessage.c:1773-1777):
                    // `logBadId` + RSRV_ERROR on missing channel.
                    // `logBadId` emits an ECA_INTERNAL "Bad Resource ID"
                    // frame (cid=0xFFFFFFFF) before the disconnect — the
                    // genuinely-silent EVENT_ADD path is only the
                    // pre-lookup INVALID_DB_REQ (bad-TYPE) branch above,
                    // which returns RSRV_ERROR with no send. This MUST run
                    // before the mask==0 ALLOCMEM check below: in C the
                    // missing-channel branch precedes the `db_add_event`
                    // NULL (select==0) path, so an unknown SID draws the
                    // ECA_INTERNAL frame regardless of mask.
                    send_ca_error(writer, hdr, ECA_INTERNAL, 0xFFFF_FFFF, "Bad Resource ID")
                        .await?;
                    return Err(epics_base_rs::error::CaError::Protocol(format!(
                        "EVENT_ADD on unknown SID {} (matches C event_add_action logBadId + RSRV_ERROR)",
                        sid
                    )));
                }
            };

            // C `db_add_event` (dbEvent.c:437-439) returns NULL when
            // `select == 0 || select > UCHAR_MAX`, which propagates as
            // ECA_ALLOCMEM + disconnect (`camessage.c:1814-1822`). A zero mask
            // installs a subscription that never triggers; a mask above
            // UCHAR_MAX (the CA wire mask is a `u16`, so 256..=65535 is
            // reachable) is not a valid event select. Reject both immediately.
            // This is the `db_add_event` NULL path, which in C only runs for
            // a *valid* channel (after the missing-channel check above), so
            // `entry.cid` is always known here — no `u32::MAX` fallback.
            if mask == 0 || mask > u16::from(u8::MAX) {
                let entry_cid = entry.cid;
                send_ca_error(
                    writer,
                    hdr,
                    ECA_ALLOCMEM,
                    entry_cid,
                    &format!("EVENT_ADD invalid mask {mask}: must be 1..={}", u8::MAX),
                )
                .await?;
                return Err(epics_base_rs::error::CaError::Protocol(
                    "EVENT_ADD invalid mask (matches C db_add_event select==0 || select>UCHAR_MAX + RSRV_ERROR)".into(),
                ));
            }
            // Captured up front so the SubscriptionOpened event we
            // emit after a successful insert below doesn't have to
            // re-borrow `state.channels` (the insert path mutates
            // `state.subscriptions` so the entry borrow has to be
            // released before then).
            let sub_pv_name = entry.pv_name.clone();
            let long_string_mode = entry.long_string_mode;

            // EVENT_ADD must also consult the
            // channel's access_rights. A NoAccess peer mounting a
            // subscription would receive every value update —
            // identical leak to the `subscribe_raw` ACF
            // bypass on the PVA side. C IOC's `event_add_NoAccess`
            // returns ECA_NORDACCESS for the same reason.
            // Type-state EVENT_ADD gate. This closed the
            // missing per-op check; the typed `require_read` shape
            // is the path every future MONITOR-class op should
            // mirror.
            // C `event_add_action` (`rsrv/camessage.c:1762-1880`)
            // installs the event unconditionally and conditionally
            // enables it via `db_event_enable` only when
            // `asCheckGet(pciu->asClientPVT)` allows reads; on no-read
            // access the subscription stays installed but disabled
            // and the initial event is `no_read_access_event`. Pre-fix
            // Rust returned `ECA_NORDACCESS` here without installing —
            // a subscription opened while denied was permanently
            // absent, so a later ACF reload that granted access could
            // not re-arm anything. Capture access as a flag and let
            // the install path below populate the `denied` gate so
            // `reeval_access_rights` can flip it later (Bug 4 parity).
            let access_denied = state.lookup_access(sid).require_read().is_err();

            // Refuse a duplicate sub_id on the same connection. Without
            // this, two EVENT_ADDs with identical sub_id leave both
            // subscribers attached to the producer (push without
            // dedup); EVENT_CANCEL strips both at once via retain, but
            // until then every event delivery emits two wire frames —
            // archived data + dashboard counts duplicated.
            if state.subscriptions.contains_key(&sub_id) {
                tracing::warn!(
                    sub_id,
                    "EVENT_ADD refused: sub_id already in use on this connection"
                );
                // use CA_PROTO_ERROR (libca exception path)
                // instead of zero-payload EVENT_ADD which
                // `cac::eventRespAction` treats as a cancel-ack
                // no-op. The libca peer
                // otherwise silently swallows the refusal and
                // waits forever for monitor updates.
                send_ca_error(writer, hdr, ECA_BADMONID, entry.cid, "duplicate sub_id").await?;
                return Ok(());
            }
            {
                match &entry.target {
                    ChannelTarget::SimplePv(pv) => {
                        let rx_opt = pv.add_subscriber(sub_id, native_type, mask).await;
                        let Some(rx) = rx_opt else {
                            // per-PV subscriber cap reached.
                            // Previously dropped silently
                            // (let the client time out). Now sends
                            // ECA_ALLOCMEM so the client surfaces the
                            // refusal immediately and can fall back to
                            // a different transport, retry strategy,
                            // or operator alert. Mirrors the
                            // already-existing per-channel-cap response
                            // a few lines above — same ECA code, same
                            // shape.
                            tracing::warn!(
                                pv = %pv.name,
                                sub_id,
                                "EVENT_ADD refused: PV subscriber cap reached"
                            );
                            // CA_PROTO_ERROR for the
                            // admission failure (see comment above
                            // on the per-channel cap branch).
                            send_ca_error(
                                writer,
                                hdr,
                                ECA_ALLOCMEM,
                                entry.cid,
                                "EVENT_ADD refused: per-PV subscriber cap",
                            )
                            .await?;
                            return Ok(());
                        };

                        // attach the channel filter chain to the
                        // just-added SimplePv subscriber so update delivery
                        // (`ProcessVariable::notify_subscribers`) runs the
                        // SAME chain as a record-field monitor. Pre-fix a
                        // `SimplePv` monitor on a `.{...}` channel always
                        // used the empty default chain — the filter suffix
                        // was ignored entirely. Symmetric with the
                        // record-field `attach_filter_to_last_subscriber`
                        // path below; both source the chain from the single
                        // `ChannelEntry::filter_chain` owner.
                        pv.attach_filters_to_subscriber(sub_id, entry.filter_chain())
                            .await;

                        let denied = Arc::new(AtomicBool::new(access_denied));
                        // initial event is the snapshot when read
                        // access is granted, `no_read_access_event` when
                        // denied (C `event_add_action` → `read_reply`
                        // routes denial through `no_read_access_event`,
                        // `rsrv/camessage.c:529-534`).
                        if access_denied {
                            // an autosize (`count == 0`) request
                            // must be normalised to the target's live
                            // element count before sizing the zero-
                            // filled denial payload. C `read_reply`
                            // (`camessage.c:507-509`) maps `m_count==0`
                            // to `paddr->no_elements`; the denial frame
                            // must match so it carries a nonzero DBR
                            // body. A zero-payload `CA_PROTO_EVENT_ADD`
                            // is indistinguishable from the historical
                            // cancel-ack no-op and is silently dropped
                            // by the client before the `ECA_NORDACCESS`
                            // status is read (`cac.cpp` eventRespAction
                            // returns on `m_postsize == 0`).
                            // C calls `db_post_single_event`
                            // unconditionally at monitor creation
                            // (`camessage.c:1853`, BEFORE the access
                            // check at 1858), so even the initial
                            // DENIED post runs through the event-context
                            // pre-chain; the ECA_NORDACCESS frame is
                            // gated by it (`db_queue_event_log` fires
                            // only `if(pLog)`). Skip the frame when the
                            // chain drops the post — the subscription is
                            // still registered below.
                            let snap = pv.snapshot().await;
                            if entry
                                .filter_chain()
                                .apply_to_event_value(snap.value.clone())
                                .is_some()
                            {
                                let denied_count =
                                    no_read_access_count(requested_count, snap.value.count());
                                send_no_read_access_event(
                                    writer,
                                    CA_PROTO_EVENT_ADD,
                                    requested_type,
                                    denied_count,
                                    sub_id,
                                    ECA_NORDACCESS,
                                )
                                .await?;
                            }
                        } else {
                            let mut snap = pv.snapshot().await;
                            // the initial monitor event is a
                            // CA monitor single-event post (C
                            // `db_post_single_event` →
                            // `db_create_event_log` with
                            // `dbfl_context_event`), NOT a one-shot
                            // read. Run the EVENT-context chain
                            // (`dec`/`sync` DO decimate/gate, unlike
                            // `READ`) on a fresh throwaway chain so the
                            // subscriber's attached chain state stays
                            // isolated (`dbnd` baseline / `dec`
                            // counter). `None` means the chain dropped
                            // the post (C `db_queue_event_log` fires
                            // only `if(pLog)`), so send no initial
                            // frame — never fall back to the unfiltered
                            // value.
                            let init_chain = entry.filter_chain();
                            match init_chain.apply_to_event_value(snap.value.clone()) {
                                Some(v) => {
                                    snap.value = v;
                                    // long-string boundary conversion
                                    // (`$` → CHAR[40], or native record field
                                    // → scalar DBR_STRING); no-op otherwise.
                                    super::apply_long_string_mode(&mut snap, long_string_mode);
                                    // the initial event honours
                                    // the EVENT_ADD request count for
                                    // BOTH directions —
                                    // `send_monitor_snapshot` now pads
                                    // when `requested_count` exceeds
                                    // the live element count and
                                    // truncates when it is smaller, via
                                    // `pad_dbr_to_requested_count` (C
                                    // `read_reply` parity). The
                                    // producer task already
                                    // pads/truncates future updates
                                    // through the same helper, so the
                                    // initial frame and later frames
                                    // now share one shape.
                                    send_monitor_snapshot(
                                        writer,
                                        sub_id,
                                        requested_type,
                                        requested_count,
                                        &snap,
                                    )
                                    .await?;
                                    // Initial subscription value — C posts
                                    // it via `db_post_single_event` at
                                    // monitor creation (`camessage.c:1853`),
                                    // so it counts as one posted and one
                                    // processed subscription event (PCAS
                                    // parity). Future updates flow through
                                    // the monitor task below.
                                    if let Some(ref s) = state.stats {
                                        s.subscription_events_posted
                                            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                                        s.subscription_events_processed
                                            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                                    }
                                }
                                None => {}
                            }
                        }

                        let task = spawn_monitor_sender(
                            pv.clone(),
                            sub_id,
                            requested_type,
                            requested_count,
                            writer.clone(),
                            state.flow_control.clone(),
                            rx,
                            denied.clone(),
                            long_string_mode,
                            state.stats.clone(),
                        );

                        state.subscriptions.insert(
                            sub_id,
                            SubscriptionEntry {
                                target: ChannelTarget::SimplePv(pv.clone()),
                                channel_sid: sid,
                                sub_id,
                                data_type: requested_type,
                                data_count: requested_count,
                                denied,
                                task,
                                long_string_mode,
                            },
                        );
                        if let Some(tx) = conn_events {
                            let _ = tx.send(ServerConnectionEvent::SubscriptionOpened {
                                peer,
                                pv_name: sub_pv_name.clone(),
                                sub_id,
                                mask,
                            });
                        }
                    }
                    ChannelTarget::RecordField { record, field } => {
                        let mut instance = record.write().await;
                        let Some(rx) = instance.add_subscriber(field, sub_id, native_type, mask)
                        else {
                            // record-field subscriber cap reached.
                            // Symmetric with the SimplePv path; send
                            // ECA_ALLOCMEM so the client surfaces the
                            // refusal instead of timing out silently.
                            tracing::warn!(
                                record = %instance.name,
                                field = %field,
                                sub_id,
                                "EVENT_ADD refused: record-field subscriber cap reached"
                            );
                            drop(instance);
                            // CA_PROTO_ERROR for admission
                            // failure (libca's eventRespAction
                            // treats zero-payload EVENT_ADD as a
                            // cancel ack, so the prior
                            // send_cmd_error path silently lost).
                            send_ca_error(
                                writer,
                                hdr,
                                ECA_ALLOCMEM,
                                entry.cid,
                                "EVENT_ADD refused: record-field subscriber cap",
                            )
                            .await?;
                            return Ok(());
                        };

                        // epics-base 3.15.7 channel filter — attach the
                        // chain (parsed via the single
                        // `ChannelEntry::filter_chain` owner, the same one
                        // the READ path and the SimplePv monitor now use)
                        // to the just-registered subscriber. The parser is
                        // permissive: malformed JSON or unknown filters
                        // degrade gracefully to an empty chain with a
                        // tracing::warn!, so an empty chain is a no-op loop.
                        for filt in entry.filter_chain().iter() {
                            instance.attach_filter_to_last_subscriber(field, filt.clone());
                        }

                        // snapshot when read access granted,
                        // no_read_access_event when denied. Drop the
                        // instance write lock before await on the
                        // writer so the producer task can pick it up.
                        //
                        // even on the denied path we must read
                        // the field's live element count under the
                        // lock, so an autosize (`count == 0`) denial
                        // frame can be sized to a nonzero DBR body
                        // instead of the zero-payload cancel-ack shape.
                        let initial_snap = if access_denied {
                            None
                        } else {
                            instance.snapshot_for_field(field).and_then(|mut snap| {
                                if requested_type == epics_base_rs::types::DBR_CLASS_NAME {
                                    snap.class_name =
                                        Some(instance.record.record_type().to_string());
                                }
                                // the initial record-field monitor
                                // event is an EVENT-context single-event
                                // post (see the SimplePv branch) — run the
                                // event-context chain (`dec`/`sync` apply)
                                // on a fresh throwaway chain so the
                                // subscriber's attached chain state stays
                                // isolated. `None` means the chain dropped
                                // the post (C `db_queue_event_log` fires
                                // only `if(pLog)`); fold it through so the
                                // send below is skipped — never fall back
                                // to the unfiltered value.
                                let init_chain = entry.filter_chain();
                                match init_chain.apply_to_event_value(snap.value.clone()) {
                                    Some(v) => {
                                        snap.value = v;
                                        // long-string boundary conversion
                                        // (`$` → CHAR[40], or native record
                                        // field → scalar DBR_STRING).
                                        super::apply_long_string_mode(&mut snap, long_string_mode);
                                        Some(snap)
                                    }
                                    None => None,
                                }
                            })
                        };
                        // Derive the field's element
                        // count for the autosize-denial frame AND run
                        // the event-context chain under the lock (the
                        // value is needed for both). `snapshot_for_field`
                        // is the same accessor the granted path uses, so
                        // the denial count matches what a granted monitor
                        // on the same field would carry. C
                        // `event_add_action` calls `db_post_single_event`
                        // unconditionally (`camessage.c:1853`, before the
                        // access check), so the DENIED initial post is
                        // gated by the event-context chain too:
                        // `Some(count)` => send the ECA_NORDACCESS frame,
                        // `None` => the chain dropped the post, send
                        // nothing. A missing field snapshot keeps the
                        // prior count=1 fallback (no value to filter).
                        let denied_event_count = if access_denied {
                            match instance.snapshot_for_field(field) {
                                Some(snap) => {
                                    let count = snap.value.count();
                                    entry
                                        .filter_chain()
                                        .apply_to_event_value(snap.value)
                                        .map(|_| count)
                                }
                                None => Some(1),
                            }
                        } else {
                            None
                        };
                        drop(instance);
                        if access_denied {
                            // normalise autosize before sizing
                            // the zero-filled denial payload. See the
                            // SimplePv branch above for the C
                            // `read_reply` (`camessage.c:507-509`)
                            // parity rationale.
                            if let Some(field_count) = denied_event_count {
                                let denied_count =
                                    no_read_access_count(requested_count, field_count);
                                send_no_read_access_event(
                                    writer,
                                    CA_PROTO_EVENT_ADD,
                                    requested_type,
                                    denied_count,
                                    sub_id,
                                    ECA_NORDACCESS,
                                )
                                .await?;
                            }
                        } else if let Some(snap) = initial_snap {
                            // initial event honours the
                            // EVENT_ADD request count in both
                            // directions — `send_monitor_snapshot`
                            // pads an over-requested count and
                            // truncates an under-requested one via
                            // `pad_dbr_to_requested_count`.
                            send_monitor_snapshot(
                                writer,
                                sub_id,
                                requested_type,
                                requested_count,
                                &snap,
                            )
                            .await?;
                            // Initial subscription value posted and
                            // processed (C `db_post_single_event` at
                            // monitor creation, `camessage.c:1853`); PCAS
                            // parity. Later updates flow through the
                            // monitor task below.
                            if let Some(ref s) = state.stats {
                                s.subscription_events_posted
                                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                                s.subscription_events_processed
                                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                            }
                        }

                        let writer_clone = writer.clone();
                        let flow_control = state.flow_control.clone();
                        let record_for_task = record.clone();
                        let denied = Arc::new(AtomicBool::new(access_denied));
                        let denied_for_task = denied.clone();
                        let stats_for_task = state.stats.clone();
                        let task = epics_base_rs::runtime::task::spawn(async move {
                            let mut rx = rx;
                            loop {
                                // Block on the queue front, then fold the
                                // producer's coalesce overflow slot. When the
                                // mpsc filled while we were busy the newest
                                // value is parked in the slot;
                                // `coalesce_consume` delivers it AND drains
                                // the now-stale queue tail, so delivery never
                                // steps from the newest value back to an older
                                // queued one. A set slot implies the queue was
                                // full, so the front `recv()` returns
                                // immediately — no added latency, no
                                // newest-then-old replay of the stale backlog.
                                let Some(queued) = rx.recv().await else {
                                    break;
                                };
                                let coalesced = record_for_task.read().await.pop_coalesced(sub_id);
                                let mut event = epics_base_rs::server::pv::coalesce_consume(
                                    &mut rx, queued, coalesced,
                                );
                                if flow_control.is_paused() {
                                    let Some(coalesced) = flow_control
                                        .coalesce_while_paused(&mut rx, event, || async {
                                            record_for_task.read().await.pop_coalesced(sub_id)
                                        })
                                        .await
                                    else {
                                        break;
                                    };
                                    event = coalesced;
                                }
                                // One subscription update committed for
                                // delivery this cycle (post-coalesce).
                                // PCAS `subscriptionEventsPosted` parity —
                                // counted before the read-access gate so a
                                // suppressed delivery reads as
                                // posted-but-not-processed, the same
                                // `serverPostRate` > `serverEventRate`
                                // divergence the gateway expects.
                                if let Some(ref s) = stats_for_task {
                                    s.subscription_events_posted.fetch_add(1, Ordering::Relaxed);
                                }
                                // C `casAccessRightsCB`
                                // (`rsrv/camessage.c:1080-1095`)
                                // suppresses delivery via
                                // `db_event_disable` while read access
                                // is denied, without tearing the
                                // subscription down. Producer task
                                // stays alive so a later re-enable
                                // resumes the same camonitor; drop
                                // the event here while denied.
                                if denied_for_task.load(Ordering::Acquire) {
                                    continue;
                                }
                                // CA-268 monitor parity: populate
                                // class_name on every emitted event so
                                // a `ca_create_subscription` against
                                // DBR_CLASS_NAME sees the record_type
                                // string instead of an empty 40-byte
                                // pad.
                                if requested_type == epics_base_rs::types::DBR_CLASS_NAME {
                                    event.snapshot.class_name = Some(
                                        record_for_task
                                            .read()
                                            .await
                                            .record
                                            .record_type()
                                            .to_string(),
                                    );
                                }
                                // long-string boundary conversion before
                                // encoding: `$` → CHAR[40]+NUL, or a native
                                // record field → scalar DBR_STRING.
                                super::apply_long_string_mode(
                                    &mut event.snapshot,
                                    long_string_mode,
                                );
                                let mut payload_bytes =
                                    match encode_dbr(requested_type, &event.snapshot) {
                                        Ok(bytes) => bytes,
                                        Err(_) => break,
                                    };
                                // CA-268: see GET path note — fixed 1.
                                //
                                // C `read_reply`
                                // (`rsrv/camessage.c:507-571`) uses the
                                // ORIGINAL request count as the header
                                // value (autosize=0 case) and pads the
                                // payload up to `dbr_size_n(type,
                                // request_count)`. Pre-fix Rust used
                                // the live `snapshot.value.count()`,
                                // so an EVENT_ADD with explicit
                                // `count=1` on a waveform received the
                                // full N-element waveform on every
                                // update instead of just one element.
                                let actual_count = event.snapshot.value.count() as u32;
                                let element_count =
                                    if requested_type == epics_base_rs::types::DBR_CLASS_NAME {
                                        1
                                    } else {
                                        pad_dbr_to_requested_count(
                                            &mut payload_bytes,
                                            actual_count,
                                            requested_count,
                                            requested_type,
                                        )
                                    };
                                let mut padded = payload_bytes;
                                padded.resize(align8(padded.len()), 0);

                                let mut hdr = CaHeader::new(CA_PROTO_EVENT_ADD);
                                // C client TCP parser requires 8-byte aligned postsize
                                hdr.set_payload_size(padded.len(), element_count);
                                hdr.data_type = requested_type;
                                hdr.cid = 1; // ECA_NORMAL
                                hdr.available = sub_id;

                                // Abort-safety: this monitor task can
                                // be `task.abort()`ed mid-flight by
                                // EVENT_CANCEL / CLEAR_CHANNEL /
                                // disconnect cleanup. Build the whole
                                // EVENT_ADD frame (header + padded
                                // payload) as ONE contiguous buffer and
                                // issue a single `write_all`, so an
                                // abort can only land at a frame
                                // boundary, never between header and
                                // payload — a split there would leave
                                // an orphan header in the shared
                                // BufWriter and mis-frame the stream.
                                let hdr_bytes = hdr.to_bytes_extended();
                                let mut frame = Vec::with_capacity(hdr_bytes.len() + padded.len());
                                frame.extend_from_slice(&hdr_bytes);
                                frame.extend_from_slice(&padded);
                                let mut w = writer_clone.lock().await;
                                if w.write_all(&frame).await.is_err() {
                                    break;
                                }
                                let _ = w.flush().await;
                                // Frame written to the client — PCAS
                                // `subscriptionEventsProcessed` parity
                                // (gateway `serverEventRate`).
                                if let Some(ref s) = stats_for_task {
                                    s.subscription_events_processed
                                        .fetch_add(1, Ordering::Relaxed);
                                }
                            }
                        });

                        state.subscriptions.insert(
                            sub_id,
                            SubscriptionEntry {
                                target: ChannelTarget::RecordField {
                                    record: record.clone(),
                                    field: field.clone(),
                                },
                                channel_sid: sid,
                                sub_id,
                                data_type: requested_type,
                                data_count: requested_count,
                                denied,
                                task,
                                long_string_mode,
                            },
                        );
                        if let Some(tx) = conn_events {
                            let _ = tx.send(ServerConnectionEvent::SubscriptionOpened {
                                peer,
                                pv_name: sub_pv_name.clone(),
                                sub_id,
                                mask,
                            });
                        }
                    }
                }
            }
        }

        CA_PROTO_EVENT_CANCEL => {
            let sub_id = hdr.available;
            let req_channel_sid = hdr.cid;
            // C `event_cancel_reply` (`camessage.c:1992-1996`)
            // calls `MPTOPCIU(mp)` first. If the request's channel id
            // is unknown or belongs to another client, rsrv calls
            // `logBadId` — which sends an ECA_INTERNAL "Bad Resource ID"
            // frame (cid=0xFFFFFFFF), flushed before the disconnect —
            // and returns RSRV_ERROR. Only after a valid channel resolves
            // does rsrv walk that channel's event queue and emit
            // ECA_BADMONID for an unknown monitor id.
            //
            // Pre-fix Rust checked the flat subscription map first,
            // so an unknown SID elicited ECA_BADMONID (the diagnostic
            // path that resolves a fallback PV name for the bad-SID
            // case). Mirror C: ECA_INTERNAL frame + close on bad SID;
            // ECA_BADMONID only when SID is good but sub-id doesn't belong.
            let (entry_cid, entry_pv_name) = match state.channels.get(&req_channel_sid) {
                Some(entry) => (entry.cid, entry.pv_name.clone()),
                None => {
                    send_ca_error(writer, hdr, ECA_INTERNAL, 0xFFFF_FFFF, "Bad Resource ID")
                        .await?;
                    return Err(epics_base_rs::error::CaError::Protocol(format!(
                        "EVENT_CANCEL on unknown SID {} (matches C event_cancel_reply \
                         logBadId + RSRV_ERROR)",
                        req_channel_sid
                    )));
                }
            };
            // C `event_cancel_reply` (camessage.c:2002-2010) walks
            // the CHANNEL's eventq looking for a matching sub-id.
            // The cross-check is implicit: a sub-id that exists but
            // belongs to a different channel is "not found on this
            // channel" and falls through to the ECA_BADMONID +
            // RSRV_ERROR path. Rust's `state.subscriptions` is a
            // flat HashMap by sub-id; we have to add the
            // cross-check explicitly. If we skipped it, a peer
            // could send EVENT_CANCEL with wrong cid but valid
            // sub-id and erase a real subscription bound to a
            // different channel — bypass of the BAD-MONID
            // disconnect.
            let channel_matches = state
                .subscriptions
                .get(&sub_id)
                .is_some_and(|s| s.channel_sid == req_channel_sid);
            if !channel_matches {
                // Trigger the BAD-MONID path: emit
                // ECA_BADMONID + disconnect. The SID is known to be
                // valid here (silent close already happened above),
                // so use entry_cid / entry_pv_name resolved from it.
                tracing::debug!(
                    sub_id,
                    sid = req_channel_sid,
                    "EVENT_CANCEL channel-mismatch (sub belongs to different channel); ECA_BADMONID"
                );
                send_ca_error(writer, hdr, ECA_BADMONID, entry_cid, &entry_pv_name).await?;
                return Err(epics_base_rs::error::CaError::Protocol(format!(
                    "EVENT_CANCEL sub-id {} channel-mismatch (requested sid {}; \
                     matches C event_cancel_reply 'not on this channel's eventq' RSRV_ERROR)",
                    sub_id, req_channel_sid
                )));
            }
            if let Some(sub) = state.subscriptions.remove(&sub_id) {
                sub.task.abort();
                // Resolve pv_name for the SubscriptionClosed event.
                // Look up via the subscription's channel_sid; if the
                // channel was already cleared, fall back to an empty
                // string (the event still increments the counter).
                let pv_name_for_event = state
                    .channels
                    .get(&sub.channel_sid)
                    .map(|e| e.pv_name.clone())
                    .unwrap_or_default();
                match &sub.target {
                    ChannelTarget::SimplePv(pv) => {
                        pv.remove_subscriber(sub.sub_id).await;
                    }
                    ChannelTarget::RecordField { record, .. } => {
                        record.write().await.remove_subscriber(sub.sub_id);
                    }
                }
                if let Some(tx) = conn_events {
                    let _ = tx.send(ServerConnectionEvent::SubscriptionClosed {
                        peer,
                        pv_name: pv_name_for_event,
                        sub_id,
                    });
                }

                // C `event_cancel_reply`
                // (`camessage.c:2002-2014`) calls cas_copy_in_header
                // with `pevext->msg.m_dataType`, `pevext->msg.m_count`,
                // `pevext->msg.m_cid` (the SID stored on the original
                // EVENT_ADD), and `pevext->msg.m_available`. Pre-fix
                // Rust truncated the count to u16 (losing extended-
                // form counts >= 0xFFFF) and used ECA_NORMAL in
                // m_cid instead of the stored SID. Use
                // `set_payload_size` with `to_bytes_extended` so
                // large counts get the extended annex, and echo
                // `sub.channel_sid` as the m_cid field.
                let mut resp = CaHeader::new(CA_PROTO_EVENT_ADD);
                resp.data_type = sub.data_type;
                resp.set_payload_size(0, sub.data_count);
                resp.cid = sub.channel_sid;
                resp.available = sub_id;
                let mut w = writer.lock().await;
                w.write_all(&resp.to_bytes_extended()).await?;
                // flush deferred to handle_client outer loop (batched)
            } else {
                // C `event_cancel_reply` (`camessage.c:1998-2021`):
                // when the sub-id (m_available of the request) does
                // not match any active subscription on the addressed
                // channel, send `send_err(ECA_BADMONID,
                // RECORD_NAME(pciu->dbch))`. The previous Rust
                // behaviour was a silent ignore, leaving libca-driven
                // tools that race a CLEAR_CHANNEL against an
                // EVENT_CANCEL with a stale sub-id waiting for an
                // exception that never arrives (the stale request
                // was discarded).
                //
                // The diagnostic string uses the resolved PV name
                // when the m_cid in the request still maps to a
                // channel; otherwise we fall back to "unknown"
                // (matches C, which would log via `logBadId` and
                // return RSRV_ERROR — we degrade to a NORMAL reply
                // path with a descriptive diag).
                let req_sid = hdr.cid;
                let (chan_cid, diag) = match state.channels.get(&req_sid) {
                    Some(entry) => (entry.cid, entry.pv_name.clone()),
                    None => (0xFFFF_FFFFu32, "unknown".to_string()),
                };
                tracing::debug!(
                    sub_id,
                    sid = req_sid,
                    "EVENT_CANCEL for unknown sub-id; replying ECA_BADMONID"
                );
                send_ca_error(writer, hdr, ECA_BADMONID, chan_cid, &diag).await?;
                // C `event_cancel_reply` (camessage.c:2016-2021):
                // after `send_err(ECA_BADMONID)`, return RSRV_ERROR
                // which tears the connection down. Pre-fix Rust kept
                // the connection; a peer racing CLEAR_CHANNEL against
                // EVENT_CANCEL on the same sub-id could spam the
                // server with stale cancels indefinitely.
                return Err(epics_base_rs::error::CaError::Protocol(format!(
                    "EVENT_CANCEL for unknown sub-id {} \
                     (matches C event_cancel_reply ECA_BADMONID + RSRV_ERROR)",
                    sub_id
                )));
            }
        }

        CA_PROTO_EVENTS_OFF | CA_PROTO_EVENTS_ON => {
            if hdr.cmmd == CA_PROTO_EVENTS_OFF {
                state.flow_control.pause();
            } else {
                state.flow_control.resume();
            }
        }

        CA_PROTO_READ_SYNC => {
            // C `read_sync_reply` (camessage.c:2053-2067): server
            // echoes the request header back with cmmd=CA_PROTO_READ_SYNC,
            // m_postsize=0, and the request's m_dataType / m_count /
            // m_cid / m_available preserved. libca client treats this
            // as ECHO (`cac.cpp:72-73`: "legacy READ_SYNC used as
            // echo with legacy server" — dispatched through
            // echoRespAction). Without the reply, a client using
            // READ_SYNC as a keepalive probe (legacy V3 / pre-V4.3
            // protocol behavior) sees no response and may trigger
            // its connection-timeout watchdog.
            //
            // The outer batched flush still fires, so any prior queued
            // responses ship along with this echo — preserving the
            // barrier semantic. Pre-fix Rust silently no-op-ed; this
            // restores wire parity.
            let mut resp = CaHeader::new(CA_PROTO_READ_SYNC);
            resp.data_type = hdr.data_type;
            resp.count = hdr.count;
            resp.cid = hdr.cid;
            resp.available = hdr.available;
            let mut w = writer.lock().await;
            w.write_all(&resp.to_bytes()).await?;
            // flush deferred to handle_client outer loop (batched)
        }

        CA_PROTO_ECHO => {
            // C `tcp_echo_action` (`rsrv/camessage.c:403-420`) echoes
            // the *full* request back to the client — same m_cmmd,
            // m_postsize, m_dataType, m_count, m_cid, m_available, and
            // the m_postsize-byte payload. Real clients (libca
            // `tcpiiu::echoRequest`) issue zero-payload echos with
            // every field zero, in which case our previous
            // `CaHeader::new(CA_PROTO_ECHO).to_bytes()` happened to be
            // byte-identical to C. But a diagnostic / probe client
            // that sends ECHO with a marker payload (e.g. to measure
            // RTT or to verify the server isn't a TCP transparent
            // proxy) gets a stripped, all-zero reply from us — wire
            // divergence that breaks the documented round-trip
            // semantics.
            let mut resp = CaHeader::new(CA_PROTO_ECHO);
            // Preserve the request fields. set_payload_size handles
            // both the short and extended encodings transparently.
            resp.data_type = hdr.data_type;
            resp.set_payload_size(hdr.actual_postsize(), hdr.actual_count());
            resp.cid = hdr.cid;
            resp.available = hdr.available;
            // Abort-safety: build header + echoed payload as ONE
            // contiguous frame and issue a single `write_all`, so a
            // `send_timeout` cancel cannot leave an orphan header
            // mid-frame in the shared BufWriter.
            let mut frame = Vec::new();
            if resp.is_extended() {
                frame.extend_from_slice(&resp.to_bytes_extended());
            } else {
                frame.extend_from_slice(&resp.to_bytes());
            }
            // Echo the payload back verbatim (truncated to the actual
            // postsize advertised by the request — `payload` here is
            // already that slice).
            frame.extend_from_slice(payload);
            let mut w = writer.lock().await;
            w.write_all(&frame).await?;
            // flush deferred to handle_client outer loop (batched)
        }

        CA_PROTO_SEARCH => {
            // C `search_reply_tcp` (camessage.c:2238-2241): if
            // `!CA_VSUPPORTED(m_count)` (minor < 4) the handler
            // returns RSRV_ERROR which tears the TCP connection
            // down. Note that the *UDP* SEARCH path returns RSRV_OK
            // on the same condition (silently skips the reply, no
            // datagram-level disconnect) — those two paths share
            // the version-check logic but differ in fatality.
            //
            // Pre-fix Rust silently `return Ok(())`-ed, keeping the
            // connection. A peer could spam unsupported-minor TCP
            // SEARCH frames indefinitely.
            if state.client_minor_version < 4 {
                return Err(epics_base_rs::error::CaError::Protocol(format!(
                    "TCP SEARCH from minor {} (< 4) — C search_reply_tcp RSRV_ERROR parity",
                    state.client_minor_version
                )));
            }
            // C `search_reply_tcp` (rsrv/camessage.c:2246) rejects
            // SEARCH whose `m_postsize <= 1` and silently returns
            // RSRV_OK. Mirror that here so an attacker's empty-name
            // SEARCH burst on an open TCP connection cannot drive
            // `db.has_name("")` per frame nor trigger a NOT_FOUND
            // amplification when CA_DO_REPLY is set.
            if hdr.postsize <= 1 {
                return Ok(());
            }
            // C `search_reply_tcp` forces NUL at postsize-1.
            let scan_end = payload.len().saturating_sub(1).max(0);
            let end = payload[..scan_end]
                .iter()
                .position(|&b| b == 0)
                .unwrap_or(scan_end);
            let pv_name = String::from_utf8_lossy(&payload[..end]).to_string();

            // Thread the connection peer into the existence check just
            // like TCP CREATE_CHANNEL (`find_entry_from(.., Some(peer))`)
            // and UDP SEARCH (`has_name_from(.., Some(src))`). Without it
            // the CA gateway resolver received `peer: None` and skipped
            // host-scoped `.pvlist` `DENY FROM host` admission, so a denied
            // host's TCP SEARCH could resolve (and lazily instantiate) a
            // PV the pvlist forbids — parity with C `pvExistTest` passing
            // the client host to `gateAs::findEntry`.
            if db.has_name_from(&pv_name, Some(peer)).await {
                // C parity: `search_reply_tcp`
                // (`rsrv/camessage.c:2229-2287`) sends:
                //   m_postsize  = 0  (no payload — TCP search reply
                //                 carries no minor-version trailer,
                //                 unlike UDP)
                //   m_dataType  = ca_server_port (carries the port)
                //   m_count     = 0
                //   m_cid       = ~0U (INADDR_BROADCAST — tells client
                //                 to use TCP peer addr as server IP;
                //                 libca `tcpiiu::searchRespNotify`
                //                 explicitly checks `msg.m_cid !=
                //                 INADDR_BROADCAST` and falls back to
                //                 `this->address()` on the sentinel)
                //   m_available = client's m_available (the cid)
                //
                // The previous code wrote `m_cid = 0` (INADDR_ANY) and
                // an 8-byte minor-version payload. C libca client at
                // `tcpiiu.cpp:2209` treats anything != INADDR_BROADCAST
                // as a literal IP, so `m_cid = 0` would surface as a
                // server at 0.0.0.0:port — unroutable. With this fix
                // the reply is now byte-equivalent to the C softIoc.
                let mut resp = CaHeader::new(CA_PROTO_SEARCH);
                resp.data_type = state.tcp_port;
                resp.set_payload_size(0, 0);
                resp.cid = u32::MAX; // ~0U — "use TCP peer addr"
                resp.available = hdr.available;

                let mut w = writer.lock().await;
                w.write_all(&resp.to_bytes()).await?;
                // flush deferred to handle_client outer loop (batched)
            } else if hdr.data_type == CA_DO_REPLY {
                // Explicit negative reply requested — send NOT_FOUND so
                // the client doesn't have to wait for a search timeout.
                //
                // C parity: `search_fail_reply` (rsrv/camessage.c:2079)
                // copies the request's `m_dataType`/`m_count`/`m_cid`/
                // `m_available` verbatim into the response. The previous
                // Rust path overwrote `count` with the server's
                // CA_MINOR_VERSION and `cid` with the request's
                // `m_available` (which happens to equal `m_cid` for
                // libca search frames, but the parity intent is
                // "echo m_cid"). With this fix the reply is byte-
                // equivalent to a C softIoc fail reply.
                let mut nf = CaHeader::new(CA_PROTO_NOT_FOUND);
                nf.data_type = hdr.data_type;
                nf.count = hdr.count;
                nf.cid = hdr.cid;
                nf.available = hdr.available;
                let mut w = writer.lock().await;
                w.write_all(&nf.to_bytes()).await?;
                // flush deferred to handle_client outer loop (batched)
            }
            // Otherwise silent — clients without CA_DO_REPLY treat absence
            // as "this server doesn't have it" and move on.
        }

        CA_PROTO_CLEAR_CHANNEL => {
            let sid = hdr.cid;
            let cid = hdr.available;
            // C `clear_channel_reply` (camessage.c:1883-1887)
            // disconnects on a bad SID via `logBadId` + RSRV_ERROR;
            // `logBadId` emits an ECA_INTERNAL "Bad Resource ID" frame
            // (cid=0xFFFFFFFF) flushed before the close. Channels in this
            // Rust state are per-client by construction, so the "foreign
            // channel" sub-case of the C check (`pciu->client != client`)
            // can't happen — the only failure mode is unknown SID.
            // Pre-fix Rust silently skipped without disconnecting,
            // so a probing peer could send CLEAR_CHANNEL on random
            // SIDs indefinitely.
            if !state.channels.contains_key(&sid) {
                send_ca_error(writer, hdr, ECA_INTERNAL, 0xFFFF_FFFF, "Bad Resource ID").await?;
                return Err(epics_base_rs::error::CaError::Protocol(format!(
                    "CLEAR_CHANNEL on unknown SID {} (matches C clear_channel_reply logBadId + RSRV_ERROR)",
                    sid
                )));
            }
            if let Some(entry) = state.channels.remove(&sid) {
                state.channel_access.remove(&sid);
                // drop the parallel trap-mask entry so a
                // recycled SID never inherits a stale trap flag.
                state.channel_trap.remove(&sid);
                state.release_sid(sid);
                if let Some(tx) = &conn_events {
                    let _ = tx.send(ServerConnectionEvent::ChannelCleared {
                        peer,
                        pv_name: entry.pv_name.clone(),
                        cid: entry.cid,
                    });
                }

                // C parity: `clear_channel_reply` (`camessage.c:1889`)
                // calls `rsrvFreePutNotify` to drain pending PUT_NOTIFY
                // operations for this channel. Without aborting the
                // matching tasks, a stuck async record could later
                // emit a stale WRITE_NOTIFY response carrying the
                // cleared channel's ioid — confusing the client's
                // ioid demultiplex. Drain finished handles
                // opportunistically while iterating.
                drain_write_notify_tasks_for_sid(&mut state.write_notify_tasks, sid);

                // Clean up subscriptions that belong to this channel
                let sub_ids: Vec<u32> = state
                    .subscriptions
                    .iter()
                    .filter(|(_, sub)| sub.channel_sid == sid)
                    .map(|(&id, _)| id)
                    .collect();
                for sub_id in sub_ids {
                    if let Some(sub) = state.subscriptions.remove(&sub_id) {
                        sub.task.abort();
                        match &sub.target {
                            ChannelTarget::SimplePv(pv) => {
                                pv.remove_subscriber(sub.sub_id).await;
                            }
                            ChannelTarget::RecordField { record, .. } => {
                                record.write().await.remove_subscriber(sub.sub_id);
                            }
                        }
                        if let Some(tx) = &conn_events {
                            let _ = tx.send(ServerConnectionEvent::SubscriptionClosed {
                                peer,
                                pv_name: entry.pv_name.clone(),
                                sub_id,
                            });
                        }
                    }
                }

                let mut resp = CaHeader::new(CA_PROTO_CLEAR_CHANNEL);
                resp.data_type = hdr.data_type;
                resp.count = hdr.count;
                resp.cid = sid;
                resp.available = cid;
                let mut w = writer.lock().await;
                w.write_all(&resp.to_bytes()).await?;
                // flush deferred to handle_client outer loop (batched)
            }
        }

        _ => {
            // Unknown command — match C `bad_tcp_cmd_action`
            // (`camessage.c:337-352`): send CA_PROTO_ERROR with
            // ECA_INTERNAL and the 0xFFFFFFFF cid sentinel (per
            // `vsend_err` non-channel-scoped convention), then
            // tear down the connection. C returns `RSRV_ERROR`
            // which breaks the dispatcher's message loop
            // (`camessage.c:2519-2524`) — its comment is
            // explicit: "by default, clients don't recover from
            // this". Without the tear-down, a misbehaving or
            // malicious peer can flood the server with unknown
            // commands and force one CA_PROTO_ERROR reply per
            // frame indefinitely.
            let error_msg = format!("Unsupported command {}", hdr.cmmd);
            send_ca_error(writer, hdr, ECA_INTERNAL, 0xFFFF_FFFF, &error_msg).await?;
            return Err(epics_base_rs::error::CaError::Protocol(format!(
                "unsupported TCP command {} (matches C bad_tcp_cmd_action drop)",
                hdr.cmmd
            )));
        }
    }

    Ok(())
}
async fn get_full_snapshot(
    target: &ChannelTarget,
) -> Option<epics_base_rs::server::snapshot::Snapshot> {
    match target {
        ChannelTarget::SimplePv(pv) => Some(pv.snapshot().await),
        ChannelTarget::RecordField { record, field } => {
            record.read().await.snapshot_for_field(field)
        }
    }
}

/// Snapshot for a one-shot client GET (`CA_PROTO_READ` /
/// `CA_PROTO_READ_NOTIFY`).
///
/// Distinct from [`get_full_snapshot`] (used for monitor initial events
/// and access-rights re-posts) so only the *client GET* path consults a
/// PV's optional [`ReadHook`](epics_base_rs::server::pv::ReadHook): the
/// CA gateway's no-cache mode installs that hook to forward each
/// downstream read to a fresh upstream fetch. For a PV without a read
/// hook — every record-backed and cached PV — this is exactly
/// `get_full_snapshot` wrapped in `Ok`. The `Err` propagates an upstream
/// get failure so the GET handler can answer `ECA_GETFAIL`, matching C
/// ca-gateway forwarding the read to the IOC under `-no_cache`
/// (`gateVc.cc:1361-1369`).
async fn get_read_snapshot(
    target: &ChannelTarget,
) -> Result<Option<epics_base_rs::server::snapshot::Snapshot>, epics_base_rs::error::CaError> {
    match target {
        ChannelTarget::SimplePv(pv) => pv.read_snapshot().await.map(Some),
        ChannelTarget::RecordField { record, field } => {
            Ok(record.read().await.snapshot_for_field(field))
        }
    }
}

/// Send an initial / access-restore monitor snapshot as a
/// `CA_PROTO_EVENT_ADD` frame.
///
/// `requested_count` is the element count from the originating
/// `CA_PROTO_EVENT_ADD` request. The encoded DBR payload is routed
/// through [`pad_dbr_to_requested_count`] so a request count *larger*
/// than the live element count is zero-padded to the requested shape
/// — and a smaller count is truncated — exactly as the READ path and
/// the steady-state monitor producer already do. Without this the
/// first monitor frame (and the access-restore frame) was framed at
/// `snapshot.value.count()`, so a client requesting more elements
/// than the PV currently holds saw a count/size discontinuity
/// between the initial frame and later padded updates. C `read_reply`
/// frames non-autosize monitor events at the requested count and
/// zero-fills missing elements (`rsrv/camessage.c:507-571`).
///
/// `requested_count == 0` is autosize: the frame keeps the live
/// element count.
async fn send_monitor_snapshot<W: AsyncWrite + Unpin + Send + 'static>(
    writer: &Arc<Mutex<BufWriter<W>>>,
    sub_id: u32,
    data_type: u16,
    requested_count: u32,
    snapshot: &epics_base_rs::server::snapshot::Snapshot,
) -> CaResult<()> {
    let data = encode_dbr(data_type, snapshot)?;
    // CA-268: DBR_CLASS_NAME wire payload is always one 40-byte
    // string regardless of underlying value count — and is never
    // padded/truncated to a requested element count.
    let mut padded = data;
    let element_count = if data_type == epics_base_rs::types::DBR_CLASS_NAME {
        1
    } else {
        // pad (or truncate) the encoded DBR to the requested
        // element count before the 8-byte alignment resize, so the
        // header count and payload shape match a non-autosize
        // request. `pad_dbr_to_requested_count` returns the header
        // element count to use (`requested_count` when non-zero,
        // the live `actual_count` for autosize).
        let actual_count = snapshot.value.count() as u32;
        pad_dbr_to_requested_count(&mut padded, actual_count, requested_count, data_type)
    };
    padded.resize(align8(padded.len()), 0);

    let mut resp = CaHeader::new(CA_PROTO_EVENT_ADD);
    // C client TCP parser requires 8-byte aligned postsize
    resp.set_payload_size(padded.len(), element_count);
    resp.data_type = data_type;
    resp.cid = 1; // ECA_NORMAL
    resp.available = sub_id;

    // Abort-safety: build header + payload as ONE contiguous frame and
    // issue a single `write_all` so a cancel (send_timeout / task abort)
    // cannot leave an orphan header mid-frame in the shared BufWriter.
    let hdr_bytes = resp.to_bytes_extended();
    let mut frame = Vec::with_capacity(hdr_bytes.len() + padded.len());
    frame.extend_from_slice(&hdr_bytes);
    frame.extend_from_slice(&padded);
    let mut w = writer.lock().await;
    w.write_all(&frame).await?;
    w.flush().await?;
    Ok(())
}

/// Re-evaluate and re-send CA_PROTO_ACCESS_RIGHTS for all open channels.
/// Called when hostname or username changes (e.g. ACF reload).
///
/// Tracks the *transition* per channel because the C behaviour is
/// asymmetric: a read-access loss must push a single
/// `no_read_access_event` frame and silence subsequent deliveries,
/// while a read-access gain must re-enable deliveries and push one
/// current snapshot. C `casAccessRightsCB`
/// (`rsrv/camessage.c:1055-1106`) walks the channel's `eventq` and
/// calls `db_event_disable` / `db_event_enable` plus
/// `db_post_single_event` — the subscription itself is never
/// removed. Pre-fix Rust permanently destroyed the subscription
/// on a NoAccess transition (`state.subscriptions.remove +
/// task.abort`), so a later ACF reload that restored read access
/// left an orphaned camonitor: the C-equivalent re-arm never
/// happened, and the subscriber's callback receiver went silent
/// until the client noticed and re-subscribed manually.
async fn reeval_access_rights<W: AsyncWrite + Unpin + Send + 'static>(
    state: &mut ClientState,
    writer: &Arc<Mutex<BufWriter<W>>>,
) -> CaResult<()> {
    if state.channels.is_empty() {
        return Ok(());
    }
    let chan_info: Vec<(u32, u32, ChannelTarget)> = state
        .channels
        .iter()
        .map(|(&sid, entry)| (sid, entry.cid, entry.target.clone()))
        .collect();

    // (sid, old_level, new_level) — old defaults to NoAccess for a
    // sid the access cache has not seen before (parity with the
    // pre-fix `insert`-without-comparison behaviour for freshly
    // created channels).
    //
    // C `libcom/src/as/asLibRoutines.c:1047-1051` fires
    // `pclient->pcallback(... asClientCOAR)` (the COAR callback
    // that calls `casAccessRightsCB` → `access_rights_reply`)
    // ONLY when `oldaccess != access`. An ACF reload that leaves
    // every channel at the same level emits zero ACCESS_RIGHTS
    // frames in C. Pre-fix Rust unconditionally pushed a frame per
    // channel, generating an O(N) burst per connection on routine
    // reloads (typo fix, new UAG that doesn't intersect, etc.).
    // Mirror C: only emit on actual transition.
    let mut transitions: Vec<(u32, AccessLevel, AccessLevel)> = Vec::new();
    {
        let mut w = writer.lock().await;
        let mut any_frame_written = false;
        for (sid, cid, target) in chan_info {
            let (new_access, new_rule_was_trap) = state.compute_access(&target).await;
            let new_level = match new_access {
                3 => AccessLevel::ReadWrite,
                1 => AccessLevel::Read,
                _ => AccessLevel::NoAccess,
            };
            let old_level = state
                .channel_access
                .insert(sid, new_level)
                .unwrap_or(AccessLevel::NoAccess);
            // an ACF reload can change which rule grants
            // access (e.g. a new TRAPWRITE rule), so the trap mask
            // must be refreshed alongside the level.
            state.channel_trap.insert(sid, new_rule_was_trap);
            if old_level == new_level {
                continue;
            }
            transitions.push((sid, old_level, new_level));
            let mut ar = CaHeader::new(CA_PROTO_ACCESS_RIGHTS);
            ar.cid = cid;
            ar.available = new_access;
            w.write_all(&ar.to_bytes()).await?;
            any_frame_written = true;
        }
        if any_frame_written {
            w.flush().await?;
        }
    }

    fn has_read(level: AccessLevel) -> bool {
        matches!(level, AccessLevel::ReadWrite | AccessLevel::Read)
    }

    for (sid, old_level, new_level) in transitions {
        let old_read = has_read(old_level);
        let new_read = has_read(new_level);
        if old_read == new_read {
            continue;
        }
        let affected: Vec<u32> = state
            .subscriptions
            .iter()
            .filter(|(_, s)| s.channel_sid == sid)
            .map(|(&id, _)| id)
            .collect();
        if affected.is_empty() {
            continue;
        }
        if !new_read {
            // Read access REVOKED. C path: db_post_single_event
            // (which emits `no_read_access_event` — ECA_NORDACCESS
            // in m_cid plus a `dbr_size_n(type, count)` zero-filled
            // payload sized from the stored EVENT_ADD request) then
            // db_event_disable. Pre-fix Rust sent a header-only
            // frame; use `send_no_read_access_event`
            // so the wire frame matches C byte-for-byte (the stored
            // request count drives the zero-fill).
            for sub_id in &affected {
                let (data_type, sub_id_v, data_count, target) = {
                    let Some(sub) = state.subscriptions.get(sub_id) else {
                        continue;
                    };
                    sub.denied.store(true, Ordering::Release);
                    (
                        sub.data_type,
                        sub.sub_id,
                        sub.data_count,
                        sub.target.clone(),
                    )
                };
                // C posts the access-revoked event through
                // `db_post_single_event` (event-context pre-chain)
                // BEFORE `db_event_disable` (`camessage.c:1090-1092`);
                // the ECA_NORDACCESS frame is only sent when the chain
                // passes the post (`db_queue_event_log` fires only
                // `if(pLog)`). Run a fresh event-context chain on the
                // current value and skip the frame when it drops — the
                // `denied` gate is already set, so the producer stays
                // disabled either way. The denial frame is zero-filled,
                // so only the chain's pass/drop decision matters, not
                // the filtered value.
                let snap = get_full_snapshot(&target).await;
                let dropped_by_filter = match (state.channels.get(&sid), &snap) {
                    (Some(entry), Some(snap)) => entry
                        .filter_chain()
                        .apply_to_event_value(snap.value.clone())
                        .is_none(),
                    _ => false,
                };
                if dropped_by_filter {
                    continue;
                }
                // an autosize (`data_count == 0`) subscription
                // revoked here must also be normalised to the live
                // element count, otherwise the access-revoked
                // notification is the same zero-payload
                // `CA_PROTO_EVENT_ADD` the client drops as a
                // cancel-ack. Same C `read_reply` autosize parity
                // (`camessage.c:507-509`) as the initial EVENT_ADD
                // denial path.
                let denied_count = if data_count == 0 {
                    let actual = snap.as_ref().map(|snap| snap.value.count()).unwrap_or(1);
                    no_read_access_count(data_count, actual)
                } else {
                    data_count
                };
                send_no_read_access_event(
                    writer,
                    CA_PROTO_EVENT_ADD,
                    data_type,
                    denied_count,
                    sub_id_v,
                    ECA_NORDACCESS,
                )
                .await?;
            }
            let mut w = writer.lock().await;
            w.flush().await?;
        } else {
            // Read access RESTORED. C path: db_event_enable then
            // db_post_single_event. Clear the gate so the producer
            // task resumes deliveries, and emit one snapshot of
            // the current value so the subscriber sees a fresh
            // event the moment access comes back (rather than
            // waiting for the next natural update).
            //
            // the restore snapshot honours the stored
            // EVENT_ADD request count in BOTH directions.
            // `send_monitor_snapshot` pads when the request asked
            // for more elements than the PV currently holds and
            // truncates when it asked for fewer, via
            // `pad_dbr_to_requested_count` — so the access-restore
            // frame matches the request shape and later padded
            // updates. C `read_reply` always honours the stored
            // request count; pre-fix Rust framed the restore event
            // at the live `snapshot.value.count()`, only truncating
            // and never padding.
            for sub_id in &affected {
                let (target, data_type, data_count, sub_id_val, sub_long_string_mode) = {
                    let Some(sub) = state.subscriptions.get(sub_id) else {
                        continue;
                    };
                    sub.denied.store(false, Ordering::Release);
                    (
                        sub.target.clone(),
                        sub.data_type,
                        sub.data_count,
                        sub.sub_id,
                        sub.long_string_mode,
                    )
                };
                if let Some(mut snap) = get_full_snapshot(&target).await {
                    // C enables the event (`db_event_enable`)
                    // THEN posts the current value through the
                    // event-context pre-chain
                    // (`db_post_single_event`, `camessage.c:1086-1088`);
                    // the restore frame is sent only when the chain
                    // passes (`db_queue_event_log` fires only
                    // `if(pLog)`) and carries the FILTERED value. The
                    // `denied` gate is already cleared above so future
                    // natural updates resume; a fresh event-context
                    // chain per subscriber keeps `dec`/`sync`/`dbnd`
                    // state isolated. `None` => send no restore frame.
                    if let Some(entry) = state.channels.get(&sid) {
                        match entry
                            .filter_chain()
                            .apply_to_event_value(snap.value.clone())
                        {
                            Some(v) => snap.value = v,
                            None => continue,
                        }
                    }
                    // long-string boundary conversion (`$` → CHAR[40], or
                    // native record field → scalar DBR_STRING).
                    super::apply_long_string_mode(&mut snap, sub_long_string_mode);
                    send_monitor_snapshot(writer, sub_id_val, data_type, data_count, &snap).await?;
                    // Access-restore post — C `db_event_enable` then
                    // `db_post_single_event` (`camessage.c:1086-1088`):
                    // one posted and one processed subscription event,
                    // same PCAS accounting as the initial value.
                    if let Some(ref s) = state.stats {
                        s.subscription_events_posted.fetch_add(1, Ordering::Relaxed);
                        s.subscription_events_processed
                            .fetch_add(1, Ordering::Relaxed);
                    }
                }
            }
        }
    }
    Ok(())
}

/// CA_PROTO_WRITE_NOTIFY reply with extended-form
/// count support. C `putNotifyErrorReply` / `write_notify_reply`
/// (`rsrv/camessage.c:1482-1501` / `1731+`) call
/// `cas_copy_in_header` with `mp->m_count` / `msgtmp.m_count` from
/// `caHdrLargeArray`, which is the decoded 32-bit count for
/// extended requests and re-emits in extended form when needed.
/// Pre-fix Rust set `resp.count = hdr.count as u16` and serialised
/// with `to_bytes()`, so a `ca_array_put_callback()` on a
/// `>= 0xFFFF`-element array received a normal-form Rust reply
/// with `count = 0` (the extended marker) where rsrv preserves
/// the count with an extended header.
async fn send_put_notify_response<W: AsyncWrite + Unpin + Send + 'static>(
    writer: &Arc<Mutex<BufWriter<W>>>,
    data_type: u16,
    count: u32,
    eca_status: u32,
    ioid: u32,
) -> CaResult<()> {
    let mut resp = CaHeader::new(CA_PROTO_WRITE_NOTIFY);
    resp.data_type = data_type;
    // postsize = 0 (WRITE_NOTIFY replies have no payload);
    // set_payload_size promotes to extended form when count >= 0xFFFF.
    resp.set_payload_size(0, count);
    resp.cid = eca_status;
    resp.available = ioid;
    let mut w = writer.lock().await;
    w.write_all(&resp.to_bytes_extended()).await?;
    // flush deferred to handle_client outer loop (batched)
    Ok(())
}

/// normalise an EVENT_ADD request count for a no-read-access
/// denial frame. C `read_reply` (`rsrv/camessage.c:507-509`) treats a
/// zero element count as autosize and substitutes `paddr->no_elements`
/// — the target's live element count. The `no_read_access_event`
/// denial path must do the same, otherwise a `count == 0` monitor on
/// a plain DBR type (`DBR_DOUBLE`, …) produces a zero-payload
/// `CA_PROTO_EVENT_ADD`. That shape is the historical
/// subscription-cancel-confirmation no-op: the CA client drops it
/// before reading the `ECA_NORDACCESS` status (C `cac.cpp`
/// eventRespAction returns on `m_postsize == 0`; this port's
/// `client/transport.rs` mirrors that), so the denied monitor would
/// silently appear to hang.
///
/// A non-zero request count is returned unchanged (explicit counts
/// are already framed at the requested shape). `actual_count` is the
/// target's live element count, used only for the autosize case.
fn no_read_access_count(requested_count: u32, actual_count: u32) -> u32 {
    if requested_count == 0 {
        // Autosize: at least one element so the denial frame carries
        // a nonzero DBR body. A target reporting zero live elements
        // still gets a single-element zero-filled payload.
        actual_count.max(1)
    } else {
        requested_count
    }
}

/// Send a `no_read_access_event`-shaped reply: same wire frame as the
/// original READ_NOTIFY / EVENT_ADD command, with `m_cid` carrying the
/// ECA status and a `dbr_buffer_size`-sized zero payload. C
/// `no_read_access_event` (`rsrv/camessage.c:450-480`) and `read_reply`
/// (`camessage.c:540-557`) use this shape for READ_NOTIFY denials and
/// dbChannel_get failures — preserving the requested count and DBR
/// type so libca-style clients see the correct callback metadata even
/// on the error path.
///
/// callers on the EVENT_ADD denial path must pass a `count`
/// already normalised through [`no_read_access_count`] so an autosize
/// (`count == 0`) request does not produce a zero-payload frame.
async fn send_no_read_access_event<W: AsyncWrite + Unpin + Send + 'static>(
    writer: &Arc<Mutex<BufWriter<W>>>,
    cmd: u16,
    data_type: u16,
    count: u32,
    available: u32,
    eca_status: u32,
) -> CaResult<()> {
    let native = epics_base_rs::types::native_type_for_dbr(data_type)
        .unwrap_or(epics_base_rs::types::DbFieldType::Char);
    let payload_size = epics_base_rs::types::dbr_buffer_size(data_type, native, count as usize);
    let padded_size = align8(payload_size);
    let mut hdr = CaHeader::new(cmd);
    hdr.set_payload_size(padded_size, count);
    hdr.data_type = data_type;
    hdr.cid = eca_status;
    hdr.available = available;
    let hdr_bytes = hdr.to_bytes_extended();
    // Build header + zero payload as one contiguous frame so a
    // task abort can only land at a frame boundary (same abort-
    // safety invariant as `send_event` / `send_monitor_snapshot`).
    let mut frame = Vec::with_capacity(hdr_bytes.len() + padded_size);
    frame.extend_from_slice(&hdr_bytes);
    frame.resize(frame.len() + padded_size, 0);
    let mut w = writer.lock().await;
    w.write_all(&frame).await?;
    Ok(())
}

/// Resize an encoded DBR payload to the requested element count.
/// C `read_reply` (`rsrv/camessage.c:507-571`) sets the response
/// header count to `mp->m_count` (non-autosize) and sizes the
/// payload to `dbr_size_n(type, request_count)`: extra bytes are
/// zero-filled, and a response that decoded fewer elements than
/// requested is still framed at the request count. This refinement
/// covers BOTH directions: pad when requested > actual, truncate
/// when requested < actual. Returns the header element count to
/// use (`requested_count` when non-zero, `actual_count` when
/// zero / autosize).
fn pad_dbr_to_requested_count(
    encoded: &mut Vec<u8>,
    actual_count: u32,
    requested_count: u32,
    data_type: u16,
) -> u32 {
    if requested_count == 0 {
        return actual_count;
    }
    if let Ok(native) = epics_base_rs::types::native_type_for_dbr(data_type) {
        // Plain types (0-6) have no metadata; STS / TIME / GR /
        // CTRL slot metadata before the value array.
        // `dbr_buffer_size(_, _, 0)` returns just the metadata size.
        let meta_size = epics_base_rs::types::dbr_buffer_size(data_type, native, 0);
        let target_size = meta_size + (requested_count as usize) * native.element_size();
        if requested_count > actual_count {
            let cur = encoded.len();
            if cur < target_size {
                encoded.extend(std::iter::repeat_n(0u8, target_size - cur));
            }
        } else if requested_count < actual_count && encoded.len() > target_size {
            encoded.truncate(target_size);
        }
    }
    requested_count
}

/// Send a CA_PROTO_ERROR response with the original header echoed
/// into the payload and an error message.
///
/// Layout follows C `vsend_err` (`rsrv/camessage.c:139`):
///   * outer `m_cid` carries the *channel client cid* (i.e. the
///     client-side identifier of the channel the error relates to),
///     or `0xFFFFFFFF` for commands that aren't channel-scoped.
///   * outer `m_available` carries the ECA status code.
///   * payload is the original request header followed by a
///     NUL-terminated diagnostic string.
///
/// The previous implementation put the ECA status in `m_cid` and left
/// `m_available` zero, so libca's `exceptionRespAction`
/// (`cac.cpp:1118`) — which reads the status from `hdr.m_available` —
/// would surface every server-emitted CA_PROTO_ERROR as ECA_NORMAL
/// (status 0), silently masking the failure.
/// C `vsend_err` (rsrv/camessage.c:147,229-242) allocates a fixed
/// 512-byte buffer for the entire reply (outer header + echoed
/// request header + diagnostic + NUL), and `epicsVsnprintf` truncates
/// the formatted diagnostic if it would overflow. Mirror that bound
/// so a buggy caller (or future translated message catalog) can't
/// ship a CA_PROTO_ERROR whose payload exceeds the libca per-server
/// recv buffer or the extended-header threshold. 480 = 512 −
/// 2*sizeof(caHdr) matches the diagnostic budget C grants
/// `epicsVsnprintf`.
const CA_PROTO_ERROR_MAX_DIAG_LEN: usize = 480;

/// On `CA_PROTO_CLEAR_CHANNEL`, abort any pending WRITE_NOTIFY
/// completion task whose owning channel `sid` is being freed (C
/// parity: `clear_channel_reply` calls `rsrvFreePutNotify` per
/// channel — `camessage.c:1889`). Finished handles are reaped
/// opportunistically while iterating so the per-connection Vec stays
/// bounded across many WRITE_NOTIFYs over a long-lived connection.
/// Pure transformation extracted so the drain semantics are unit-
/// testable without standing up a full server + async record.
fn drain_write_notify_tasks_for_sid(tasks: &mut Vec<(u32, tokio::task::AbortHandle)>, sid: u32) {
    let mut keep = Vec::with_capacity(tasks.len());
    let mut to_abort = Vec::new();
    for (task_sid, h) in tasks.drain(..) {
        if h.is_finished() {
            continue;
        }
        if task_sid == sid {
            to_abort.push(h);
        } else {
            keep.push((task_sid, h));
        }
    }
    *tasks = keep;
    for h in to_abort {
        h.abort();
    }
}

/// Truncate `message` to at most `CA_PROTO_ERROR_MAX_DIAG_LEN` bytes
/// on a char boundary (so the resulting `&str` slice is always valid
/// UTF-8). `pad_string` appends the NUL terminator and 8-aligns.
fn truncate_diag(message: &str) -> &str {
    if message.len() <= CA_PROTO_ERROR_MAX_DIAG_LEN {
        return message;
    }
    let mut end = CA_PROTO_ERROR_MAX_DIAG_LEN;
    while end > 0 && !message.is_char_boundary(end) {
        end -= 1;
    }
    &message[..end]
}

async fn send_ca_error<W: AsyncWrite + Unpin + Send + 'static>(
    writer: &Arc<Mutex<BufWriter<W>>>,
    original_hdr: &CaHeader,
    eca_status: u32,
    chan_cid: u32,
    message: &str,
) -> CaResult<()> {
    let error_msg_bytes = pad_string(truncate_diag(message));
    // payload_size must use the echo header's ACTUAL byte length (16 or 24
    // for extended), not the constant CaHeader::SIZE=16.  Compute orig_bytes first.
    let orig_bytes = original_hdr.to_bytes_extended();
    let payload_size = orig_bytes.len() + error_msg_bytes.len();

    let mut resp = CaHeader::new(CA_PROTO_ERROR);
    resp.set_payload_size(payload_size, 0);
    resp.cid = chan_cid;
    resp.available = eca_status;

    // Abort-safety: a CA_PROTO_ERROR reply is response-header +
    // echoed-request-header + diagnostic string. Build all three as ONE
    // contiguous frame and issue a single `write_all` so a `send_timeout`
    // cancel cannot leave a partial frame (orphan header) in the shared
    // BufWriter and mis-frame every following message.
    //
    // The echoed request header is emitted in extended form when the
    // original request used the extended layout. C `vsend_err`
    // (`rsrv/camessage.c:201-214`) writes a 16-byte header with
    // `m_postsize = 0xffff` plus an 8-byte annex carrying the full
    // 32-bit postsize / count; libca `cac::exceptionRespAction`
    // (`modules/ca/src/client/cac.cpp:1097-1107`) parses the annex
    // first when it sees the 0xffff marker, then walks the diag
    // string from the post-annex offset. `to_bytes_extended()`
    // produces exactly that layout (24 bytes when `is_extended()`,
    // 16 bytes otherwise), so an extended READ/WRITE error
    // round-trips byte-for-byte with libca.
    let resp_bytes = resp.to_bytes_extended();
    // orig_bytes computed above (before payload_size).
    let mut frame = Vec::with_capacity(resp_bytes.len() + orig_bytes.len() + error_msg_bytes.len());
    frame.extend_from_slice(&resp_bytes);
    frame.extend_from_slice(&orig_bytes);
    frame.extend_from_slice(&error_msg_bytes);
    let mut w = writer.lock().await;
    w.write_all(&frame).await?;
    // flush deferred to handle_client outer loop (batched)
    Ok(())
}

#[cfg(test)]
mod write_notify_drain_tests {
    use super::drain_write_notify_tasks_for_sid;

    /// Spawn a long-running task (sleep-loop) and return its abort
    /// handle. The handle's `is_finished()` flips to true once `abort()`
    /// has fired AND the runtime has processed the cancellation. We
    /// poll for that transition in the test below — drop-flag
    /// approaches were timing-sensitive on saturated CI runners.
    fn spawn_pending() -> tokio::task::AbortHandle {
        tokio::spawn(async {
            loop {
                tokio::time::sleep(std::time::Duration::from_millis(1)).await;
            }
        })
        .abort_handle()
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn drains_only_matching_sid() {
        let h_a = spawn_pending();
        let h_b = spawn_pending();
        let h_c = spawn_pending();
        let h_a_probe = h_a.clone();
        let h_b_probe = h_b.clone();
        let h_c_probe = h_c.clone();
        let mut tasks = vec![(10u32, h_a), (20u32, h_b), (10u32, h_c)];

        drain_write_notify_tasks_for_sid(&mut tasks, 10);

        // sid=20 entry survives
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].0, 20);

        // Wait up to 2s (generous for saturated CI) for the aborted
        // tasks to actually finish. The sid=20 task must still be
        // running (no abort fired against it).
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        while std::time::Instant::now() < deadline {
            if h_a_probe.is_finished() && h_c_probe.is_finished() {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        assert!(h_a_probe.is_finished(), "sid=10 task #1 must be aborted");
        assert!(h_c_probe.is_finished(), "sid=10 task #3 must be aborted");
        assert!(!h_b_probe.is_finished(), "sid=20 task must survive");

        // Cleanup the surviving task so we don't leak.
        h_b_probe.abort();
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn reaps_finished_handles_during_drain() {
        // A handle whose future already completed should be removed
        // from the Vec regardless of whether its sid matches — this
        // is the opportunistic-reap behaviour the long-lived
        // connection relies on.
        let done = tokio::spawn(async {}).abort_handle();
        for _ in 0..200 {
            if done.is_finished() {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
        assert!(done.is_finished(), "spawned no-op task should complete");

        let live = spawn_pending();
        let live_probe = live.clone();
        let mut tasks = vec![(99u32, done), (5u32, live)];
        drain_write_notify_tasks_for_sid(&mut tasks, 1234);
        assert_eq!(tasks.len(), 1, "finished handle was not reaped");
        assert_eq!(tasks[0].0, 5);

        // Cleanup the still-live task.
        live_probe.abort();
    }
}

#[cfg(test)]
mod put_notify_supersede_tests {
    //! A second `CA_PROTO_WRITE_NOTIFY` on a channel with an in-flight
    //! put-callback must *supersede* the previous one (cancel it, reply
    //! ECA_PUTCBINPROG to the superseded request) and proceed — never
    //! reject the new request. C `write_notify_action`
    //! (`rsrv/camessage.c:1660-1707`). The single owner of the channel's
    //! in-flight put-callback is [`PutNotifySlot`]; the single owner of
    //! each put-callback's reply is its `responded` token.
    use super::{ECA_PUTCBINPROG, InFlightPutNotify, PutNotifySlot, supersede_put_notify};
    use epics_base_rs::runtime::sync::Mutex;
    use std::pin::Pin;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::task::{Context, Poll};
    use tokio::io::{AsyncWrite, BufWriter};

    /// Mock writer recording every byte batch (mirrors monitor.rs).
    #[derive(Default)]
    struct RecordingWriter {
        batches: Vec<Vec<u8>>,
    }

    impl AsyncWrite for RecordingWriter {
        fn poll_write(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<std::io::Result<usize>> {
            self.batches.push(buf.to_vec());
            Poll::Ready(Ok(buf.len()))
        }
        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            Poll::Ready(Ok(()))
        }
        fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            Poll::Ready(Ok(()))
        }
    }

    fn recording_writer() -> Arc<Mutex<BufWriter<RecordingWriter>>> {
        Arc::new(Mutex::new(BufWriter::with_capacity(
            0,
            RecordingWriter::default(),
        )))
    }

    /// A never-completing task so the in-flight put-callback has a real
    /// `AbortHandle` for the supersede to cancel.
    fn pending_abort_handle() -> tokio::task::AbortHandle {
        tokio::spawn(async {
            loop {
                tokio::task::yield_now().await;
            }
        })
        .abort_handle()
    }

    fn inflight(ioid: u32, responded: Arc<AtomicBool>) -> InFlightPutNotify {
        InFlightPutNotify {
            abort: pending_abort_handle(),
            responded,
            ioid,
            dbr_type: epics_base_rs::types::DBR_LONG,
            count: 1,
        }
    }

    /// take/install round-trips the channel's in-flight put-callback;
    /// `take` leaves the slot empty so the same entry is never
    /// superseded twice.
    #[tokio::test]
    async fn slot_take_install_roundtrip() {
        let slot = PutNotifySlot::default();
        assert!(slot.take().is_none(), "fresh slot holds no put-callback");
        slot.install(inflight(7, Arc::new(AtomicBool::new(false))));
        let taken = slot.take().expect("installed entry is taken back");
        assert_eq!(taken.ioid, 7);
        assert!(slot.take().is_none(), "take leaves the slot empty");
    }

    /// A still-in-flight put-callback (responded == false) that is
    /// superseded gets ECA_PUTCBINPROG sent to ITS ioid — the new
    /// request is never the one refused. Mirrors C
    /// `putNotifyErrorReply(client, &pPutNotify->msg, ECA_PUTCBINPROG)`.
    #[tokio::test]
    async fn supersede_replies_putcbinprog_to_the_superseded_request() {
        let writer = recording_writer();
        let responded = Arc::new(AtomicBool::new(false));
        let prev = Some(inflight(0x1234, responded.clone()));

        supersede_put_notify(prev, &writer)
            .await
            .expect("supersede sends the superseded request its reply");

        assert!(
            responded.load(Ordering::Acquire),
            "supersede claims the superseded put-callback's reply"
        );
        let guard = writer.lock().await;
        let batches = &guard.get_ref().batches;
        assert_eq!(batches.len(), 1, "exactly one ECA_PUTCBINPROG reply");
        let frame = &batches[0];
        // CA header: param1 (ECA status) at [8..12], param2 (ioid) at [12..16].
        let eca = u32::from_be_bytes([frame[8], frame[9], frame[10], frame[11]]);
        let ioid = u32::from_be_bytes([frame[12], frame[13], frame[14], frame[15]]);
        assert_eq!(
            eca, ECA_PUTCBINPROG,
            "superseded request gets ECA_PUTCBINPROG"
        );
        assert_eq!(ioid, 0x1234, "the reply targets the superseded ioid");
    }

    /// A put-callback that completed naturally (its completion task
    /// already won the `responded` race and replied) must NOT get a
    /// second reply when a later WRITE_NOTIFY supersedes the stale slot
    /// entry — one ioid, one reply.
    #[tokio::test]
    async fn supersede_after_completion_sends_no_second_reply() {
        let writer = recording_writer();
        let responded = Arc::new(AtomicBool::new(true)); // completion already replied
        let prev = Some(inflight(0x55, responded.clone()));

        supersede_put_notify(prev, &writer)
            .await
            .expect("supersede of a completed put-callback is a no-op reply");

        let guard = writer.lock().await;
        assert!(
            guard.get_ref().batches.is_empty(),
            "no second reply for an already-answered ioid"
        );
    }

    /// Exactly one of {completion task, superseding request} owns the
    /// reply. The first `responded` swap wins; the loser must observe
    /// `true` and stay silent. This is the invariant that prevents a
    /// double reply when a put completes at the instant it is
    /// superseded.
    #[tokio::test]
    async fn responded_token_grants_a_single_reply_owner() {
        let writer = recording_writer();
        let responded = Arc::new(AtomicBool::new(false));

        // Simulate the completion task winning first.
        assert!(
            !responded.swap(true, Ordering::AcqRel),
            "completion task claims the reply"
        );
        // The superseding request now finds it already claimed.
        let prev = Some(inflight(0x99, responded.clone()));
        supersede_put_notify(prev, &writer).await.unwrap();

        let guard = writer.lock().await;
        assert!(
            guard.get_ref().batches.is_empty(),
            "superseding path must not reply once the completion task has"
        );
    }
}

#[cfg(test)]
mod truncate_diag_tests {
    use super::{CA_PROTO_ERROR_MAX_DIAG_LEN, truncate_diag};

    #[test]
    fn passes_through_short_message() {
        let s = "channel limit reached";
        assert_eq!(truncate_diag(s), s);
    }

    #[test]
    fn truncates_at_exact_limit() {
        let s = "x".repeat(CA_PROTO_ERROR_MAX_DIAG_LEN);
        assert_eq!(truncate_diag(&s).len(), CA_PROTO_ERROR_MAX_DIAG_LEN);
    }

    #[test]
    fn truncates_oversize_to_limit() {
        let s = "x".repeat(CA_PROTO_ERROR_MAX_DIAG_LEN + 100);
        let out = truncate_diag(&s);
        assert_eq!(out.len(), CA_PROTO_ERROR_MAX_DIAG_LEN);
        assert!(out.chars().all(|c| c == 'x'));
    }

    #[test]
    fn truncation_lands_on_utf8_char_boundary() {
        // Construct a string that crosses the 480-byte cap inside
        // a multi-byte UTF-8 sequence: 'é' (U+00E9) is 2 bytes in
        // UTF-8. Padding with 479 'a's puts the first byte of 'é'
        // exactly at byte 479 — within the limit — and the second
        // at byte 480 — past it. Naive byte slicing would split it
        // and panic. `truncate_diag` must back off to the previous
        // char boundary (byte 479).
        let mut s = "a".repeat(479);
        s.push('é');
        assert_eq!(s.len(), 481);
        let out = truncate_diag(&s);
        assert!(out.is_char_boundary(out.len()));
        assert!(out.len() <= CA_PROTO_ERROR_MAX_DIAG_LEN);
        // Standard library guarantees: the returned &str is valid
        // UTF-8 (otherwise this method-call would panic).
        let _ = out.to_owned();
    }
}

#[cfg(test)]
mod multi_nic_listener_tests {
    //! C-parity regression: `run_tcp_listener` must honour every entry
    //! in `EPICS_CAS_INTF_ADDR_LIST`, not just the first.
    //!
    //! C `rsrv_init` (caservertask.c:603-712) iterates `casIntfAddrList`
    //! and spawns one accept thread per entry, all on the same TCP
    //! port. The previous Rust implementation bound only the first
    //! interface, so a server configured with `INTF_ADDR_LIST="A B"`
    //! silently dropped TCP accepts on interface B.
    use super::*;
    use epics_base_rs::server::database::PvDatabase;
    use std::sync::Arc;
    use std::sync::atomic::AtomicBool;
    use std::time::Duration;
    use tokio::net::TcpStream;
    use tokio::sync::{Notify, broadcast, oneshot};

    /// Spawn `run_tcp_listener` against a per-test database, return the
    /// (port, abort-handle). Honours whatever EPICS_CAS_INTF_ADDR_LIST
    /// is currently set in the process env (caller manages it).
    async fn start_listener() -> (u16, tokio::task::JoinHandle<()>) {
        let db = Arc::new(PvDatabase::new());
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (acf_reload_tx, _) = broadcast::channel::<()>(4);
        let (tcp_tx, tcp_rx) = oneshot::channel::<u16>();
        let beacon_reset = Arc::new(Notify::new());
        let drain = Arc::new(AtomicBool::new(false));
        let handle = tokio::spawn(async move {
            let _ = run_tcp_listener(
                db,
                0, // ephemeral
                acf,
                acf_reload_tx,
                tcp_tx,
                beacon_reset,
                None,
                None,
                drain,
                None,
                #[cfg(feature = "experimental-rust-tls")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await;
        });
        let port = tcp_rx.await.expect("listener bound");
        (port, handle)
    }

    /// Confirm `INTF_ADDR_LIST=127.0.0.1` results in a listener that
    /// accepts on 127.0.0.1. This is the "single specific IP" path
    /// which already worked before — the test guards against a
    /// regression in the refactor.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[serial_test::serial]
    async fn single_specific_intf_binds_and_accepts() {
        let saved = std::env::var("EPICS_CAS_INTF_ADDR_LIST").ok();
        // SAFETY: gated by `serial_test::serial`; restored before return.
        unsafe { std::env::set_var("EPICS_CAS_INTF_ADDR_LIST", "127.0.0.1") };

        let (port, listener_task) = start_listener().await;
        // Connect — TCP handshake completes only if the listener bound
        // to 127.0.0.1 and is accepting.
        let stream = tokio::time::timeout(
            Duration::from_secs(2),
            TcpStream::connect(("127.0.0.1", port)),
        )
        .await
        .expect("connect within timeout")
        .expect("connect succeeded");
        drop(stream);

        listener_task.abort();
        let _ = listener_task.await;

        // SAFETY: same `serial_test::serial` scope.
        unsafe {
            match saved {
                Some(v) => std::env::set_var("EPICS_CAS_INTF_ADDR_LIST", v),
                None => std::env::remove_var("EPICS_CAS_INTF_ADDR_LIST"),
            }
        }
    }

    /// Two-entry `INTF_ADDR_LIST`: the first valid interface decides
    /// the port; the second must bind on the same port. Use
    /// `127.0.0.1` for both — POSIX rejects two identical
    /// (addr,port) binds, so the second bind on the same loopback IP
    /// fails. The contract is that a failed *subsequent* bind is
    /// logged-and-skipped (matching C `cleanup: continue;`), and the
    /// listener as a whole still serves the first interface.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[serial_test::serial]
    async fn duplicate_intf_subsequent_skipped_not_fatal() {
        let saved = std::env::var("EPICS_CAS_INTF_ADDR_LIST").ok();
        // SAFETY: gated by `serial_test::serial`.
        unsafe { std::env::set_var("EPICS_CAS_INTF_ADDR_LIST", "127.0.0.1 127.0.0.1") };

        let (port, listener_task) = start_listener().await;
        // First listener still accepts.
        let stream = tokio::time::timeout(
            Duration::from_secs(2),
            TcpStream::connect(("127.0.0.1", port)),
        )
        .await
        .expect("connect within timeout")
        .expect("connect succeeded — first listener serves");
        drop(stream);

        listener_task.abort();
        let _ = listener_task.await;

        // SAFETY: same scope.
        unsafe {
            match saved {
                Some(v) => std::env::set_var("EPICS_CAS_INTF_ADDR_LIST", v),
                None => std::env::remove_var("EPICS_CAS_INTF_ADDR_LIST"),
            }
        }
    }

    /// Empty list → falls back to single 0.0.0.0 bind (default).
    /// Asserts the empty-list path didn't regress.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[serial_test::serial]
    async fn empty_intf_list_binds_wildcard() {
        let saved = std::env::var("EPICS_CAS_INTF_ADDR_LIST").ok();
        // SAFETY: gated by `serial_test::serial`.
        unsafe { std::env::remove_var("EPICS_CAS_INTF_ADDR_LIST") };

        let (port, listener_task) = start_listener().await;
        // 0.0.0.0 binds accept connections on every local IP including
        // 127.0.0.1.
        let stream = tokio::time::timeout(
            Duration::from_secs(2),
            TcpStream::connect(("127.0.0.1", port)),
        )
        .await
        .expect("connect within timeout")
        .expect("connect succeeded");
        drop(stream);

        listener_task.abort();
        let _ = listener_task.await;

        // SAFETY: same scope.
        unsafe {
            if let Some(v) = saved {
                std::env::set_var("EPICS_CAS_INTF_ADDR_LIST", v);
            }
        }
    }
}

#[cfg(test)]
mod extended_header_split_tests {
    //! C-parity regression: a TCP segment that ends in the middle of an
    //! extended-form header (16..24 bytes, `m_postsize == 0xffff`) must
    //! make the framing loop *wait* for the rest of the header, not
    //! disconnect the client. C `rsrv/camessage.c:~2410` does
    //! `status = RSRV_OK; break;` for this partial-header case.
    use super::*;
    use epics_base_rs::server::database::PvDatabase;
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::io::AsyncWriteExt;

    /// Feed exactly 20 bytes of an extended-form header (a 16-byte base
    /// header with `postsize == 0xFFFF`, plus 4 of the 8 extended
    /// bytes) and assert `handle_client` does NOT return early with an
    /// error: it must block awaiting the remaining 4 bytes. Pre-fix,
    /// `from_bytes_extended` returned `Err("extended header
    /// incomplete")` and the `?` closed the connection.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn partial_extended_header_waits_not_disconnects() {
        let db = Arc::new(PvDatabase::new());
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (_acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);

        let (client_io, server_io) = tokio::io::duplex(256);
        let peer: SocketAddr = "127.0.0.1:55123".parse().unwrap();

        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                None,
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });

        // Build a CA_PROTO_READ_NOTIFY header in extended form:
        // postsize=0xFFFF marks extended; write only 20 of the 24
        // header bytes so the framing loop sees a partial ext header.
        let mut hdr = CaHeader::new(CA_PROTO_READ_NOTIFY);
        hdr.postsize = 0xFFFF;
        let base = hdr.to_bytes();
        let mut prefix = base.to_vec();
        // 4 of the 8 extended bytes (extended postsize = 0).
        prefix.extend_from_slice(&[0u8, 0, 0, 0]);
        assert_eq!(prefix.len(), 20);

        let mut client = client_io;
        client.write_all(&prefix).await.expect("write prefix");
        client.flush().await.expect("flush prefix");

        // The handler must still be running — it is waiting for the
        // remaining 4 bytes, not disconnected with an error.
        tokio::time::sleep(Duration::from_millis(200)).await;
        assert!(
            !handle.is_finished(),
            "handle_client returned on a partial extended header — \
             must wait for more bytes (C camessage.c RSRV_OK; break)"
        );

        // Close the write half: a clean EOF on a partial frame must
        // resolve to Ok(()), never an Err.
        drop(client);
        let res = tokio::time::timeout(Duration::from_secs(2), handle)
            .await
            .expect("handle_client completes after EOF")
            .expect("join ok");
        assert!(
            res.is_ok(),
            "clean EOF after partial extended header must be Ok, got {res:?}"
        );
    }
}

#[cfg(test)]
mod non_graceful_disconnect_teardown_tests {
    //! CRITICAL regression: every exit path out of `handle_client`'s
    //! read loop — not just the graceful `break` — must run the single
    //! teardown block (subscription cancel + `SubscriptionClosed`
    //! emission + write-notify abort + `ChannelCleared` emission).
    //!
    //! Before the fix, an in-loop `return Err(..)` (misaligned payload,
    //! payload-too-large, dispatch error, send-timeout, rate-limit
    //! disconnect, batched-flush error) bypassed the teardown. A client
    //! that established a subscription and then disconnected
    //! non-gracefully (TCP RST, malformed frame) would leave its
    //! `SubscriptionClosed` event unfired forever — inflating consumer
    //! refcounts that key off these events (e.g. ca_gateway).
    use super::*;
    use epics_base_rs::server::database::PvDatabase;
    use epics_base_rs::types::EpicsValue;
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    /// Build a CA_PROTO_VERSION request (minor version 13).
    pub(super) fn version_frame() -> Vec<u8> {
        let mut h = CaHeader::new(CA_PROTO_VERSION);
        h.count = CA_MINOR_VERSION;
        h.to_bytes().to_vec()
    }

    /// Build a CA_PROTO_CREATE_CHAN request for `pv_name` with the
    /// given client cid. Payload is the 8-aligned, NUL-terminated name.
    pub(super) fn create_chan_frame(cid: u32, pv_name: &str) -> Vec<u8> {
        let name = pad_string(pv_name);
        let mut h = CaHeader::new(CA_PROTO_CREATE_CHAN);
        h.cid = cid;
        h.available = CA_MINOR_VERSION as u32;
        h.set_payload_size(name.len(), 0);
        let mut frame = h.to_bytes().to_vec();
        frame.extend_from_slice(&name);
        frame
    }

    /// Build a CA_PROTO_EVENT_ADD request: subscribe `sub_id` on `sid`.
    /// Payload is the 16-byte monitor request (low/high/to f32 + mask).
    pub(super) fn event_add_frame(sid: u32, sub_id: u32) -> Vec<u8> {
        let mut h = CaHeader::new(CA_PROTO_EVENT_ADD);
        h.data_type = epics_base_rs::types::DBR_TIME_DOUBLE;
        h.count = 1;
        h.cid = sid;
        h.available = sub_id;
        h.set_payload_size(16, 1);
        let mut frame = h.to_bytes().to_vec();
        frame.extend_from_slice(&0f32.to_be_bytes());
        frame.extend_from_slice(&0f32.to_be_bytes());
        frame.extend_from_slice(&0f32.to_be_bytes());
        frame.extend_from_slice(&3u16.to_be_bytes()); // mask: value+alarm
        frame.extend_from_slice(&0u16.to_be_bytes()); // pad
        frame
    }

    /// Drain `rx` for up to `timeout`, returning the first event that
    /// satisfies `pred`, or `None` on timeout.
    pub(super) async fn await_event(
        rx: &mut broadcast::Receiver<ServerConnectionEvent>,
        timeout: Duration,
        mut pred: impl FnMut(&ServerConnectionEvent) -> bool,
    ) -> Option<ServerConnectionEvent> {
        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            if remaining.is_zero() {
                return None;
            }
            match tokio::time::timeout(remaining, rx.recv()).await {
                Ok(Ok(ev)) => {
                    if pred(&ev) {
                        return Some(ev);
                    }
                }
                Ok(Err(broadcast::error::RecvError::Lagged(_))) => continue,
                Ok(Err(broadcast::error::RecvError::Closed)) | Err(_) => return None,
            }
        }
    }

    /// Read from `client` until a CA_PROTO_CREATE_CHAN response frame is
    /// seen, then return its server-assigned sid (`m_available`). The
    /// EVENT_ADD request must address the channel by this sid, not by
    /// the client cid.
    pub(super) async fn read_create_chan_sid<R: tokio::io::AsyncRead + Unpin>(
        client: &mut R,
        timeout: Duration,
    ) -> u32 {
        let mut acc: Vec<u8> = Vec::new();
        let mut buf = [0u8; 512];
        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            assert!(
                !remaining.is_zero(),
                "timed out waiting for CREATE_CHAN response"
            );
            let n = tokio::time::timeout(remaining, client.read(&mut buf))
                .await
                .expect("read within timeout")
                .expect("read ok");
            assert!(n > 0, "server closed before CREATE_CHAN response");
            acc.extend_from_slice(&buf[..n]);
            let mut offset = 0;
            while offset + CaHeader::SIZE <= acc.len() {
                let (hdr, hdr_size) = CaHeader::from_bytes_extended(&acc[offset..])
                    .expect("server response header parses");
                let msg_len = hdr_size + hdr.actual_postsize();
                if offset + msg_len > acc.len() {
                    break;
                }
                if hdr.cmmd == CA_PROTO_CREATE_CHAN {
                    return hdr.available;
                }
                offset += msg_len;
            }
        }
    }

    /// Read frames until a CREATE_CHAN (success) or CREATE_CH_FAIL response
    /// is seen, then return that header so the caller can distinguish the
    /// two outcomes and inspect the advertised type/count.
    pub(super) async fn read_create_chan_result<R: tokio::io::AsyncRead + Unpin>(
        client: &mut R,
        timeout: Duration,
    ) -> CaHeader {
        let mut acc: Vec<u8> = Vec::new();
        let mut buf = [0u8; 512];
        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            assert!(
                !remaining.is_zero(),
                "timed out waiting for CREATE_CHAN result"
            );
            let n = tokio::time::timeout(remaining, client.read(&mut buf))
                .await
                .expect("read within timeout")
                .expect("read ok");
            assert!(n > 0, "server closed before CREATE_CHAN result");
            acc.extend_from_slice(&buf[..n]);
            let mut offset = 0;
            while offset + CaHeader::SIZE <= acc.len() {
                let (hdr, hdr_size) = CaHeader::from_bytes_extended(&acc[offset..])
                    .expect("server response header parses");
                let msg_len = hdr_size + hdr.actual_postsize();
                if offset + msg_len > acc.len() {
                    break;
                }
                if hdr.cmmd == CA_PROTO_CREATE_CHAN || hdr.cmmd == CA_PROTO_CREATE_CH_FAIL {
                    return hdr;
                }
                offset += msg_len;
            }
        }
    }

    /// Regression: a record-level `$` long-string channel — `REC$` with no
    /// explicit `.FIELD` — must resolve and create as a CHAR[40] channel.
    /// C dbChannel.c:482-507 strips the `$` modifier AFTER the record/field
    /// name lookup, so it applies to the default VAL field. The port
    /// previously stripped `$` only from an explicit `.FIELD`, leaving it on
    /// the record key so `find_entry_from` missed the record and returned
    /// CREATE_CH_FAIL where C serves the field's long string.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn record_level_dollar_creates_long_string_channel() {
        use epics_base_rs::server::records::stringin::StringinRecord;

        let db = Arc::new(PvDatabase::new());
        db.add_record("longstr:rec", Box::new(StringinRecord::new("hello")))
            .await
            .expect("add stringin record");
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (_acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);
        let (conn_tx, _conn_rx) = broadcast::channel::<ServerConnectionEvent>(64);

        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = "127.0.0.1:55223".parse().unwrap();
        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                Some(conn_tx),
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });

        let mut client = client_io;
        client.write_all(&version_frame()).await.expect("version");
        // Record-level `$`: no explicit `.FIELD`.
        client
            .write_all(&create_chan_frame(0xAA, "longstr:rec$"))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");

        let hdr = read_create_chan_result(&mut client, Duration::from_secs(3)).await;
        assert_eq!(
            hdr.cmmd, CA_PROTO_CREATE_CHAN,
            "record-level `REC$` must create the channel, not CREATE_CH_FAIL"
        );
        // A `$` long string is served as CHAR[40] (DbFieldType::Char == 4).
        assert_eq!(hdr.data_type, 4, "long-string channel advertises DBR_CHAR");
        assert_eq!(hdr.count, 40, "long-string channel advertises 40 elements");

        drop(client);
        handle.abort();
    }

    /// Regression: a `$` long-string channel on a string SimplePv must
    /// advertise CHAR[40], not the native DBR_STRING/1. The channel stores
    /// `long_string` and every delivery path runs `apply_long_string` to
    /// emit CHAR[40], so the SimplePv arm must override the advertised
    /// type/count to match — like the RecordField arm and C
    /// dbChannel.c:486-492.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn simple_pv_dollar_advertises_char_array() {
        let db = Arc::new(PvDatabase::new());
        db.add_pv("longstr:simple", EpicsValue::String("hi".into()))
            .await
            .expect("add string pv");
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (_acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);
        let (conn_tx, _conn_rx) = broadcast::channel::<ServerConnectionEvent>(64);

        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = "127.0.0.1:55224".parse().unwrap();
        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                Some(conn_tx),
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });

        let mut client = client_io;
        client.write_all(&version_frame()).await.expect("version");
        client
            .write_all(&create_chan_frame(0xA1, "longstr:simple$"))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");

        let hdr = read_create_chan_result(&mut client, Duration::from_secs(3)).await;
        assert_eq!(
            hdr.cmmd, CA_PROTO_CREATE_CHAN,
            "string SimplePv `$` must create the channel"
        );
        assert_eq!(hdr.data_type, 4, "long-string SimplePv advertises DBR_CHAR");
        assert_eq!(hdr.count, 40, "long-string SimplePv advertises 40 elements");

        drop(client);
        handle.abort();
    }

    /// Regression: a `$` long-string channel on a non-string SimplePv must
    /// be rejected with CREATE_CH_FAIL — C dbChannel.c:500-502 returns
    /// S_dbLib_fieldNotFound for a `$` modifier on a non-DBF_STRING field,
    /// matching the RecordField arm.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn simple_pv_dollar_on_non_string_fails() {
        let db = Arc::new(PvDatabase::new());
        db.add_pv("num:simple", EpicsValue::Double(1.0))
            .await
            .expect("add double pv");
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (_acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);
        let (conn_tx, _conn_rx) = broadcast::channel::<ServerConnectionEvent>(64);

        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = "127.0.0.1:55225".parse().unwrap();
        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                Some(conn_tx),
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });

        let mut client = client_io;
        client.write_all(&version_frame()).await.expect("version");
        client
            .write_all(&create_chan_frame(0xA2, "num:simple$"))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");

        let hdr = read_create_chan_result(&mut client, Duration::from_secs(3)).await;
        assert_eq!(
            hdr.cmmd, CA_PROTO_CREATE_CH_FAIL,
            "`$` on a non-string SimplePv must be rejected with CREATE_CH_FAIL"
        );

        drop(client);
        handle.abort();
    }

    /// A client that opens a subscription and then sends a misaligned
    /// frame (postsize not 8-aligned) MUST still have its
    /// `SubscriptionClosed` event emitted. The misaligned frame drives
    /// the `break 'client_loop Err(..)` path that previously bypassed
    /// the teardown block.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn misaligned_frame_after_subscribe_still_emits_subscription_closed() {
        let db = Arc::new(PvDatabase::new());
        db.add_pv("teardown:test:pv", EpicsValue::Double(1.0))
            .await
            .expect("add pv");
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (_acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);
        let (conn_tx, mut conn_rx) = broadcast::channel::<ServerConnectionEvent>(64);

        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = "127.0.0.1:55222".parse().unwrap();

        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                Some(conn_tx),
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });

        let mut client = client_io;
        // Establish the channel first; read back the server-assigned sid.
        client.write_all(&version_frame()).await.expect("version");
        client
            .write_all(&create_chan_frame(0xAA, "teardown:test:pv"))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");
        let sid = read_create_chan_sid(&mut client, Duration::from_secs(3)).await;
        // Now subscribe, addressing the channel by its server sid.
        client
            .write_all(&event_add_frame(sid, 0xBB))
            .await
            .expect("event_add");
        client.flush().await.expect("flush event_add");

        // The server must accept the subscription before we test the
        // teardown — otherwise the test would pass vacuously.
        let opened = await_event(&mut conn_rx, Duration::from_secs(3), |ev| {
            matches!(ev, ServerConnectionEvent::SubscriptionOpened { .. })
        })
        .await;
        assert!(
            matches!(opened, Some(ServerConnectionEvent::SubscriptionOpened { sub_id, .. }) if sub_id == 0xBB),
            "subscription must open before the disconnect test (got {opened:?})"
        );

        // Now send a definitively malformed frame: a header whose
        // postsize is not 8-byte aligned. The server rejects it with
        // ECA_INTERNAL and `break 'client_loop Err(..)` — a NON-graceful
        // exit. Before the fix this `return Err` bypassed the teardown.
        let mut bad = CaHeader::new(CA_PROTO_READ_NOTIFY);
        bad.postsize = 5; // not a multiple of 8 — misaligned
        client
            .write_all(&bad.to_bytes())
            .await
            .expect("misaligned frame");
        client.flush().await.expect("flush misaligned");

        // The teardown MUST emit SubscriptionClosed for sub_id 0xBB even
        // though the connection ended via the error path.
        let closed = await_event(&mut conn_rx, Duration::from_secs(3), |ev| {
            matches!(ev, ServerConnectionEvent::SubscriptionClosed { .. })
        })
        .await;
        assert!(
            matches!(closed, Some(ServerConnectionEvent::SubscriptionClosed { sub_id, .. }) if sub_id == 0xBB),
            "SubscriptionClosed must fire on a non-graceful (error-path) \
             disconnect — teardown was bypassed (got {closed:?})"
        );

        // The handler returns Err for the misaligned-frame path.
        let res = tokio::time::timeout(Duration::from_secs(2), handle)
            .await
            .expect("handle_client completes")
            .expect("join ok");
        assert!(
            res.is_err(),
            "misaligned frame must close the connection with Err, got {res:?}"
        );
        drop(client);
    }

    /// Control case: a graceful EOF disconnect must ALSO emit
    /// `SubscriptionClosed` (the path that always worked) — guards
    /// against the restructure regressing the `break` path.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn graceful_eof_after_subscribe_emits_subscription_closed() {
        let db = Arc::new(PvDatabase::new());
        db.add_pv("teardown:test:pv2", EpicsValue::Double(1.0))
            .await
            .expect("add pv");
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (_acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);
        let (conn_tx, mut conn_rx) = broadcast::channel::<ServerConnectionEvent>(64);

        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = "127.0.0.1:55223".parse().unwrap();

        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                Some(conn_tx),
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });

        let mut client = client_io;
        client.write_all(&version_frame()).await.expect("version");
        client
            .write_all(&create_chan_frame(0xCC, "teardown:test:pv2"))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");
        let sid = read_create_chan_sid(&mut client, Duration::from_secs(3)).await;
        client
            .write_all(&event_add_frame(sid, 0xDD))
            .await
            .expect("event_add");
        client.flush().await.expect("flush event_add");

        let opened = await_event(&mut conn_rx, Duration::from_secs(3), |ev| {
            matches!(ev, ServerConnectionEvent::SubscriptionOpened { .. })
        })
        .await;
        assert!(opened.is_some(), "subscription must open");

        // Graceful close: drop the write half → server reads EOF →
        // `break 'client_loop Ok(())`.
        drop(client);

        let closed = await_event(&mut conn_rx, Duration::from_secs(3), |ev| {
            matches!(ev, ServerConnectionEvent::SubscriptionClosed { .. })
        })
        .await;
        assert!(
            matches!(closed, Some(ServerConnectionEvent::SubscriptionClosed { sub_id, .. }) if sub_id == 0xDD),
            "SubscriptionClosed must fire on graceful EOF too (got {closed:?})"
        );

        let res = tokio::time::timeout(Duration::from_secs(2), handle)
            .await
            .expect("handle_client completes")
            .expect("join ok");
        assert!(res.is_ok(), "graceful EOF must be Ok, got {res:?}");
    }
}

#[cfg(test)]
mod write_gate_order_tests {
    //! The deprecated `CA_PROTO_WRITE` (cmd 4) and `CA_PROTO_WRITE_NOTIFY`
    //! (cmd 19) run their DBR-type gate and their write-access gate in
    //! OPPOSITE orders, and the order is observable when BOTH fail:
    //!
    //! * `write_notify_action` (rsrv/camessage.c:1647-1656): TYPE first
    //!   (ECA_BADTYPE → RSRV_ERROR / connection DROPPED), THEN access.
    //! * `write_action` (rsrv/camessage.c:741-766): ACCESS first
    //!   (ECA_NOWTACCESS → RSRV_OK / connection KEPT), the type is
    //!   validated only afterwards by `caNetConvert`.
    //!
    //! So a peer that sends a deprecated WRITE which is BOTH access-denied
    //! AND carries an unsupported DBR type must receive ECA_NOWTACCESS and
    //! keep its connection — NOT ECA_BADTYPE + drop. Pre-fix Rust ran the
    //! type gate first for both opcodes, inverting `write_action`. These
    //! two tests pin each opcode's ordering.
    use super::non_graceful_disconnect_teardown_tests::{
        create_chan_frame, read_create_chan_sid, version_frame,
    };
    use super::*;
    use epics_base_rs::server::access_security::parse_acf;
    use epics_base_rs::server::database::PvDatabase;
    use epics_base_rs::types::EpicsValue;
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    /// An unsupported DBR type code: far above `LAST_BUFFER_TYPE`, and
    /// neither `DBR_PUT_ACKT` (35) nor `DBR_PUT_ACKS` (36) — so it falls
    /// through to the regular `DbFieldType::from_u16` gate and fails it.
    const BAD_DBR_TYPE: u16 = 9999;

    /// Build a write frame (`cmmd` = `CA_PROTO_WRITE` or
    /// `CA_PROTO_WRITE_NOTIFY`) addressed to `sid`, carrying `data_type`
    /// and an 8-byte (one DBR_DOUBLE) payload. `count == 1`.
    fn write_frame(cmmd: u16, sid: u32, ioid: u32, data_type: u16) -> Vec<u8> {
        let mut h = CaHeader::new(cmmd);
        h.data_type = data_type;
        h.count = 1;
        h.cid = sid;
        h.available = ioid;
        h.set_payload_size(8, 1);
        let mut frame = h.to_bytes().to_vec();
        frame.extend_from_slice(&0f64.to_be_bytes());
        frame
    }

    /// Read frames from `client` until one whose command is `want_cmmd`
    /// is seen; return it. Times out (panics) otherwise.
    async fn read_frame_of_cmmd<R: tokio::io::AsyncRead + Unpin>(
        client: &mut R,
        want_cmmd: u16,
        timeout: Duration,
    ) -> CaHeader {
        let mut acc: Vec<u8> = Vec::new();
        let mut buf = [0u8; 512];
        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            assert!(
                !remaining.is_zero(),
                "timed out waiting for cmmd {want_cmmd}"
            );
            let n = tokio::time::timeout(remaining, client.read(&mut buf))
                .await
                .expect("read within timeout")
                .expect("read ok");
            assert!(n > 0, "server closed before cmmd {want_cmmd}");
            acc.extend_from_slice(&buf[..n]);
            let mut offset = 0;
            while offset + CaHeader::SIZE <= acc.len() {
                let (hdr, hdr_size) =
                    CaHeader::from_bytes_extended(&acc[offset..]).expect("response header parses");
                let msg_len = hdr_size + hdr.actual_postsize();
                if offset + msg_len > acc.len() {
                    break;
                }
                if hdr.cmmd == want_cmmd {
                    return hdr;
                }
                offset += msg_len;
            }
        }
    }

    /// Spawn `handle_client` over a duplex pair with a read-only ACF
    /// (`RULE(0, READ)` — unconditional, write denied to every peer) and
    /// a single double SimplePv `caput:ro`. Returns the client half, the
    /// join handle, and the ACF-reload sender — the caller MUST keep the
    /// sender alive for the test's duration: the read loop polls
    /// `acf_reload_rx.recv()` biased-first, and a dropped sender resolves
    /// to `Closed`, which makes `handle_client` exit `Ok(())` before it
    /// ever reads a client frame.
    async fn spawn_read_only_server(
        peer_port: u16,
    ) -> (
        tokio::io::DuplexStream,
        tokio::task::JoinHandle<CaResult<()>>,
        broadcast::Sender<()>,
    ) {
        let db = Arc::new(PvDatabase::new());
        db.add_pv("caput:ro", EpicsValue::Double(0.0))
            .await
            .expect("add pv");
        let cfg = parse_acf("ASG(DEFAULT) { RULE(0, READ) }").expect("parse acf");
        let acf = Arc::new(tokio::sync::RwLock::new(Some(cfg)));
        let (acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);

        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = format!("127.0.0.1:{peer_port}").parse().unwrap();
        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                None,
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });
        (client_io, handle, acf_reload_tx)
    }

    /// Drive version + create-chan and return the server-assigned sid.
    async fn handshake(client: &mut tokio::io::DuplexStream) -> u32 {
        client.write_all(&version_frame()).await.expect("version");
        client
            .write_all(&create_chan_frame(0xC1, "caput:ro"))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");
        read_create_chan_sid(client, Duration::from_secs(3)).await
    }

    /// Deprecated `CA_PROTO_WRITE`, access-denied AND bad type: C
    /// `write_action` checks access FIRST → ECA_NOWTACCESS + RSRV_OK
    /// (keep). The error rides a `CA_PROTO_ERROR` reply (`m_available` =
    /// ECA status). Pre-fix the type-first path replied ECA_BADTYPE and
    /// dropped the connection.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn deprecated_write_denied_reports_nowtaccess_and_keeps_conn() {
        let (mut client, handle, _acf_reload_tx) = spawn_read_only_server(55330).await;
        let sid = handshake(&mut client).await;

        client
            .write_all(&write_frame(CA_PROTO_WRITE, sid, 0x42, BAD_DBR_TYPE))
            .await
            .expect("write");
        client.flush().await.expect("flush write");

        let err = read_frame_of_cmmd(&mut client, CA_PROTO_ERROR, Duration::from_secs(3)).await;
        assert_eq!(
            err.available, ECA_NOWTACCESS,
            "deprecated WRITE must report access denial first (ECA_NOWTACCESS), \
             not the type error (ECA_BADTYPE={ECA_BADTYPE}); got {}",
            err.available
        );

        // RSRV_OK after ECA_NOWTACCESS — the connection must stay up.
        tokio::time::sleep(Duration::from_millis(150)).await;
        assert!(
            !handle.is_finished(),
            "deprecated WRITE access-denied must KEEP the connection (C write_action RSRV_OK)"
        );

        drop(client);
        handle.abort();
    }

    /// `CA_PROTO_WRITE_NOTIFY`, same access-denied + bad type: C
    /// `write_notify_action` checks the TYPE FIRST → ECA_BADTYPE +
    /// RSRV_ERROR (drop). The error rides a `CA_PROTO_WRITE_NOTIFY` reply
    /// (`m_cid` = ECA status). This pins the opposite ordering so a future
    /// "unify the two opcodes" refactor cannot silently re-invert either.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn write_notify_bad_type_reports_badtype_and_drops_conn() {
        let (mut client, handle, _acf_reload_tx) = spawn_read_only_server(55331).await;
        let sid = handshake(&mut client).await;

        client
            .write_all(&write_frame(CA_PROTO_WRITE_NOTIFY, sid, 0x43, BAD_DBR_TYPE))
            .await
            .expect("write_notify");
        client.flush().await.expect("flush write_notify");

        let reply =
            read_frame_of_cmmd(&mut client, CA_PROTO_WRITE_NOTIFY, Duration::from_secs(3)).await;
        // send_put_notify_response carries the ECA status in `m_cid`.
        assert_eq!(
            reply.cid, ECA_BADTYPE,
            "WRITE_NOTIFY must report the type error first (ECA_BADTYPE), \
             not access (ECA_NOWTACCESS={ECA_NOWTACCESS}); got {}",
            reply.cid
        );

        // RSRV_ERROR after ECA_BADTYPE — the connection must drop.
        let res = tokio::time::timeout(Duration::from_secs(2), handle)
            .await
            .expect("handle_client completes after WRITE_NOTIFY bad type")
            .expect("join ok");
        assert!(
            res.is_err(),
            "WRITE_NOTIFY bad type must DROP the connection (C write_notify_action RSRV_ERROR), \
             got {res:?}"
        );

        drop(client);
    }
}

#[cfg(test)]
mod deprecated_read_autosize_tests {
    //! The deprecated synchronous CA_PROTO_READ (cmd 3) does NOT
    //! autosize a zero element count. C `read_action`
    //! (rsrv/camessage.c:622-645) sizes the reply with
    //! `dbr_size_n(type, m_count)`, writes the header count as `m_count`,
    //! and calls `dbChannel_get(.., m_count, ..)` — all verbatim. Only
    //! `read_reply` (READ_NOTIFY / EVENT_ADD, camessage.c:507-509) treats
    //! `m_count == 0` as "all available elements". So a deprecated READ
    //! with count==0 against a 3-element waveform must reply count=0 with
    //! a value-less payload, while a READ_NOTIFY with count==0 autosizes
    //! to the full 3-element array.
    use super::non_graceful_disconnect_teardown_tests::{
        create_chan_frame, read_create_chan_sid, version_frame,
    };
    use super::*;
    use epics_base_rs::server::database::PvDatabase;
    use epics_base_rs::types::{DBR_DOUBLE, EpicsValue};
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    /// Build a READ / READ_NOTIFY request for `sid` at `data_type` with
    /// the given element `count` (0 means "autosize" only on the NOTIFY
    /// opcode). No payload.
    fn read_request(cmmd: u16, sid: u32, ioid: u32, data_type: u16, count: u32) -> Vec<u8> {
        let mut h = CaHeader::new(cmmd);
        h.data_type = data_type;
        h.cid = sid;
        h.available = ioid;
        h.set_payload_size(0, count);
        h.to_bytes_extended().to_vec()
    }

    /// Read frames until one whose command is `want_cmmd` arrives; return
    /// its header. Panics on timeout / EOF.
    async fn read_frame_of_cmmd<R: tokio::io::AsyncRead + Unpin>(
        client: &mut R,
        want_cmmd: u16,
        timeout: Duration,
    ) -> CaHeader {
        let mut acc: Vec<u8> = Vec::new();
        let mut buf = [0u8; 512];
        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            assert!(
                !remaining.is_zero(),
                "timed out waiting for cmmd {want_cmmd}"
            );
            let n = tokio::time::timeout(remaining, client.read(&mut buf))
                .await
                .expect("read within timeout")
                .expect("read ok");
            assert!(n > 0, "server closed before cmmd {want_cmmd}");
            acc.extend_from_slice(&buf[..n]);
            let mut offset = 0;
            while offset + CaHeader::SIZE <= acc.len() {
                let (hdr, hdr_size) =
                    CaHeader::from_bytes_extended(&acc[offset..]).expect("response header parses");
                let msg_len = hdr_size + hdr.actual_postsize();
                if offset + msg_len > acc.len() {
                    break;
                }
                if hdr.cmmd == want_cmmd {
                    return hdr;
                }
                offset += msg_len;
            }
        }
    }

    /// Spawn `handle_client` over a duplex pair with a permissive (no
    /// ACF) server holding one waveform SimplePv `rd:arr` of `elems`.
    /// Returns the client half, the join handle, and the ACF-reload
    /// sender — the caller MUST keep the sender alive (a dropped sender
    /// makes the biased-first `acf_reload_rx.recv()` resolve `Closed`,
    /// exiting `handle_client` before it reads a client frame).
    async fn spawn_array_server(
        peer_port: u16,
        elems: Vec<f64>,
    ) -> (
        tokio::io::DuplexStream,
        tokio::task::JoinHandle<CaResult<()>>,
        broadcast::Sender<()>,
    ) {
        let db = Arc::new(PvDatabase::new());
        db.add_pv("rd:arr", EpicsValue::DoubleArray(elems))
            .await
            .expect("add array pv");
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);

        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = format!("127.0.0.1:{peer_port}").parse().unwrap();
        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                None,
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });
        (client_io, handle, acf_reload_tx)
    }

    async fn handshake(client: &mut tokio::io::DuplexStream) -> u32 {
        client.write_all(&version_frame()).await.expect("version");
        client
            .write_all(&create_chan_frame(0xD1, "rd:arr"))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");
        read_create_chan_sid(client, Duration::from_secs(3)).await
    }

    /// Deprecated CA_PROTO_READ (cmd 3), count==0 against a 3-element
    /// DBR_DOUBLE waveform: C ships count=0 + a value-less (0-byte for a
    /// plain DBR type) payload. Pre-fix Rust autosized to count=3 + 24
    /// payload bytes.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn deprecated_read_count0_ships_verbatim_zero() {
        let (mut client, handle, _acf_reload_tx) =
            spawn_array_server(55340, vec![1.0, 2.0, 3.0]).await;
        let sid = handshake(&mut client).await;

        client
            .write_all(&read_request(CA_PROTO_READ, sid, 0x11, DBR_DOUBLE, 0))
            .await
            .expect("read");
        client.flush().await.expect("flush read");

        let resp = read_frame_of_cmmd(&mut client, CA_PROTO_READ, Duration::from_secs(3)).await;
        assert_eq!(
            resp.actual_count(),
            0,
            "deprecated READ must echo m_count==0 verbatim (no autosize); got {}",
            resp.actual_count()
        );
        assert_eq!(
            resp.actual_postsize(),
            0,
            "deprecated READ count==0 of a plain DBR_DOUBLE ships a value-less \
             (dbr_size_n(type,0)==0) payload; got {} bytes",
            resp.actual_postsize()
        );

        drop(client);
        handle.abort();
    }

    /// Contrast: CA_PROTO_READ_NOTIFY (cmd 15), count==0 against the same
    /// waveform DOES autosize to the full 3-element array (C `read_reply`,
    /// camessage.c:507-509). Pins that the fix did not touch the NOTIFY
    /// autosize path.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn read_notify_count0_autosizes_to_full_array() {
        let (mut client, handle, _acf_reload_tx) =
            spawn_array_server(55341, vec![1.0, 2.0, 3.0]).await;
        let sid = handshake(&mut client).await;

        client
            .write_all(&read_request(
                CA_PROTO_READ_NOTIFY,
                sid,
                0x12,
                DBR_DOUBLE,
                0,
            ))
            .await
            .expect("read_notify");
        client.flush().await.expect("flush read_notify");

        let resp =
            read_frame_of_cmmd(&mut client, CA_PROTO_READ_NOTIFY, Duration::from_secs(3)).await;
        assert_eq!(
            resp.actual_count(),
            3,
            "READ_NOTIFY count==0 must autosize to the full native array; got {}",
            resp.actual_count()
        );
        assert_eq!(
            resp.actual_postsize(),
            24,
            "READ_NOTIFY count==0 ships all 3 DBR_DOUBLE elements (3*8=24 bytes); got {}",
            resp.actual_postsize()
        );

        drop(client);
        handle.abort();
    }
}

#[cfg(test)]
mod single_write_all_framing_tests {
    //! BUG 4: GET/READ_NOTIFY, introspection (`send_monitor_snapshot`)
    //! and CA_PROTO_ERROR (`send_ca_error`) replies must be written to
    //! the shared `BufWriter` as ONE contiguous `write_all`. A split
    //! across two `write_all` awaits lets a `send_timeout` cancel land
    //! between header and payload, leaving an orphan header that
    //! mis-frames every following message. A true cancel-race is
    //! non-deterministic; this asserts the structural property that
    //! makes the race impossible: exactly one write batch == one frame.
    use super::*;
    use std::pin::Pin;
    use std::sync::Arc;
    use std::task::{Context, Poll};

    /// Mock `AsyncWrite` recording each `poll_write` batch. Wrapped in a
    /// zero-capacity `BufWriter`, batch count == `write_all` count.
    #[derive(Default)]
    struct RecordingWriter {
        batches: Vec<Vec<u8>>,
    }

    impl AsyncWrite for RecordingWriter {
        fn poll_write(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<std::io::Result<usize>> {
            self.batches.push(buf.to_vec());
            Poll::Ready(Ok(buf.len()))
        }
        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            Poll::Ready(Ok(()))
        }
        fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            Poll::Ready(Ok(()))
        }
    }

    fn recording_writer() -> Arc<Mutex<BufWriter<RecordingWriter>>> {
        // Zero capacity: every write_all forwards straight through.
        Arc::new(Mutex::new(BufWriter::with_capacity(
            0,
            RecordingWriter::default(),
        )))
    }

    /// `send_ca_error` builds response-header + echoed-request-header +
    /// diagnostic string. All three must leave in a single `write_all`.
    #[tokio::test]
    async fn send_ca_error_writes_single_frame() {
        let writer = recording_writer();
        let original = CaHeader::new(CA_PROTO_READ_NOTIFY);

        send_ca_error(
            &writer,
            &original,
            ECA_INTERNAL,
            0xFFFF_FFFF,
            "CAS: Missaligned protocol rejected",
        )
        .await
        .expect("send_ca_error succeeds");

        let guard = writer.lock().await;
        let batches = &guard.get_ref().batches;
        assert_eq!(
            batches.len(),
            1,
            "send_ca_error must issue exactly one write_all (got {} batches: {:?})",
            batches.len(),
            batches.iter().map(|b| b.len()).collect::<Vec<_>>(),
        );
        // The one batch must be the complete frame: response header +
        // 16-byte echoed request header + padded diagnostic string.
        let frame = &batches[0];
        let payload_size = u16::from_be_bytes([frame[2], frame[3]]) as usize;
        assert_eq!(
            16 + payload_size,
            frame.len(),
            "CA_PROTO_ERROR header-declared size must match the contiguous frame",
        );
    }

    /// READ_NOTIFY get-failure / no-snapshot wire shape: C `read_reply`
    /// `status < 0` branch (`rsrv/camessage.c:548-562`) keeps the
    /// CA_PROTO_READ_NOTIFY reply at the requested count, abuses `m_cid`
    /// to carry the ECA status, and commits a `dbr_size_n(type, count)`
    /// ZEROED body. The pre-fix `send_cmd_error` shipped `count=0` + an
    /// empty body; this locks the corrected `send_no_read_access_event`
    /// shape the get-failure and no-snapshot paths now use.
    #[tokio::test]
    async fn read_notify_get_failure_frame_keeps_count_and_zero_body() {
        let writer = recording_writer();
        let requested_count = 3u32;
        // DBR_TIME_DOUBLE = compound type with 16-byte metadata, so the
        // get-failure body is non-empty even though every byte is zero —
        // exactly where `count=0`/empty diverged from C.
        send_no_read_access_event(
            &writer,
            CA_PROTO_READ_NOTIFY,
            epics_base_rs::types::DBR_TIME_DOUBLE,
            requested_count,
            0x4242_4242, // ioid echoed into m_available
            ECA_GETFAIL,
        )
        .await
        .expect("send_no_read_access_event succeeds");

        let guard = writer.lock().await;
        let batches = &guard.get_ref().batches;
        assert_eq!(batches.len(), 1, "one contiguous write_all");
        let frame = &batches[0];
        let hdr = CaHeader::from_bytes(&frame[..16]).expect("parse READ_NOTIFY header");
        assert_eq!(hdr.cmmd, CA_PROTO_READ_NOTIFY, "stays a READ_NOTIFY reply");
        assert_eq!(hdr.data_type, epics_base_rs::types::DBR_TIME_DOUBLE);
        assert_eq!(
            hdr.actual_count(),
            requested_count,
            "C preserves the requested count, not 0"
        );
        assert_eq!(hdr.cid, ECA_GETFAIL, "m_cid abused to carry the ECA status");
        assert_eq!(hdr.available, 0x4242_4242);

        // body = dbr_size_n(type, count), 8-aligned, all zero.
        let native =
            epics_base_rs::types::native_type_for_dbr(epics_base_rs::types::DBR_TIME_DOUBLE)
                .expect("native type");
        let body_size = epics_base_rs::types::dbr_buffer_size(
            epics_base_rs::types::DBR_TIME_DOUBLE,
            native,
            requested_count as usize,
        );
        let padded = align8(body_size);
        assert!(
            padded > 0,
            "compound DBR get-failure body must be non-empty"
        );
        assert_eq!(
            hdr.actual_postsize(),
            padded,
            "m_postsize is dbr_size_n(type, count), not 0"
        );
        assert_eq!(
            frame.len(),
            16 + padded,
            "single frame = header + zero body"
        );
        assert!(
            frame[16..].iter().all(|&b| b == 0),
            "the get-failure body is entirely zero-filled"
        );
    }

    /// Regression: when the original request used an extended
    /// 24-byte header, the outer CA_PROTO_ERROR reply must declare
    /// `m_postsize = 24 + diag_len`, not `16 + diag_len`.
    #[tokio::test]
    async fn send_ca_error_extended_original_declares_correct_payload_size() {
        let writer = recording_writer();
        // Build an extended original header: set_payload_size triggers
        // extended form when count >= 0xFFFF.
        let mut original = CaHeader::new(CA_PROTO_READ_NOTIFY);
        original.set_payload_size(0, 0x1_0000); // count >= 0xFFFF → extended (24 bytes)
        assert!(
            original.is_extended(),
            "test requires an extended original header"
        );

        send_ca_error(
            &writer,
            &original,
            ECA_INTERNAL,
            0xFFFF_FFFF,
            "Regression test",
        )
        .await
        .expect("send_ca_error succeeds");

        let guard = writer.lock().await;
        let batches = &guard.get_ref().batches;
        assert_eq!(batches.len(), 1, "must issue exactly one write_all");
        let frame = &batches[0];
        // Outer CA_PROTO_ERROR response header is normal form (payload < 0xFFFF);
        // m_postsize lives at bytes [2..4].
        let declared = u16::from_be_bytes([frame[2], frame[3]]) as usize;
        assert_eq!(
            16 + declared,
            frame.len(),
            "declared m_postsize must account for the full payload (echo hdr + diag)"
        );
        // With an extended original, the echoed header contributes 24 bytes.
        // Any diagnostic shorter than 0xFFFF − 24 keeps the outer header normal.
        // Echo header occupies frame bytes [16..40]; those 24 bytes must round-trip
        // the extended marker (postsize field = 0xFFFF at echo-hdr offset 2..4).
        let echo_postsize = u16::from_be_bytes([frame[18], frame[19]]);
        assert_eq!(
            echo_postsize, 0xFFFF,
            "echoed request header must preserve the extended marker (m_postsize = 0xFFFF)"
        );
    }

    /// `send_monitor_snapshot` (the introspection EVENT_ADD reply) must
    /// emit header + padded payload as a single `write_all`.
    #[tokio::test]
    async fn send_monitor_snapshot_writes_single_frame() {
        use epics_base_rs::server::snapshot::Snapshot;
        use epics_base_rs::types::{DBR_LONG, EpicsValue};

        let writer = recording_writer();
        let snapshot = Snapshot::new(
            EpicsValue::Long(123),
            0,
            0,
            std::time::SystemTime::UNIX_EPOCH,
        );

        // requested_count 0 = autosize: frame the live element count.
        send_monitor_snapshot(&writer, 9, DBR_LONG, 0, &snapshot)
            .await
            .expect("send_monitor_snapshot succeeds");

        let guard = writer.lock().await;
        let batches = &guard.get_ref().batches;
        assert_eq!(
            batches.len(),
            1,
            "send_monitor_snapshot must issue exactly one write_all (got {} batches: {:?})",
            batches.len(),
            batches.iter().map(|b| b.len()).collect::<Vec<_>>(),
        );
    }

    /// an initial monitor snapshot for an EVENT_ADD whose
    /// request count exceeds the live element count must be framed at
    /// the requested count with a zero-padded payload — the same
    /// shape the READ path and later monitor updates use. Pre-fix the
    /// initial frame was framed at `snapshot.value.count()`, so a
    /// client saw a count/size discontinuity inside one subscription.
    #[tokio::test]
    async fn ex_r9_initial_snapshot_pads_over_requested_count() {
        use epics_base_rs::server::snapshot::Snapshot;
        use epics_base_rs::types::{DBR_LONG, DbFieldType, EpicsValue};

        // Live PV holds 3 LONG elements; the client requested 8.
        let snapshot = Snapshot::new(
            EpicsValue::LongArray(vec![10, 20, 30]),
            0,
            0,
            std::time::SystemTime::UNIX_EPOCH,
        );
        let requested_count = 8u32;

        let writer = recording_writer();
        send_monitor_snapshot(&writer, 9, DBR_LONG, requested_count, &snapshot)
            .await
            .expect("send_monitor_snapshot succeeds");

        let guard = writer.lock().await;
        let batches = &guard.get_ref().batches;
        assert_eq!(batches.len(), 1, "exactly one contiguous frame");
        let frame = &batches[0];

        // Standard 16-byte CA header: count 8 and the resulting
        // payload both fit under the 0xFFFF extended-form threshold.
        let postsize = u16::from_be_bytes([frame[2], frame[3]]) as usize;
        let count = u16::from_be_bytes([frame[6], frame[7]]) as u32;
        assert_eq!(
            count, requested_count,
            "the initial monitor frame must carry the REQUESTED \
             element count (8), not the live count (3)"
        );

        // DBR_LONG is a plain type (no metadata); the payload must
        // hold the requested element count of value bytes, zero-
        // padded for the elements the PV does not have.
        let elem = DbFieldType::Long.element_size();
        let value_bytes = requested_count as usize * elem;
        assert!(
            postsize >= value_bytes,
            "payload ({postsize}) must be padded to at least the \
             requested {requested_count} elements ({value_bytes} bytes)"
        );
        // The three live elements come first, then zero padding.
        let body = &frame[16..16 + postsize];
        assert_eq!(&body[0..4], &10i32.to_be_bytes(), "element 0 preserved");
        assert_eq!(&body[8..12], &30i32.to_be_bytes(), "element 2 preserved");
        assert!(
            body[3 * elem..value_bytes].iter().all(|&b| b == 0),
            "over-requested elements must be zero-filled"
        );
    }

    /// a request count SMALLER than the live element count
    /// still truncates — `send_monitor_snapshot` must own both
    /// directions of the count contract.
    #[tokio::test]
    async fn ex_r9_initial_snapshot_truncates_under_requested_count() {
        use epics_base_rs::server::snapshot::Snapshot;
        use epics_base_rs::types::{DBR_LONG, EpicsValue};

        let snapshot = Snapshot::new(
            EpicsValue::LongArray(vec![1, 2, 3, 4, 5]),
            0,
            0,
            std::time::SystemTime::UNIX_EPOCH,
        );
        let writer = recording_writer();
        send_monitor_snapshot(&writer, 9, DBR_LONG, 2, &snapshot)
            .await
            .expect("send_monitor_snapshot succeeds");

        let guard = writer.lock().await;
        let frame = &guard.get_ref().batches[0];
        let count = u16::from_be_bytes([frame[6], frame[7]]) as u32;
        assert_eq!(count, 2, "under-requested count must truncate to 2");
    }

    /// `requested_count == 0` is autosize — the frame keeps the
    /// live element count, unchanged behaviour.
    #[tokio::test]
    async fn ex_r9_autosize_keeps_live_count() {
        use epics_base_rs::server::snapshot::Snapshot;
        use epics_base_rs::types::{DBR_LONG, EpicsValue};

        let snapshot = Snapshot::new(
            EpicsValue::LongArray(vec![7, 8, 9, 10]),
            0,
            0,
            std::time::SystemTime::UNIX_EPOCH,
        );
        let writer = recording_writer();
        send_monitor_snapshot(&writer, 9, DBR_LONG, 0, &snapshot)
            .await
            .expect("send_monitor_snapshot succeeds");

        let guard = writer.lock().await;
        let frame = &guard.get_ref().batches[0];
        let count = u16::from_be_bytes([frame[6], frame[7]]) as u32;
        assert_eq!(count, 4, "autosize (count==0) keeps the live count");
    }
}

#[cfg(test)]
mod ex_r6_no_read_access_count_tests {
    //! an autosize (`count == 0`) no-read-access EVENT_ADD
    //! denial must be sized to a nonzero DBR body. A zero-payload
    //! `CA_PROTO_EVENT_ADD` is the historical subscription-cancel
    //! confirmation no-op; the CA client drops it before reading the
    //! `ECA_NORDACCESS` status, so a denied autosize monitor would
    //! silently appear to hang.
    use super::no_read_access_count;
    use epics_base_rs::types::{DbFieldType, dbr_buffer_size};

    /// Autosize (`requested_count == 0`) must normalise to the
    /// target's live element count — mirrors C `read_reply`
    /// substituting `paddr->no_elements` (`camessage.c:507-509`).
    #[test]
    fn ex_r6_autosize_normalises_to_actual_count() {
        assert_eq!(no_read_access_count(0, 7), 7);
        // A scalar (1 element) autosize denial still gets a body.
        assert_eq!(no_read_access_count(0, 1), 1);
        // A target reporting zero live elements is floored at one so
        // the frame is never zero-payload.
        assert_eq!(no_read_access_count(0, 0), 1);
    }

    /// An explicit non-zero request count is framed unchanged — the
    /// caller already asked for a definite shape.
    #[test]
    fn ex_r6_explicit_count_passes_through() {
        assert_eq!(no_read_access_count(3, 7), 3);
        assert_eq!(no_read_access_count(1, 100), 1);
    }

    /// The defect proof: with the pre-fix raw `count == 0`, the
    /// `dbr_buffer_size` of a plain DBR type (`DBR_DOUBLE`) is zero,
    /// producing the cancel-ack-shaped frame. After normalisation the
    /// payload is strictly positive, so the client's status-error
    /// path runs. `DBR_DOUBLE == 6` is a plain (non-STS) type, so its
    /// metadata size is zero — the value bytes are the whole payload.
    #[test]
    fn ex_r6_normalised_count_yields_nonzero_plain_dbr_payload() {
        const DBR_DOUBLE: u16 = 6;
        // Pre-fix shape: raw autosize count 0 → zero-payload frame
        // (indistinguishable from an EVENT_CANCEL ack).
        assert_eq!(
            dbr_buffer_size(DBR_DOUBLE, DbFieldType::Double, 0),
            0,
            "regression baseline: a raw count==0 plain-DBR denial is \
             zero-payload — the cancel-ack shape later normalised"
        );
        // After normalisation the denial frame carries a real
        // DBR body, so the client sees the ECA_NORDACCESS status.
        let normalised = no_read_access_count(0, 4) as usize;
        let payload = dbr_buffer_size(DBR_DOUBLE, DbFieldType::Double, normalised);
        assert!(
            payload > 0,
            "a normalised autosize denial must have a nonzero \
             DBR payload so the client does not drop it as a cancel-ack"
        );
        assert_eq!(payload, 4 * DbFieldType::Double.element_size());
    }
}

#[cfg(test)]
mod bfr7_event_context_filter_tests {
    //! a CA monitor initial single-event post
    //! (`db_post_single_event`, `rsrv/camessage.c:1853`) runs the
    //! channel filter chain in EVENT context (`db_create_event_log` →
    //! `dbfl_context_event`), NOT in one-shot READ context. `dec`/`sync`
    //! therefore decimate/gate the initial event, and a chain that drops
    //! the post sends NO initial `EVENT_ADD` frame (C
    //! `db_queue_event_log` fires only `if(pLog)`) — never an unfiltered
    //! fallback.
    //!
    //! These drive the full `handle_client` EVENT_ADD path; the
    //! deterministic context split (read bypasses `sync`, event gates it)
    //! is also unit-proven in
    //! `epics_base_rs::server::database::filters` tests.
    use super::non_graceful_disconnect_teardown_tests::{
        await_event, create_chan_frame, event_add_frame, read_create_chan_sid, version_frame,
    };
    use super::*;
    use epics_base_rs::server::database::PvDatabase;
    use epics_base_rs::types::EpicsValue;
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    /// Read frames from `client` for `window`, returning the
    /// `(cmd, postsize)` of every COMPLETE CA frame observed. Used to
    /// assert presence/absence of an initial `CA_PROTO_EVENT_ADD` data
    /// frame.
    async fn collect_frames<R: tokio::io::AsyncRead + Unpin>(
        client: &mut R,
        window: Duration,
    ) -> Vec<(u16, usize)> {
        let mut acc: Vec<u8> = Vec::new();
        let mut frames: Vec<(u16, usize)> = Vec::new();
        let mut buf = [0u8; 512];
        let deadline = tokio::time::Instant::now() + window;
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            if remaining.is_zero() {
                break;
            }
            match tokio::time::timeout(remaining, client.read(&mut buf)).await {
                Ok(Ok(0)) => break, // EOF
                Ok(Ok(n)) => {
                    acc.extend_from_slice(&buf[..n]);
                    let mut offset = 0;
                    while offset + CaHeader::SIZE <= acc.len() {
                        let Ok((hdr, hdr_size)) = CaHeader::from_bytes_extended(&acc[offset..])
                        else {
                            break;
                        };
                        let msg_len = hdr_size + hdr.actual_postsize();
                        if offset + msg_len > acc.len() {
                            break;
                        }
                        frames.push((hdr.cmmd, hdr.actual_postsize()));
                        offset += msg_len;
                    }
                    acc.drain(0..offset);
                }
                Ok(Err(_)) | Err(_) => break,
            }
        }
        frames
    }

    /// Spawn `handle_client` over a duplex socket; returns the client
    /// half, the join handle, the connection-event receiver, and the
    /// ACF-reload sender. The caller MUST keep the sender alive for the
    /// connection's lifetime — dropping it closes the ACF-reload
    /// broadcast, which `handle_client` treats as a shutdown signal.
    fn spawn_server(
        db: Arc<PvDatabase>,
        port: u16,
    ) -> (
        tokio::io::DuplexStream,
        tokio::task::JoinHandle<CaResult<()>>,
        broadcast::Receiver<ServerConnectionEvent>,
        broadcast::Sender<()>,
    ) {
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);
        let (conn_tx, conn_rx) = broadcast::channel::<ServerConnectionEvent>(64);
        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                Some(conn_tx),
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });
        (client_io, handle, conn_rx, acf_reload_tx)
    }

    /// Open a subscription on `pv_name` and return every frame the
    /// server emits in the `window` after the subscription opens.
    /// Asserts the subscription actually opened so a missing initial
    /// frame is never a vacuous pass.
    async fn subscribe_and_collect(pv_name: &str, port: u16) -> Vec<(u16, usize)> {
        let db = Arc::new(PvDatabase::new());
        db.add_pv("bfr7:pv", EpicsValue::Double(42.0))
            .await
            .expect("add pv");
        let (mut client, handle, mut conn_rx, _acf_reload_tx) = spawn_server(db, port);

        client.write_all(&version_frame()).await.expect("version");
        client
            .write_all(&create_chan_frame(0xA1, pv_name))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");
        let sid = read_create_chan_sid(&mut client, Duration::from_secs(3)).await;

        client
            .write_all(&event_add_frame(sid, 0xB1))
            .await
            .expect("event_add");
        client.flush().await.expect("flush event_add");

        let opened = await_event(&mut conn_rx, Duration::from_secs(3), |ev| {
            matches!(ev, ServerConnectionEvent::SubscriptionOpened { .. })
        })
        .await;
        assert!(
            matches!(opened, Some(ServerConnectionEvent::SubscriptionOpened { sub_id, .. }) if sub_id == 0xB1),
            "subscription must open (else the no-initial-frame assertion is vacuous): got {opened:?}"
        );

        let frames = collect_frames(&mut client, Duration::from_millis(700)).await;
        drop(client);
        let _ = tokio::time::timeout(Duration::from_secs(2), handle).await;
        frames
    }

    /// Regression: a `sync` filter gating `while` a never-set
    /// state drops the initial monitor post in EVENT context, so the
    /// server sends NO `CA_PROTO_EVENT_ADD` data frame. Pre-fix the
    /// initial post ran in READ context (`apply_to_read_value`), where
    /// `sync` is bypassed, so an initial frame WAS sent — this test
    /// fails against that behaviour.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn event_context_sync_gate_suppresses_initial_event() {
        let pv = r#"bfr7:pv.{"sync":{"while":"BFR7:NEVERSET"}}"#;
        let frames = subscribe_and_collect(pv, 55301).await;
        let event_adds: Vec<_> = frames
            .iter()
            .filter(|(cmd, _)| *cmd == CA_PROTO_EVENT_ADD)
            .collect();
        assert!(
            event_adds.is_empty(),
            "the event-context `sync` gate must suppress the \
             initial EVENT_ADD post — no fallback to the unfiltered \
             value (got {event_adds:?})"
        );
    }

    /// Control: an unfiltered channel still sends exactly one initial
    /// `CA_PROTO_EVENT_ADD` data frame — proving the harness/timing is
    /// sound and the suppression above is the filter's doing, not a
    /// dropped read.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn plain_channel_sends_initial_event() {
        let frames = subscribe_and_collect("bfr7:pv", 55302).await;
        let event_adds = frames
            .iter()
            .filter(|(cmd, _)| *cmd == CA_PROTO_EVENT_ADD)
            .count();
        assert!(
            event_adds >= 1,
            "control: an unfiltered channel must send an initial \
             EVENT_ADD frame (got frames {frames:?})"
        );
    }

    /// a `dec` filter whose window offset skips slot 0
    /// (`offset = 1`) drops the FIRST event in EVENT context — the
    /// initial monitor post lands on a fresh decimator counter at
    /// position 0, which is decimated away. READ context would bypass
    /// the decimator and send it.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn event_context_decimator_suppresses_initial_event() {
        let pv = r#"bfr7:pv.{"dec":{"n":2,"offset":1}}"#;
        let frames = subscribe_and_collect(pv, 55303).await;
        let event_adds: Vec<_> = frames
            .iter()
            .filter(|(cmd, _)| *cmd == CA_PROTO_EVENT_ADD)
            .collect();
        assert!(
            event_adds.is_empty(),
            "the event-context decimator must drop the initial \
             EVENT_ADD post (offset 1 skips window slot 0): got {event_adds:?}"
        );
    }
}

#[cfg(test)]
mod r46_zero_mask_event_add_tests {
    //! EVENT_ADD with mask=0 must be rejected with CA_PROTO_ERROR
    //! (ECA_ALLOCMEM) + connection close.
    //!
    //! C reference: `db_add_event` (dbEvent.c:437-439) returns NULL when
    //! `select==0`; `event_add_action` (camessage.c:1814-1822) then calls
    //! `send_err(ECA_ALLOCMEM)` and returns `RSRV_ERROR`, closing the
    //! connection.  Previously the Rust server silently installed a dead
    //! subscription whose `Subscriber::accepts` always returned false, so
    //! no events ever arrived after the initial snapshot.
    use super::non_graceful_disconnect_teardown_tests::{
        create_chan_frame, read_create_chan_sid, version_frame,
    };
    use super::*;
    use epics_base_rs::server::database::PvDatabase;
    use epics_base_rs::types::EpicsValue;
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    /// Build a CA_PROTO_EVENT_ADD request with mask=0 (the defect input).
    fn event_add_zero_mask_frame(sid: u32, sub_id: u32) -> Vec<u8> {
        let mut h = CaHeader::new(CA_PROTO_EVENT_ADD);
        h.data_type = epics_base_rs::types::DBR_TIME_DOUBLE;
        h.count = 1;
        h.cid = sid;
        h.available = sub_id;
        h.set_payload_size(16, 1);
        let mut frame = h.to_bytes().to_vec();
        frame.extend_from_slice(&0f32.to_be_bytes());
        frame.extend_from_slice(&0f32.to_be_bytes());
        frame.extend_from_slice(&0f32.to_be_bytes());
        frame.extend_from_slice(&0u16.to_be_bytes()); // mask = 0 — the defect input
        frame.extend_from_slice(&0u16.to_be_bytes()); // pad
        frame
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn zero_mask_event_add_replies_eca_allocmem_and_disconnects() {
        let db = Arc::new(PvDatabase::new());
        db.add_pv("r46:pv", EpicsValue::Double(0.0))
            .await
            .expect("add pv");
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (_acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);
        let (conn_tx, _conn_rx) = broadcast::channel::<ServerConnectionEvent>(64);

        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = "127.0.0.1:55400".parse().unwrap();

        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                Some(conn_tx),
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });

        let mut client = client_io;
        client.write_all(&version_frame()).await.expect("version");
        client
            .write_all(&create_chan_frame(1, "r46:pv"))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");
        let sid = read_create_chan_sid(&mut client, Duration::from_secs(3)).await;

        // Send the defect input: EVENT_ADD with mask=0.
        client
            .write_all(&event_add_zero_mask_frame(sid, 0xC0DE))
            .await
            .expect("zero-mask event_add");
        client.flush().await.expect("flush zero-mask event_add");

        // Read server output until EOF; expect at least one CA_PROTO_ERROR
        // frame before the connection closes.
        let mut acc: Vec<u8> = Vec::new();
        let mut buf = [0u8; 256];
        let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            assert!(
                !remaining.is_zero(),
                "timed out waiting for server to close"
            );
            match tokio::time::timeout(remaining, client.read(&mut buf)).await {
                Ok(Ok(0)) => break, // EOF — server closed
                Ok(Ok(n)) => acc.extend_from_slice(&buf[..n]),
                Ok(Err(_)) | Err(_) => break,
            }
        }

        // Scan the accumulated bytes for a CA_PROTO_ERROR frame.
        let mut got_error = false;
        let mut offset = 0;
        while offset + CaHeader::SIZE <= acc.len() {
            if let Ok((hdr, hdr_size)) = CaHeader::from_bytes_extended(&acc[offset..]) {
                if hdr.cmmd == CA_PROTO_ERROR {
                    got_error = true;
                    break;
                }
                let msg_len = hdr_size + hdr.actual_postsize();
                if msg_len == 0 {
                    break;
                }
                offset += msg_len;
            } else {
                break;
            }
        }
        assert!(
            got_error,
            "zero-mask EVENT_ADD must produce a CA_PROTO_ERROR (ECA_ALLOCMEM) \
             reply before the connection closes (received {} bytes: {acc:?})",
            acc.len()
        );

        // The handler must exit with Err (RSRV_ERROR path, not graceful EOF).
        let res = tokio::time::timeout(Duration::from_secs(2), handle)
            .await
            .expect("handle_client completes after zero-mask rejection")
            .expect("join ok");
        assert!(
            res.is_err(),
            "zero-mask EVENT_ADD must close the connection with Err \
             (matches C RSRV_ERROR), got {res:?}"
        );
    }

    /// Build a CA_PROTO_EVENT_ADD request with an arbitrary `mask`.
    fn event_add_mask_frame(sid: u32, sub_id: u32, mask: u16) -> Vec<u8> {
        let mut h = CaHeader::new(CA_PROTO_EVENT_ADD);
        h.data_type = epics_base_rs::types::DBR_TIME_DOUBLE;
        h.count = 1;
        h.cid = sid;
        h.available = sub_id;
        h.set_payload_size(16, 1);
        let mut frame = h.to_bytes().to_vec();
        frame.extend_from_slice(&0f32.to_be_bytes());
        frame.extend_from_slice(&0f32.to_be_bytes());
        frame.extend_from_slice(&0f32.to_be_bytes());
        frame.extend_from_slice(&mask.to_be_bytes());
        frame.extend_from_slice(&0u16.to_be_bytes()); // pad
        frame
    }

    /// Regression: a mask above UCHAR_MAX (256, reachable because the CA
    /// wire mask is a `u16`) must be rejected exactly like mask==0. C
    /// `db_add_event` (dbEvent.c:437) returns NULL for
    /// `select == 0 || select > UCHAR_MAX`, which `event_add_action` turns
    /// into ECA_ALLOCMEM + RSRV_ERROR (camessage.c:1814-1822). The previous
    /// guard checked only mask==0, so a mask in 256..=65535 silently
    /// installed a never-firing subscription.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn over_max_mask_event_add_replies_eca_allocmem_and_disconnects() {
        let db = Arc::new(PvDatabase::new());
        db.add_pv("r46:pv", EpicsValue::Double(0.0))
            .await
            .expect("add pv");
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (_acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);
        let (conn_tx, _conn_rx) = broadcast::channel::<ServerConnectionEvent>(64);

        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = "127.0.0.1:55402".parse().unwrap();

        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                Some(conn_tx),
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });

        let mut client = client_io;
        client.write_all(&version_frame()).await.expect("version");
        client
            .write_all(&create_chan_frame(1, "r46:pv"))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");
        let sid = read_create_chan_sid(&mut client, Duration::from_secs(3)).await;

        // mask = 256 — one past UCHAR_MAX.
        client
            .write_all(&event_add_mask_frame(sid, 0xC0DE, 256))
            .await
            .expect("over-max event_add");
        client.flush().await.expect("flush over-max event_add");

        let mut acc: Vec<u8> = Vec::new();
        let mut buf = [0u8; 256];
        let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            assert!(
                !remaining.is_zero(),
                "timed out waiting for server to close"
            );
            match tokio::time::timeout(remaining, client.read(&mut buf)).await {
                Ok(Ok(0)) => break, // EOF — server closed
                Ok(Ok(n)) => acc.extend_from_slice(&buf[..n]),
                Ok(Err(_)) | Err(_) => break,
            }
        }

        let mut got_error = false;
        let mut offset = 0;
        while offset + CaHeader::SIZE <= acc.len() {
            if let Ok((hdr, hdr_size)) = CaHeader::from_bytes_extended(&acc[offset..]) {
                if hdr.cmmd == CA_PROTO_ERROR {
                    got_error = true;
                    break;
                }
                let msg_len = hdr_size + hdr.actual_postsize();
                if msg_len == 0 {
                    break;
                }
                offset += msg_len;
            } else {
                break;
            }
        }
        assert!(
            got_error,
            "mask>UCHAR_MAX EVENT_ADD must produce a CA_PROTO_ERROR (ECA_ALLOCMEM) \
             reply before the connection closes (received {} bytes: {acc:?})",
            acc.len()
        );

        let res = tokio::time::timeout(Duration::from_secs(2), handle)
            .await
            .expect("handle_client completes after over-max-mask rejection")
            .expect("join ok");
        assert!(
            res.is_err(),
            "mask>UCHAR_MAX EVENT_ADD must close the connection with Err \
             (matches C RSRV_ERROR), got {res:?}"
        );
    }

    /// Guard-ordering regression: an EVENT_ADD carrying an unknown/stale
    /// SID *and* mask==0 must emit the bad-SID `ECA_INTERNAL` "Bad
    /// Resource ID" frame, NOT the spurious `ECA_ALLOCMEM` mask frame. In
    /// C `event_add_action` the missing-channel branch (`if (!pciu) {
    /// logBadId; return RSRV_ERROR; }`, camessage.c:1773-1777) runs
    /// *before* the `db_add_event` NULL (select==0) ALLOCMEM path
    /// (camessage.c:1814-1822). `logBadId` (camessage.c:307-320) sends
    /// `send_err(ECA_INTERNAL, "Bad Resource ID")` with the cid=0xFFFFFFFF
    /// sentinel (MPTOPCIU→NULL), flushed by camsgtask.c:142 before the
    /// disconnect — so an unknown SID draws ECA_INTERNAL regardless of
    /// mask. The defective guard ran the mask==0 check before the channel
    /// lookup and replied `CA_PROTO_ERROR(ECA_ALLOCMEM, m_cid=0xFFFF_FFFF)`
    /// here.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn unknown_sid_zero_mask_event_add_sends_bad_resource_id() {
        let db = Arc::new(PvDatabase::new());
        db.add_pv("r46:pv", EpicsValue::Double(0.0))
            .await
            .expect("add pv");
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (_acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);
        let (conn_tx, _conn_rx) = broadcast::channel::<ServerConnectionEvent>(64);

        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = "127.0.0.1:55401".parse().unwrap();

        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                Some(conn_tx),
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });

        let mut client = client_io;
        client.write_all(&version_frame()).await.expect("version");
        client
            .write_all(&create_chan_frame(1, "r46:pv"))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");
        let sid = read_create_chan_sid(&mut client, Duration::from_secs(3)).await;

        // Target a SID the server never assigned: unknown/stale channel.
        let unknown_sid = sid.wrapping_add(0xDEAD);
        assert_ne!(
            unknown_sid, sid,
            "test must use a SID distinct from the real one"
        );
        client
            .write_all(&event_add_zero_mask_frame(unknown_sid, 0xC0DE))
            .await
            .expect("unknown-sid zero-mask event_add");
        client
            .flush()
            .await
            .expect("flush unknown-sid zero-mask event_add");

        // Read server output until EOF; the unknown SID must produce the
        // bad-SID `ECA_INTERNAL` frame, then the server closes.
        let acc = drain_to_eof(&mut client, Duration::from_secs(3)).await;

        // The first CA_PROTO_ERROR frame must be the bad-SID ECA_INTERNAL
        // ("Bad Resource ID") frame with the 0xFFFFFFFF cid sentinel — NOT
        // the mask-path ECA_ALLOCMEM frame the defective guard emitted.
        let err = first_ca_proto_error(&acc).unwrap_or_else(|| {
            panic!(
                "EVENT_ADD on an unknown SID with mask=0 must emit the bad-SID \
                 ECA_INTERNAL frame (C logBadId), but no CA_PROTO_ERROR was emitted \
                 (received {} bytes: {acc:?})",
                acc.len()
            )
        });
        assert_eq!(
            err.available, ECA_INTERNAL,
            "Guard ordering: unknown-SID EVENT_ADD must reply ECA_INTERNAL \
             (bad-SID logBadId), not ECA_ALLOCMEM (mask path); got eca={:#x}",
            err.available
        );
        assert_eq!(
            err.cid, 0xFFFF_FFFF,
            "bad-SID ECA_INTERNAL frame echoes the 0xFFFFFFFF cid sentinel \
             (MPTOPCIU→NULL ⇒ vsend_err cid=0xffffffff), got {:#x}",
            err.cid
        );

        // The handler still closes the connection with Err (RSRV_ERROR).
        let res = tokio::time::timeout(Duration::from_secs(2), handle)
            .await
            .expect("handle_client completes after unknown-sid event_add")
            .expect("join ok");
        assert!(
            res.is_err(),
            "Guard ordering: unknown-SID EVENT_ADD must close the connection with \
             Err (matches C RSRV_ERROR), got {res:?}"
        );
    }

    /// Build a deprecated CA_PROTO_READ (cmd=3) request addressing
    /// `sid` with DBR `data_type`, element `count`, and read `ioid`.
    fn read_frame(sid: u32, data_type: u16, count: u16, ioid: u32) -> Vec<u8> {
        let mut h = CaHeader::new(CA_PROTO_READ);
        h.data_type = data_type;
        h.count = count;
        h.cid = sid;
        h.available = ioid;
        h.to_bytes().to_vec()
    }

    /// Read all server output until EOF (server closed) or `timeout`.
    async fn drain_to_eof<R: tokio::io::AsyncRead + Unpin>(
        client: &mut R,
        timeout: Duration,
    ) -> Vec<u8> {
        let mut acc: Vec<u8> = Vec::new();
        let mut buf = [0u8; 256];
        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            assert!(
                !remaining.is_zero(),
                "timed out waiting for server to close"
            );
            match tokio::time::timeout(remaining, client.read(&mut buf)).await {
                Ok(Ok(0)) => break,
                Ok(Ok(n)) => acc.extend_from_slice(&buf[..n]),
                Ok(Err(_)) | Err(_) => break,
            }
        }
        acc
    }

    /// Scan `acc` for the first CA_PROTO_ERROR frame and return its
    /// parsed header, or `None` if there is none.
    fn first_ca_proto_error(acc: &[u8]) -> Option<CaHeader> {
        let mut offset = 0;
        while offset + CaHeader::SIZE <= acc.len() {
            if let Ok((hdr, hdr_size)) = CaHeader::from_bytes_extended(&acc[offset..]) {
                if hdr.cmmd == CA_PROTO_ERROR {
                    return Some(hdr);
                }
                let msg_len = hdr_size + hdr.actual_postsize();
                if msg_len == 0 {
                    break;
                }
                offset += msg_len;
            } else {
                break;
            }
        }
        None
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn deprecated_read_unknown_sid_bad_type_sends_bad_resource_id() {
        // C `read_action` (`rsrv/camessage.c:608-619`) resolves the
        // channel BEFORE checking the DBR type, so an unknown SID takes
        // the bad-SID `logBadId` branch even when the requested type is
        // also invalid. `logBadId` (camessage.c:307-320) sends
        // ECA_INTERNAL ("Bad Resource ID", cid=0xFFFFFFFF), flushed by
        // camsgtask.c:142 before the disconnect — NOT the post-lookup
        // ECA_BADTYPE. Pre-fix Rust checked the type first and emitted a
        // spurious ECA_BADTYPE(cid=0xFFFFFFFF) ahead of the lookup.
        let db = Arc::new(PvDatabase::new());
        db.add_pv("a41:pv", EpicsValue::Double(0.0))
            .await
            .expect("add pv");
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (_acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);
        let (conn_tx, _conn_rx) = broadcast::channel::<ServerConnectionEvent>(64);

        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = "127.0.0.1:55411".parse().unwrap();

        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                Some(conn_tx),
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });

        let mut client = client_io;
        client.write_all(&version_frame()).await.expect("version");
        client
            .write_all(&create_chan_frame(1, "a41:pv"))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");
        let sid = read_create_chan_sid(&mut client, Duration::from_secs(3)).await;

        let unknown_sid = sid.wrapping_add(0xDEAD);
        assert_ne!(
            unknown_sid, sid,
            "test must use a SID distinct from the real one"
        );
        // Bad DBR type (99 > LAST_BUFFER_TYPE = 38) on the unknown SID.
        client
            .write_all(&read_frame(unknown_sid, 99, 1, 0x4141))
            .await
            .expect("read unknown sid bad type");
        client.flush().await.expect("flush read");

        let acc = drain_to_eof(&mut client, Duration::from_secs(3)).await;
        let err = first_ca_proto_error(&acc).unwrap_or_else(|| {
            panic!(
                "deprecated READ on an unknown SID with a bad type must emit the \
                 bad-SID ECA_INTERNAL frame (C read_action logBadId), but no \
                 CA_PROTO_ERROR was emitted (received {} bytes: {acc:?})",
                acc.len()
            )
        });
        assert_eq!(
            err.available, ECA_INTERNAL,
            "unknown-SID READ takes the bad-SID logBadId branch (ECA_INTERNAL), \
             not the post-lookup ECA_BADTYPE; got eca={:#x}",
            err.available
        );
        assert_eq!(
            err.cid, 0xFFFF_FFFF,
            "bad-SID ECA_INTERNAL frame echoes the 0xFFFFFFFF cid sentinel, got {:#x}",
            err.cid
        );

        let res = tokio::time::timeout(Duration::from_secs(2), handle)
            .await
            .expect("handle_client completes after unknown-sid read")
            .expect("join ok");
        assert!(
            res.is_err(),
            "unknown-SID READ must close the connection with Err (C RSRV_ERROR), got {res:?}"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn deprecated_read_known_sid_bad_type_sends_badtype_with_real_cid() {
        // with a VALID channel, C `read_action`
        // (`rsrv/camessage.c:616-619`) sends ECA_BADTYPE carrying the
        // channel's real cid (`pciu->cid`) + record name — never the
        // 0xFFFFFFFF sentinel the pre-fix code used.
        let db = Arc::new(PvDatabase::new());
        db.add_pv("a41:pv", EpicsValue::Double(0.0))
            .await
            .expect("add pv");
        let acf = Arc::new(tokio::sync::RwLock::new(None));
        let (_acf_reload_tx, acf_reload_rx) = broadcast::channel::<()>(4);
        let (conn_tx, _conn_rx) = broadcast::channel::<ServerConnectionEvent>(64);

        let (client_io, server_io) = tokio::io::duplex(4096);
        let peer: SocketAddr = "127.0.0.1:55412".parse().unwrap();

        let handle = tokio::spawn(async move {
            handle_client(
                server_io,
                peer,
                db,
                acf,
                acf_reload_rx,
                5064,
                None,
                None,
                None,
                Some(conn_tx),
                None,
                #[cfg(feature = "cap-tokens")]
                None,
                #[cfg(feature = "cap-tokens")]
                None,
            )
            .await
        });

        let mut client = client_io;
        client.write_all(&version_frame()).await.expect("version");
        // create_chan client cid = 1; the BADTYPE error must echo it.
        client
            .write_all(&create_chan_frame(1, "a41:pv"))
            .await
            .expect("create_chan");
        client.flush().await.expect("flush create_chan");
        let sid = read_create_chan_sid(&mut client, Duration::from_secs(3)).await;

        // Bad DBR type (99 > LAST_BUFFER_TYPE = 38) on the VALID sid.
        client
            .write_all(&read_frame(sid, 99, 1, 0x4242))
            .await
            .expect("read known sid bad type");
        client.flush().await.expect("flush read");

        let acc = drain_to_eof(&mut client, Duration::from_secs(3)).await;
        let err = first_ca_proto_error(&acc)
            .expect("deprecated READ with a valid SID + bad type must emit a CA_PROTO_ERROR");
        assert_eq!(
            err.available, ECA_BADTYPE,
            "status must be ECA_BADTYPE, got {:#x}",
            err.available
        );
        assert_ne!(
            err.cid,
            u32::MAX,
            "BADTYPE cid must be the channel's real cid, not the 0xFFFFFFFF sentinel"
        );
        assert_eq!(
            err.cid, 1,
            "BADTYPE cid must echo the create_chan client cid (pciu->cid)"
        );

        let res = tokio::time::timeout(Duration::from_secs(2), handle)
            .await
            .expect("handle_client completes after known-sid bad-type read")
            .expect("join ok");
        assert!(
            res.is_err(),
            "bad-type READ must close the connection with Err (C RSRV_ERROR), got {res:?}"
        );
    }
}