epics-base-rs 0.19.2

Pure Rust EPICS IOC core — record system, database, iocsh, calc engine
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
#![allow(unused_imports, clippy::all)]
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};

use epics_base_rs::error::CaError;
use epics_base_rs::server::database::PvDatabase;
use epics_base_rs::server::record::*;
use epics_base_rs::server::records::ai::AiRecord;
use epics_base_rs::server::records::ao::AoRecord;
use epics_base_rs::server::records::bi::BiRecord;
use epics_base_rs::server::records::longin::LonginRecord;
use epics_base_rs::types::EpicsValue;

#[tokio::test]
async fn test_write_notify_follows_flnk() {
    let db = PvDatabase::new();
    db.add_record("REC_A", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("REC_B", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    if let Some(rec) = db.get_record("REC_A").await {
        let mut inst = rec.write().await;
        inst.put_common_field("FLNK", EpicsValue::String("REC_B".into()))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("REC_A", &mut visited, 0)
        .await
        .unwrap();
    assert!(visited.contains("REC_A"));
    assert!(visited.contains("REC_B"));
}

#[tokio::test]
async fn test_inp_link_processing() {
    let db = PvDatabase::new();
    db.add_record("SOURCE", Box::new(AoRecord::new(42.0)))
        .await
        .unwrap();
    db.add_record("DEST", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();

    if let Some(rec) = db.get_record("DEST").await {
        let mut inst = rec.write().await;
        inst.put_common_field("INP", EpicsValue::String("SOURCE".into()))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("DEST", &mut visited, 0)
        .await
        .unwrap();

    let val = db.get_pv("DEST").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 42.0).abs() < 1e-10),
        other => panic!("expected Double(42.0), got {:?}", other),
    }
}

/// epics-base PR #4737901 regression: a soft-channel ai record with
/// an INP link to a non-existent PV must surface LINK_ALARM/INVALID
/// rather than silently returning the cached VAL with NO_ALARM. The
/// pre-fix path called `read_link_value_soft → get_pv → Err` then
/// folded the error to `None` and let process() succeed — leaving
/// downstream alarm consumers blind to the broken link.
#[tokio::test]
async fn test_soft_inp_read_failure_sets_link_alarm() {
    use epics_base_rs::server::recgbl::alarm_status;
    use epics_base_rs::server::record::AlarmSeverity;

    let db = PvDatabase::new();
    db.add_record("BROKEN", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();

    // Point INP at a record that doesn't exist. Soft Channel is the
    // default DTYP, so the read path runs through
    // `read_link_value_soft → get_pv("NO_SUCH_PV")` which returns Err.
    if let Some(rec) = db.get_record("BROKEN").await {
        let mut inst = rec.write().await;
        inst.put_common_field("INP", EpicsValue::String("NO_SUCH_PV".into()))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("BROKEN", &mut visited, 0)
        .await
        .unwrap();

    let rec = db.get_record("BROKEN").await.expect("record exists");
    let inst = rec.read().await;
    assert_eq!(
        inst.common.sevr,
        AlarmSeverity::Invalid,
        "broken soft-channel INP must drive SEVR=INVALID, got {:?}",
        inst.common.sevr
    );
    assert_eq!(
        inst.common.stat,
        alarm_status::LINK_ALARM,
        "broken soft-channel INP must drive STAT=LINK, got {}",
        inst.common.stat
    );
}

/// epics-base PR #d0cf47c regression: single-INP MS-class link must
/// propagate STAT/SEVR/AMSG from the source record. Previously only
/// the multi-input link path (INPA..INPL, calc/sub/aSub/sel) carried
/// MS-class alarms; ai/longin/bi/mbbi/stringin INP=`SRC MS/MSS/MSI`
/// silently dropped them even though the link parser recorded the
/// modifier.
///
/// C `recGblInheritSevrMsg` (recGbl.c:260) per-flavour semantics:
/// * **MS**  — DEST gets `LINK_ALARM` (NOT source stat), max-raised
///             sevr, no amsg propagation.
/// * **MSS** — DEST gets source stat + sevr + amsg.
/// * **MSI** — same as MS, but only when source.sevr == INVALID.
#[tokio::test]
async fn test_single_inp_ms_propagates_link_alarm_no_msg() {
    use epics_base_rs::server::recgbl::alarm_status;
    use epics_base_rs::server::record::AlarmSeverity;

    let db = PvDatabase::new();
    db.add_record("SRC", Box::new(AoRecord::new(7.0)))
        .await
        .unwrap();
    db.add_record("DST", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();

    // Force SRC into Major with a specific HIHI stat and a non-empty
    // amsg. Under plain MS, DST must lift to Major but surface
    // LINK_ALARM (NOT HIHI), and DST's amsg must NOT inherit "src-msg".
    if let Some(rec) = db.get_record("SRC").await {
        let mut inst = rec.write().await;
        inst.common.stat = alarm_status::HIHI_ALARM;
        inst.common.sevr = AlarmSeverity::Major;
        inst.common.amsg = "src-msg".to_string();
    }

    if let Some(rec) = db.get_record("DST").await {
        let mut inst = rec.write().await;
        inst.put_common_field("INP", EpicsValue::String("SRC NPP MS".into()))
            .unwrap();
        inst.common.udf = false;
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("DST", &mut visited, 0)
        .await
        .unwrap();

    let dst = db.get_record("DST").await.expect("DST exists");
    let inst = dst.read().await;
    assert_eq!(
        inst.common.sevr,
        AlarmSeverity::Major,
        "MS link must lift DST severity to source's Major"
    );
    assert_eq!(
        inst.common.stat,
        alarm_status::LINK_ALARM,
        "C parity: MS link MUST surface as LINK_ALARM, not the source's STAT"
    );
    assert!(
        inst.common.amsg.is_empty(),
        "C parity: MS link MUST NOT propagate amsg; got {:?}",
        inst.common.amsg
    );
}

/// MSS propagates source stat + sevr + amsg (PR d0cf47c).
#[tokio::test]
async fn test_single_inp_mss_propagates_stat_and_amsg() {
    use epics_base_rs::server::recgbl::alarm_status;
    use epics_base_rs::server::record::AlarmSeverity;

    let db = PvDatabase::new();
    db.add_record("SRC", Box::new(AoRecord::new(7.0)))
        .await
        .unwrap();
    db.add_record("DST", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();

    if let Some(rec) = db.get_record("SRC").await {
        let mut inst = rec.write().await;
        inst.common.stat = alarm_status::HIHI_ALARM;
        inst.common.sevr = AlarmSeverity::Major;
        inst.common.amsg = "src-major".to_string();
    }

    if let Some(rec) = db.get_record("DST").await {
        let mut inst = rec.write().await;
        inst.put_common_field("INP", EpicsValue::String("SRC NPP MSS".into()))
            .unwrap();
        inst.common.udf = false;
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("DST", &mut visited, 0)
        .await
        .unwrap();

    let dst = db.get_record("DST").await.expect("DST exists");
    let inst = dst.read().await;
    assert_eq!(inst.common.sevr, AlarmSeverity::Major);
    assert_eq!(
        inst.common.stat,
        alarm_status::HIHI_ALARM,
        "MSS must carry source's STAT"
    );
    assert_eq!(
        inst.common.amsg, "src-major",
        "MSS must carry source's AMSG"
    );
}

/// OUTPUT-side twin of the INP MS-class tests above: C `dbDbPutValue`
/// (dbDbLink.c:382-383) folds the SOURCE record's alarm into a DB
/// OUT-link DEST via `recGblInheritSevrMsg`. A source at MAJOR writing
/// through `OUT = DST PP MS` must lift DST to MAJOR under `LINK_ALARM`
/// (NOT the source's HIHI stat), with no amsg. Pre-fix the OUT-link
/// write path only put the value and propagated PUTF — the dest never
/// inherited the source severity, so an alarming upstream record silently
/// drove a NO_ALARM downstream. (Per-mode semantics — MS/MSI/MSS/NMS —
/// are exercised by the INP tests above; both sides share the
/// `inherit_sevr_msg` helper, so these OUT tests pin the wiring: the OUT
/// path captures the source's committed alarm and applies it to the DEST.)
#[tokio::test]
async fn test_out_link_ms_propagates_link_alarm_to_dest() {
    use epics_base_rs::server::recgbl::alarm_status;

    let db = PvDatabase::new();
    // SRC: ao with VAL=99 over HIHI=50/HHSV=Major → computes MAJOR/HIHI
    // through its own analog-limit alarm, then writes 99 to DST via a
    // `PP MS` OUT link.
    db.add_record("SRC", Box::new(AoRecord::new(99.0)))
        .await
        .unwrap();
    db.add_record("DST", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("SRC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("OUT", EpicsValue::String("DST PP MS".into()))
            .unwrap();
        inst.put_common_field("HIHI", EpicsValue::Double(50.0))
            .unwrap();
        inst.put_common_field("HHSV", EpicsValue::Short(AlarmSeverity::Major as i16))
            .unwrap();
        inst.common.udf = false;
    }
    if let Some(rec) = db.get_record("DST").await {
        // Clear DST's own UDF so its post-write process raises no alarm
        // of its own — the only severity it can end up at is the
        // inherited one.
        rec.write().await.common.udf = false;
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("SRC", &mut visited, 0)
        .await
        .unwrap();

    let dst = db.get_record("DST").await.expect("DST exists");
    let inst = dst.read().await;
    // Guard: the OUT-link value actually landed.
    let val = inst.record.val().and_then(|v| v.to_f64()).unwrap_or(0.0);
    assert!(
        (val - 99.0).abs() < 1e-9,
        "OUT-link value must reach DST: got {val}"
    );
    assert_eq!(
        inst.common.sevr,
        AlarmSeverity::Major,
        "MS OUT link must lift DST severity to source's Major"
    );
    assert_eq!(
        inst.common.stat,
        alarm_status::LINK_ALARM,
        "C parity: MS OUT link MUST surface as LINK_ALARM, not the source's HIHI stat"
    );
    assert!(
        inst.common.amsg.is_empty(),
        "C parity: MS OUT link MUST NOT propagate amsg; got {:?}",
        inst.common.amsg
    );
}

/// NMS contrast for the OUT-link inheritance above: a bare `OUT = DST PP`
/// carries the default NoMaximize switch, so a MAJOR source must NOT
/// raise the dest's severity.
#[tokio::test]
async fn test_out_link_nms_does_not_propagate_alarm_to_dest() {
    let db = PvDatabase::new();
    db.add_record("SRC", Box::new(AoRecord::new(99.0)))
        .await
        .unwrap();
    db.add_record("DST", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("SRC").await {
        let mut inst = rec.write().await;
        // No MS-class modifier → NoMaximize.
        inst.put_common_field("OUT", EpicsValue::String("DST PP".into()))
            .unwrap();
        inst.put_common_field("HIHI", EpicsValue::Double(50.0))
            .unwrap();
        inst.put_common_field("HHSV", EpicsValue::Short(AlarmSeverity::Major as i16))
            .unwrap();
        inst.common.udf = false;
    }
    if let Some(rec) = db.get_record("DST").await {
        rec.write().await.common.udf = false;
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("SRC", &mut visited, 0)
        .await
        .unwrap();

    let dst = db.get_record("DST").await.expect("DST exists");
    let inst = dst.read().await;
    assert_eq!(
        inst.common.sevr,
        AlarmSeverity::NoAlarm,
        "NMS OUT link MUST NOT propagate the source's Major severity"
    );
}

/// B2 regression: a soft-channel record whose INP is an external
/// `pva://` link must fold the lset's gated alarm severity into its
/// own `LINK_ALARM`. Previously `read_link_with_alarm` returned
/// `(None, None)` for any non-Db link, so a connected pva link
/// carrying a remote MAJOR severity left the owning record at
/// NO_ALARM.
#[tokio::test]
async fn test_pva_link_propagates_alarm_severity_into_link_alarm() {
    use epics_base_rs::server::database::LinkSet;
    use epics_base_rs::server::recgbl::alarm_status;
    use epics_base_rs::server::record::AlarmSeverity;

    /// Stub lset: serves a value and a fixed (already gated) severity.
    struct AlarmingLset;
    impl LinkSet for AlarmingLset {
        fn is_connected(&self, _: &str) -> bool {
            true
        }
        fn get_value(&self, _: &str) -> Option<EpicsValue> {
            Some(EpicsValue::Double(12.0))
        }
        fn alarm_severity(&self, _: &str) -> Option<i32> {
            Some(2) // MAJOR — as if the link's MS mode let it through
        }
        fn alarm_message(&self, _: &str) -> Option<String> {
            Some("remote major".into())
        }
    }

    let db = PvDatabase::new();
    db.register_link_set("pva", Arc::new(AlarmingLset)).await;
    db.add_record("PVADST", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("PVADST").await {
        let mut inst = rec.write().await;
        inst.put_common_field("INP", EpicsValue::String("pva://REMOTE:PV".into()))
            .unwrap();
        inst.common.udf = false;
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("PVADST", &mut visited, 0)
        .await
        .unwrap();

    let rec = db.get_record("PVADST").await.expect("record exists");
    let inst = rec.read().await;
    // Value was read from the lset.
    assert_eq!(
        inst.record.val().and_then(|v| v.to_f64()),
        Some(12.0),
        "pva link value must be applied"
    );
    // Severity folded into LINK_ALARM.
    assert_eq!(
        inst.common.sevr,
        AlarmSeverity::Major,
        "pva link's MAJOR severity must reach the record's SEVR"
    );
    assert_eq!(
        inst.common.stat,
        alarm_status::LINK_ALARM,
        "pva link alarm must surface as LINK_ALARM"
    );
}

/// B2: when the lset reports no alarm severity (`alarm_severity` →
/// None — e.g. NMS, or remote NO_ALARM), a connected pva link must
/// NOT raise any alarm on the owning record.
#[tokio::test]
async fn test_pva_link_no_alarm_when_lset_reports_none() {
    use epics_base_rs::server::database::LinkSet;
    use epics_base_rs::server::record::AlarmSeverity;

    struct QuietLset;
    impl LinkSet for QuietLset {
        fn is_connected(&self, _: &str) -> bool {
            true
        }
        fn get_value(&self, _: &str) -> Option<EpicsValue> {
            Some(EpicsValue::Double(5.0))
        }
        // alarm_severity defaults to None.
    }

    let db = PvDatabase::new();
    db.register_link_set("pva", Arc::new(QuietLset)).await;
    db.add_record("PVAQUIET", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("PVAQUIET").await {
        let mut inst = rec.write().await;
        inst.put_common_field("INP", EpicsValue::String("pva://REMOTE:OK".into()))
            .unwrap();
        inst.common.udf = false;
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("PVAQUIET", &mut visited, 0)
        .await
        .unwrap();

    let rec = db.get_record("PVAQUIET").await.expect("record exists");
    let inst = rec.read().await;
    assert_eq!(
        inst.record.val().and_then(|v| v.to_f64()),
        Some(5.0),
        "pva link value must still be applied"
    );
    assert_eq!(
        inst.common.sevr,
        AlarmSeverity::NoAlarm,
        "no lset severity → record stays NO_ALARM"
    );
}

/// Mock lset shared by the external-OUT-link dispatch tests: records
/// every `(name, value, op)` triple the database routes through
/// `put_value`, so a test can assert both the delivered value and the
/// chosen [`LinkPutOp`] (plain vs put-notify `Async`).
struct CapturingLset {
    writes: Arc<
        std::sync::Mutex<
            Vec<(
                String,
                EpicsValue,
                epics_base_rs::server::database::LinkPutOp,
            )>,
        >,
    >,
}
impl epics_base_rs::server::database::LinkSet for CapturingLset {
    fn is_connected(&self, _: &str) -> bool {
        true
    }
    fn get_value(&self, _: &str) -> Option<EpicsValue> {
        None
    }
    fn put_value(
        &self,
        name: &str,
        value: EpicsValue,
        op: epics_base_rs::server::database::LinkPutOp,
    ) -> Result<(), String> {
        self.writes
            .lock()
            .unwrap()
            .push((name.to_string(), value, op));
        Ok(())
    }
}

/// A record whose OUT link is an external `pva://` link must drive
/// the processed value through the registered link set's `put_value`.
///
/// Before this fix the OUT-link write stage in `processing.rs` only
/// matched `ParsedLink::Db` — a record with a `ParsedLink::Ca`/`Pva`
/// OUT link processed normally but the value went nowhere. The
/// OUTPUT side now mirrors the INPUT side: it dispatches the write
/// through the registered lset, matching C `dbLink.c::dbPutLink`
/// (dbLink.c:434-448), which routes every link write through
/// `plink->lset->putValue` regardless of DB vs CA link.
#[tokio::test]
async fn test_pva_out_link_writes_value_through_link_set() {
    use std::sync::Mutex;

    use epics_base_rs::server::database::LinkPutOp;

    let writes = Arc::new(Mutex::new(Vec::new()));
    let db = PvDatabase::new();
    db.register_link_set(
        "pva",
        Arc::new(CapturingLset {
            writes: writes.clone(),
        }),
    )
    .await;

    // Soft-Channel ao record (DTYP empty) — its OUT link is the
    // soft OUT-link write path.
    db.add_record("AO_PVAOUT", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("AO_PVAOUT").await {
        let mut inst = rec.write().await;
        inst.put_common_field("OUT", EpicsValue::String("pva://REMOTE:OUT".into()))
            .unwrap();
        inst.common.udf = false;
        // Set VAL so process() has a value to drive out the OUT link.
        inst.record
            .put_field("VAL", EpicsValue::Double(3.5))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("AO_PVAOUT", &mut visited, 0)
        .await
        .unwrap();

    let captured = writes.lock().unwrap();
    assert_eq!(
        captured.len(),
        1,
        "the pva OUT link must drive exactly one put_value"
    );
    assert_eq!(
        captured[0].0, "REMOTE:OUT",
        "put_value must receive the bare PV name (scheme stripped)"
    );
    assert_eq!(
        captured[0].1.to_f64(),
        Some(3.5),
        "put_value must receive the record's processed value"
    );
    assert_eq!(
        captured[0].2,
        LinkPutOp::Plain,
        "a plain record-processing OUT write (no put-notify chain) must \
         deliver a Plain put, not a completion-aware Async put"
    );
}

/// A record with a `pva://` OUT link and NO registered link set must
/// fail gracefully — process() completes without panic, the value is
/// simply not delivered (C `dbPutLink` returns `S_db_noLSET`).
#[tokio::test]
async fn test_pva_out_link_no_link_set_fails_gracefully() {
    let db = PvDatabase::new();
    // No register_link_set call — the "pva" scheme is unregistered.
    db.add_record("AO_NOLSET", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("AO_NOLSET").await {
        let mut inst = rec.write().await;
        inst.put_common_field("OUT", EpicsValue::String("pva://NOWHERE:PV".into()))
            .unwrap();
        inst.common.udf = false;
        inst.record
            .put_field("VAL", EpicsValue::Double(1.0))
            .unwrap();
    }

    let mut visited = HashSet::new();
    // Must not panic; process completes cleanly.
    db.process_record_with_links("AO_NOLSET", &mut visited, 0)
        .await
        .expect("process must complete despite the unresolvable OUT link");

    let rec = db.get_record("AO_NOLSET").await.expect("record exists");
    let inst = rec.read().await;
    assert_eq!(
        inst.record.val().and_then(|v| v.to_f64()),
        Some(1.0),
        "the record itself still holds its value"
    );
}

/// Boundary twin of `test_pva_out_link_writes_value_through_link_set`:
/// when the originating record is part of a put-notify / blocking-put
/// chain (it carries a completion wait-set), its external OUT-link
/// write must be delivered as [`LinkPutOp::Async`] — the C
/// `dbPutLinkAsync` / pvxs `pvaPutValueAsync` path. The plain-process
/// twin asserts the `Plain` boundary; this asserts `Async`, so the
/// notify→op mapping (`PvDatabase::external_put_op`) is pinned on both
/// sides of its single branch.
#[tokio::test]
async fn test_pva_out_link_put_notify_chain_uses_async_op() {
    use std::sync::Mutex;

    use epics_base_rs::server::database::LinkPutOp;

    let writes = Arc::new(Mutex::new(Vec::new()));
    let db = PvDatabase::new();
    db.register_link_set(
        "pva",
        Arc::new(CapturingLset {
            writes: writes.clone(),
        }),
    )
    .await;

    db.add_record("AO_PVAOUT_NOTIFY", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    // Keep the receiver alive so the completion `send` at the tail of
    // processing never observes a dropped channel; the test only
    // inspects the op captured at OUT-write time.
    let (tx, _rx) = epics_base_rs::runtime::sync::oneshot::channel();
    if let Some(rec) = db.get_record("AO_PVAOUT_NOTIFY").await {
        let mut inst = rec.write().await;
        inst.put_common_field("OUT", EpicsValue::String("pva://REMOTE:OUT".into()))
            .unwrap();
        inst.common.udf = false;
        inst.record
            .put_field("VAL", EpicsValue::Double(7.0))
            .unwrap();
        // Arm a put-notify wait-set: the source record is now in a
        // blocking-put chain, so its OUT-link write must use Async.
        inst.notify = Some(NotifyWaitSet::new(tx));
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("AO_PVAOUT_NOTIFY", &mut visited, 0)
        .await
        .unwrap();

    let captured = writes.lock().unwrap();
    assert_eq!(
        captured.len(),
        1,
        "the pva OUT link must drive exactly one put_value"
    );
    assert_eq!(captured[0].0, "REMOTE:OUT");
    assert_eq!(
        captured[0].2,
        LinkPutOp::Async,
        "an OUT-link write from a put-notify chain must be a \
         completion-aware Async put (C dbPutLinkAsync / pvxs \
         pvaPutValueAsync)"
    );
}

/// C `recGbl.c:194/210-211` — when only `amsg` changes (no SEVR/STAT
/// transition), `stat_mask` is set to `DBE_ALARM` and STAT/AMSG/VAL
/// are still posted. The Rust port previously only checked
/// `alarm_changed` (sevr-or-stat) and silently dropped the AMSG-only
/// update, leaving subscribers reading a stale message string.
///
/// Reproduce via MSS link: source carries Major severity. Cycle 1
/// propagates the source amsg into the dest, raising sevr 0→Major
/// (alarm_changed=true; AMSG flows in the normal path). Cycle 2
/// changes the source amsg but keeps the same severity — dest's
/// reset_alarms sees sevr Major→Major (alarm_changed=false) but
/// amsg "msg1"→"msg2" (amsg_changed=true). The fix posts AMSG for
/// this case so the subscriber sees the new message.
#[tokio::test]
async fn test_mss_propagates_amsg_only_change_posts_amsg_event() {
    use epics_base_rs::server::recgbl::{EventMask, alarm_status};
    use epics_base_rs::server::record::AlarmSeverity;
    use epics_base_rs::types::DbFieldType;

    let db = PvDatabase::new();
    db.add_record("SRC_AMSG", Box::new(AoRecord::new(7.0)))
        .await
        .unwrap();
    db.add_record("DST_AMSG", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();

    // Source: Major severity with first amsg.
    if let Some(rec) = db.get_record("SRC_AMSG").await {
        let mut inst = rec.write().await;
        inst.common.stat = alarm_status::HIHI_ALARM;
        inst.common.sevr = AlarmSeverity::Major;
        inst.common.amsg = "msg1".to_string();
    }
    // Dest: MSS link to source. Subscribe to AMSG with ALARM mask
    // (C posts AMSG with stat_mask = DBE_ALARM on amsg-only change).
    if let Some(rec) = db.get_record("DST_AMSG").await {
        let mut inst = rec.write().await;
        inst.put_common_field("INP", EpicsValue::String("SRC_AMSG NPP MSS".into()))
            .unwrap();
        inst.common.udf = false;
    }

    // Cycle 1: drives sevr 0→Major, amsg ""→"msg1" (alarm_changed=true).
    let mut visited = HashSet::new();
    db.process_record_with_links("DST_AMSG", &mut visited, 0)
        .await
        .unwrap();

    // Now subscribe to AMSG with ALARM mask AFTER cycle 1, so
    // last_posted seeds at "msg1".
    let mut amsg_rx = {
        let rec = db.get_record("DST_AMSG").await.unwrap();
        let mut inst = rec.write().await;
        inst.add_subscriber("AMSG", 11, DbFieldType::String, EventMask::ALARM.bits())
    }
    .expect("AMSG subscription must be accepted");

    // Source: keep severity Major, change amsg only.
    if let Some(rec) = db.get_record("SRC_AMSG").await {
        let mut inst = rec.write().await;
        inst.common.amsg = "msg2".to_string();
    }

    // Cycle 2: dest picks up msg2. sevr stays Major (alarm_changed=false),
    // amsg "msg1"→"msg2" (amsg_changed=true). AMSG event must flow.
    let mut visited = HashSet::new();
    db.process_record_with_links("DST_AMSG", &mut visited, 0)
        .await
        .unwrap();

    {
        let rec = db.get_record("DST_AMSG").await.unwrap();
        let inst = rec.read().await;
        assert_eq!(inst.common.sevr, AlarmSeverity::Major, "sevr unchanged");
        assert_eq!(inst.common.amsg, "msg2", "amsg propagated");
    }

    let event = amsg_rx
        .try_recv()
        .expect("AMSG-only change must produce an event on DBE_ALARM-class subscribers");
    assert!(
        matches!(event.snapshot.value, EpicsValue::String(ref s) if s == "msg2"),
        "AMSG event payload should be the new message, got {:?}",
        event.snapshot.value
    );
}

// BUG 2 regression — `process_record` (the foreign-process / QSRV-group
// path) calls `process_local`. A recent fix excluded UDF from the
// `process_local` `sub_updates` snapshot loop, citing "UDF via the
// explicit UDF push above" — but `process_local` had NO such push (the
// two `database/processing.rs` paths exclude UDF AND pair it with an
// explicit push at `:1327` and `:1948`). Without the push a UDF change
// driven through `process_record` was never delivered to `.UDF`
// subscribers. The fix adds the `if !event_mask.is_empty()` UDF push to
// `process_local`, mirroring `processing.rs`.
#[tokio::test]
async fn test_process_record_delivers_udf_monitor_event() {
    use epics_base_rs::server::recgbl::{EventMask, alarm_status};
    use epics_base_rs::server::record::AlarmSeverity;
    use epics_base_rs::types::DbFieldType;

    let db = PvDatabase::new();
    // Soft-Channel ai with a defined VAL — `process_local`'s
    // `value_is_undefined()` returns false, so processing clears UDF.
    db.add_record("UDF_REC", Box::new(AiRecord::new(5.0)))
        .await
        .unwrap();

    // Seed the prior UDF state: UDF=true with INVALID/UDF_ALARM, as a
    // freshly-initialised record reads before its first process. The
    // first `process_record` clears UDF (true→false) and the alarm
    // (INVALID→NO_ALARM), so `event_mask` carries DBE_ALARM and the UDF
    // push fires.
    {
        let rec = db.get_record("UDF_REC").await.unwrap();
        let mut inst = rec.write().await;
        inst.common.udf = true;
        inst.common.sevr = AlarmSeverity::Invalid;
        inst.common.stat = alarm_status::UDF_ALARM;
    }

    // Subscribe to UDF before processing.
    let mut udf_rx = {
        let rec = db.get_record("UDF_REC").await.unwrap();
        let mut inst = rec.write().await;
        inst.add_subscriber("UDF", 31, DbFieldType::Char, EventMask::ALARM.bits())
    }
    .expect("UDF subscription must be accepted");

    // Foreign-process path — `process_record` → `process_local`.
    db.process_record("UDF_REC").await.unwrap();

    {
        let rec = db.get_record("UDF_REC").await.unwrap();
        let inst = rec.read().await;
        assert!(!inst.common.udf, "process must have cleared UDF");
    }

    let event = udf_rx
        .try_recv()
        .expect("a UDF change via process_record must deliver a UDF monitor event");
    assert!(
        matches!(event.snapshot.value, EpicsValue::Char(0)),
        "UDF event payload should be the cleared value 0, got {:?}",
        event.snapshot.value
    );
}

/// C `dbAccess.c::dbPutField:1276` sets `precord->putf = TRUE`
/// IMMEDIATELY before calling `dbProcess`. The flag stays TRUE
/// throughout the entire process cycle and is cleared in
/// `recGblFwdLink` (`recGbl.c:302`) after the forward-link
/// dispatch — i.e. observable for the WHOLE put-driven processing
/// cycle. Async records keep PUTF=TRUE through the device round
/// trip; it clears only when the completion path runs FLNK.
///
/// Pre-fix the Rust port cleared PUTF in `put_record_field_from_ca`
/// BEFORE the `process_record_with_links` call (field_io.rs:497),
/// so any consumer reading PUTF during the process cycle (TPRO
/// trace, monitor on .PUTF, async-completion path's
/// "put-driven vs scan-driven" classifier) always saw PUTF=0.
#[tokio::test]
async fn test_putf_clears_after_synchronous_put_completion() {
    // AoRecord is synchronous Soft Channel (process() returns
    // Complete immediately). The synchronous-completion clear
    // point in `put_record_field_from_ca` runs after the
    // `process_record_with_links` call returns — so the
    // test-observable end state is PUTF=false. The companion
    // async test below differentiates "stays set through round
    // trip" vs the pre-fix "always false during process".
    let db = PvDatabase::new();
    db.add_record("PUTF_SYNC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    let _ = db
        .put_record_field_from_ca("PUTF_SYNC", "VAL", EpicsValue::Double(42.0))
        .await;

    let rec = db.get_record("PUTF_SYNC").await.unwrap();
    let inst = rec.read().await;
    assert!(
        !inst.common.putf,
        "after synchronous put completion, PUTF must clear (mirrors C recGblFwdLink:302)"
    );
}

/// Async-completion path: for a record that returns AsyncPending,
/// PUTF must remain TRUE across the device round trip and clear
/// only when `complete_async_record` runs. C parity:
/// `dbAccess.c::dbPutField:1276` sets putf=TRUE; the async device's
/// completion eventually calls `dbProcess` again, which runs through
/// `recGblFwdLink` (clears putf).
#[tokio::test]
async fn test_putf_survives_async_round_trip_and_clears_on_completion() {
    let db = PvDatabase::new();
    db.add_record("ASYNC_PUTF", Box::new(AsyncRecord { val: 0.0 }))
        .await
        .unwrap();

    // Drive a CA put. AsyncRecord returns AsyncPending, so the
    // process call returns with PACT=true; PUTF must stay TRUE.
    let _ = db
        .put_record_field_from_ca("ASYNC_PUTF", "VAL", EpicsValue::Double(7.0))
        .await;

    {
        let rec = db.get_record("ASYNC_PUTF").await.unwrap();
        let inst = rec.read().await;
        assert!(inst.is_processing(), "async pending → PACT=true");
        assert!(
            inst.common.putf,
            "PUTF must remain TRUE across the async round trip — \
             pre-fix the Rust port cleared it before the process call \
             so async-completion logic could not classify the trigger \
             as put-driven"
        );
    }

    // Now fire the async completion. PUTF must clear (mirrors C
    // recGblFwdLink:302 after the FLNK dispatch).
    db.complete_async_record("ASYNC_PUTF").await.unwrap();
    {
        let rec = db.get_record("ASYNC_PUTF").await.unwrap();
        let inst = rec.read().await;
        assert!(!inst.is_processing(), "completion clears PACT");
        assert!(
            !inst.common.putf,
            "complete_async_record_inner must clear PUTF (recGblFwdLink parity)"
        );
    }
}

/// C `dbAccess.c::dbPut:1410-1411` clears `precord->udf = FALSE`
/// synchronously when the put target is the record-type's primary
/// value field (`dbIsValueField`). The clear runs INSIDE dbPut —
/// BEFORE dbProcess. Pre-fix the Rust port deferred UDF clearing
/// to the process-cycle's own `if instance.record.clears_udf()`
/// branch (processing.rs:839). The processing path drops the put's
/// write lock and re-acquires inside `process_record_with_links`,
/// so a second reader between the put and the process could
/// observe `(VAL=new, udf=true)` — a C-illegal pair. For async
/// records the window spans the entire device round trip until
/// `complete_async_record` runs its own clear. This test pins the
/// C-parity invariant: post-put, pre-process, UDF must already be
/// false on a primary-field write.
#[tokio::test]
async fn test_put_record_field_from_ca_clears_udf_on_primary_field_write() {
    let db = PvDatabase::new();
    db.add_record("UDF_ASYNC", Box::new(AsyncRecord { val: 0.0 }))
        .await
        .unwrap();

    // Record starts with udf=true (default).
    {
        let rec = db.get_record("UDF_ASYNC").await.unwrap();
        assert!(
            rec.read().await.common.udf,
            "AsyncRecord starts undefined (udf=true)"
        );
    }

    let _ = db
        .put_record_field_from_ca("UDF_ASYNC", "VAL", EpicsValue::Double(7.0))
        .await;

    // AsyncRecord returns AsyncPending; PACT is set, process bailed
    // before its own UDF clear at processing.rs:840 ran. The put-time
    // clear in field_io.rs must have already fired.
    let rec = db.get_record("UDF_ASYNC").await.unwrap();
    let inst = rec.read().await;
    assert!(
        inst.is_processing(),
        "AsyncRecord should be mid-async (PACT=true)"
    );
    assert!(
        !inst.common.udf,
        "primary-field CA put must clear UDF synchronously \
         (dbAccess.c::dbPut:1411 parity) — observable before \
         complete_async_record runs"
    );
}

/// epics-base PR #3fb10b6 regression: only the record directly
/// receiving a dbPut should carry PUTF=1 during chain processing.
/// Pre-fix the CP-target dispatch set PUTF=true on every chained
/// record, smearing put attribution across the entire chain.
#[tokio::test]
async fn test_putf_stays_off_for_cp_chained_targets() {
    let db = PvDatabase::new();
    db.add_record("SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("TGT", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("TGT").await {
        let mut inst = rec.write().await;
        inst.put_common_field("INP", EpicsValue::String("SRC CP".into()))
            .unwrap();
    }

    // Drive SRC's process directly. The CP dispatch enumerates TGT
    // and would (pre-fix) set TGT.common.putf=true before processing.
    let mut visited = HashSet::new();
    db.process_record_with_links("SRC", &mut visited, 0)
        .await
        .unwrap();

    let tgt = db.get_record("TGT").await.expect("TGT exists");
    let inst = tgt.read().await;
    assert!(
        !inst.common.putf,
        "CP-driven TGT must not carry PUTF=1 — that bit belongs only to the directly-put record"
    );
}

/// C `dbDbLink.c::processTarget:474` propagates `pdst->putf = psrc->putf`
/// when writing through a DB OUT link to a non-pact target. Pre-fix
/// the Rust `write_db_link_value` only put the value and called
/// `process_record_with_links` without touching `target.putf` — so a
/// CA put on an ao with OUT pointing at a passive ai left the ai's
/// PUTF=0 during the chained process cycle. dbNotify completion
/// attribution and device-support `put-driven vs scan-driven`
/// classifiers downstream of the OUT link silently observed
/// scan-driven processing instead of put-driven.
#[tokio::test]
async fn test_putf_propagates_through_db_out_link_to_passive_target() {
    let db = PvDatabase::new();
    db.add_record("PUTF_OUT_TGT", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    // Source ao: OUT to TGT, PP semantics so the target processes.
    db.add_record("PUTF_OUT_SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("PUTF_OUT_SRC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("OUT", EpicsValue::String("PUTF_OUT_TGT PP".into()))
            .unwrap();
    }
    // Target must be Passive for processTarget to run; AoRecord
    // defaults to Passive scan so no explicit set needed.

    // Drive a CA put that lands as a put on SRC. SRC.putf becomes 1
    // before processing; during processing, the OUT-link write runs
    // and target should inherit putf=1 BEFORE its process cycle.
    let _ = db
        .put_record_field_from_ca("PUTF_OUT_SRC", "VAL", EpicsValue::Double(5.0))
        .await;

    // After both records' synchronous cycles complete, the C path
    // clears putf on each (each runs its own recGblFwdLink). What
    // this test pins is the steady-state observability: value
    // landed (proving OUT-write happened) AND target.rpro stayed
    // false (no spurious reprocess request — that path only fires
    // when target was pact at OUT-write time). The mid-cycle PUTF
    // observability is tested separately via an async target below.
    let tgt = db.get_record("PUTF_OUT_TGT").await.unwrap();
    let inst = tgt.read().await;
    assert!(
        !inst.common.putf,
        "after both records' synchronous cycles complete, both clear putf"
    );
    assert!(
        !inst.common.rpro,
        "target was not pact, so rpro must stay false (normal propagation)"
    );
    let val = inst.record.val().and_then(|v| v.to_f64()).unwrap_or(0.0);
    assert!(
        (val - 5.0).abs() < 1e-10,
        "OUT link write propagated value (val={val})"
    );
}

/// Mid-cycle PUTF propagation: when the source's OUT-link write
/// dispatches a target's process(), the target.putf must equal the
/// source's putf BEFORE the target's own clears fire. Using an async
/// target lets us observe the bit between write_db_link_value's set
/// and the eventual complete_async_record clear.
///
/// Pre-fix `write_db_link_value` only forwarded the value
/// and dispatched process — never touched `target.putf`. So even
/// when the source had `putf=1` from a CA put, the async target
/// stayed at `putf=0` for the duration of the in-flight cycle.
#[tokio::test]
async fn test_putf_propagates_mid_cycle_via_async_target_out_link() {
    let db = PvDatabase::new();
    // Async target: stays pact between process and complete_async.
    db.add_record("PROP_TGT", Box::new(AsyncRecord { val: 0.0 }))
        .await
        .unwrap();
    db.add_record("PROP_SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("PROP_SRC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("OUT", EpicsValue::String("PROP_TGT PP".into()))
            .unwrap();
    }

    // Drive CA put. SRC processes synchronously, OUT writes to TGT,
    // dispatches process; TGT returns AsyncPending so its process
    // stays in flight — PUTF must be set on TGT before that return
    // and stay set until completion.
    let _ = db
        .put_record_field_from_ca("PROP_SRC", "VAL", EpicsValue::Double(11.0))
        .await;

    let tgt = db.get_record("PROP_TGT").await.unwrap();
    let inst = tgt.read().await;
    assert!(
        inst.is_processing(),
        "AsyncPending target stays pact between process and complete"
    );
    assert!(
        inst.common.putf,
        "target.putf must inherit from src.putf BEFORE complete_async_record clears it \
         (C dbDbLink.c::processTarget:474). Pre-fix this stayed false."
    );
}

/// epics-base 7.0.7 + PR #ac92e3e follow-up: SIMM=RAW input must
/// route the SIOL value through RVAL and run the record's conversion
/// chain (LINR/ESLO/EOFF), not overwrite VAL with the raw count.
/// Pre-fix the simulation path called both put_field("RVAL", v) AND
/// set_val(v), so VAL ended up holding raw counts and the operator's
/// configured EGU conversion was silently bypassed.
#[tokio::test]
async fn test_simm_raw_input_runs_conversion_chain() {
    let db = PvDatabase::new();
    // Source PV that the ai's SIOL link reads from — provides the
    // "raw count" for the simulation.
    db.add_record("RAW:SRC", Box::new(AoRecord::new(5.0)))
        .await
        .unwrap();
    // Target ai: configure LINR=SLOPE(1), ESLO=2.0, EOFF=10.0 so a
    // raw value of 5 should convert to VAL = 5*2 + 10 = 20.
    let mut ai = epics_base_rs::server::records::ai::AiRecord::new(0.0);
    ai.linr = 1;
    ai.eslo = 2.0;
    ai.eoff = 10.0;
    db.add_record("AI:SIMRAW", Box::new(ai)).await.unwrap();
    if let Some(rec) = db.get_record("AI:SIMRAW").await {
        let mut inst = rec.write().await;
        // SIMM=2 (RAW) directly on the ai record's own SIMM field.
        // Putting through put_field exercises the same code path
        // operators hit via caput .SIMM 2.
        inst.record.put_field("SIMM", EpicsValue::Short(2)).unwrap();
        // SIOL lives on the ai record-specific struct (not common),
        // so put through the record's own put_field — put_common_field
        // would leave ai.siol empty and the simulation never enters.
        inst.record
            .put_field("SIOL", EpicsValue::String("RAW:SRC".into()))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("AI:SIMRAW", &mut visited, 0)
        .await
        .unwrap();

    let ai_rec = db.get_record("AI:SIMRAW").await.expect("AI:SIMRAW exists");
    let inst = ai_rec.read().await;
    let val = inst
        .record
        .get_field("VAL")
        .and_then(|v| v.to_f64())
        .expect("VAL must be readable as f64");
    assert!(
        (val - 20.0).abs() < 1e-10,
        "SIMM=RAW must run convert(): expected VAL=5*ESLO+EOFF=20.0, got {val}"
    );
    let rval = inst
        .record
        .get_field("RVAL")
        .and_then(|v| match v {
            EpicsValue::Long(n) => Some(n as f64),
            other => other.to_f64(),
        })
        .expect("RVAL must be readable");
    assert!(
        (rval - 5.0).abs() < 1e-10,
        "RVAL must hold the raw count from SIOL; got {rval}"
    );
}

#[tokio::test]
async fn test_cycle_detection() {
    let db = PvDatabase::new();
    db.add_record("CYCLE_A", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("CYCLE_B", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    if let Some(rec) = db.get_record("CYCLE_A").await {
        let mut inst = rec.write().await;
        inst.put_common_field("FLNK", EpicsValue::String("CYCLE_B".into()))
            .unwrap();
    }
    if let Some(rec) = db.get_record("CYCLE_B").await {
        let mut inst = rec.write().await;
        inst.put_common_field("FLNK", EpicsValue::String("CYCLE_A".into()))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("CYCLE_A", &mut visited, 0)
        .await
        .unwrap();
    assert!(visited.contains("CYCLE_A"));
    assert!(visited.contains("CYCLE_B"));
    assert_eq!(visited.len(), 2);
}

#[tokio::test]
async fn test_ao_drvh_drvl_clamp() {
    let mut rec = AoRecord::new(0.0);
    rec.drvh = 100.0;
    rec.drvl = -50.0;
    rec.val = 200.0;
    rec.process().unwrap();
    assert!((rec.val - 100.0).abs() < 1e-10);

    rec.val = -100.0;
    rec.process().unwrap();
    assert!((rec.val - (-50.0)).abs() < 1e-10);
}

#[tokio::test]
async fn test_ao_oroc_rate_limit() {
    let mut rec = AoRecord::new(0.0);
    rec.oroc = 5.0;
    rec.drvh = 0.0;
    rec.drvl = 0.0;

    rec.val = 100.0;
    rec.process().unwrap();
    // C: OROC modifies OVAL, not VAL
    assert!((rec.oval - 5.0).abs() < 1e-10, "First: oval={}", rec.oval);

    rec.val = 200.0;
    rec.process().unwrap();
    assert!((rec.oval - 10.0).abs() < 1e-10, "Second: oval={}", rec.oval);
}

#[tokio::test]
async fn test_ao_omsl_dol() {
    let db = PvDatabase::new();
    db.add_record("SOURCE", Box::new(AoRecord::new(42.0)))
        .await
        .unwrap();

    let mut ao = AoRecord::new(0.0);
    ao.omsl = 1;
    ao.dol = "SOURCE".to_string();
    db.add_record("OUTPUT", Box::new(ao)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("OUTPUT", &mut visited, 0)
        .await
        .unwrap();

    let val = db.get_pv("OUTPUT").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 42.0).abs() < 1e-10),
        other => panic!("expected Double(42.0), got {:?}", other),
    }
}

#[tokio::test]
async fn test_ao_oif_incremental() {
    let db = PvDatabase::new();
    db.add_record("DELTA", Box::new(AoRecord::new(10.0)))
        .await
        .unwrap();

    let mut ao = AoRecord::new(100.0);
    ao.omsl = 1;
    ao.oif = 1;
    ao.dol = "DELTA".to_string();
    db.add_record("OUTPUT", Box::new(ao)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("OUTPUT", &mut visited, 0)
        .await
        .unwrap();

    let val = db.get_pv("OUTPUT").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 110.0).abs() < 1e-10),
        other => panic!("expected Double(110.0), got {:?}", other),
    }
}

#[tokio::test]
async fn test_ao_ivoa_dont_drive() {
    let db = PvDatabase::new();
    db.add_record("TARGET", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    let mut ao = AoRecord::new(999.0);
    ao.ivoa = 1;
    db.add_record("OUTPUT", Box::new(ao)).await.unwrap();

    if let Some(rec) = db.get_record("OUTPUT").await {
        let mut inst = rec.write().await;
        inst.put_common_field("OUT", EpicsValue::String("TARGET".into()))
            .unwrap();
        inst.put_common_field("HIHI", EpicsValue::Double(100.0))
            .unwrap();
        inst.put_common_field("HHSV", EpicsValue::Short(AlarmSeverity::Invalid as i16))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("OUTPUT", &mut visited, 0)
        .await
        .unwrap();

    let val = db.get_pv("TARGET").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 0.0).abs() < 1e-10),
        other => panic!("expected Double(0.0), got {:?}", other),
    }
}

/// Regression: IVOA=2 ("set outputs to IVOV") must route
/// IVOV into the C-conventional output field for each record type.
/// Pre-fix the framework special-cased only `calcout` (OVAL) and fell
/// back to `set_val` (VAL) — every other output record left OVAL/RVAL
/// stale, so the soft-channel OUT writeback (which reads `OVAL.or(VAL)`)
/// shipped the pre-IVOA value instead of IVOV.
/// A `.db` file's `field(ASL, "1")` directive must
/// land in `common.asl`. `db_loader::apply_fields` feeds every common
/// field as `EpicsValue::String`; the ASL handler must parse string
/// numerics or the directive is silently dropped at IOC load.
#[tokio::test]
async fn test_db_load_records_asl_field() {
    use epics_base_rs::server::db_loader;
    use epics_base_rs::server::records::ai::AiRecord;

    let defs = db_loader::parse_db(
        r#"
record(ai, "ASLT:HIGH") {
    field(ASL, "1")
}
record(ai, "ASLT:LOW") {
}
"#,
        &std::collections::HashMap::new(),
    )
    .unwrap();

    let db = PvDatabase::new();
    for def in defs {
        let mut record: Box<dyn epics_base_rs::server::record::Record> =
            Box::new(AiRecord::new(0.0));
        let mut common_fields = Vec::new();
        db_loader::apply_fields(&mut record, &def.fields, &mut common_fields).unwrap();
        db.add_record(&def.name, record).await.unwrap();
        if let Some(rec) = db.get_record(&def.name).await {
            let mut inst = rec.write().await;
            for (n, v) in common_fields {
                let _ = inst.put_common_field(&n, v);
            }
        }
    }

    let high = db.get_record("ASLT:HIGH").await.unwrap();
    let low = db.get_record("ASLT:LOW").await.unwrap();
    assert_eq!(
        high.read().await.common.asl,
        1,
        "field(ASL, \"1\") must set ASL=1"
    );
    assert_eq!(low.read().await.common.asl, 0, "absent ASL defaults to 0");
}

#[tokio::test]
async fn test_ao_ivoa_set_to_ivov_writes_oval() {
    use epics_base_rs::server::records::ao::AoRecord;

    let db = PvDatabase::new();
    db.add_record("TARGET", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    let mut ao = AoRecord::new(7.0);
    ao.ivoa = 2;
    ao.ivov = 42.0;
    db.add_record("SRC", Box::new(ao)).await.unwrap();

    if let Some(rec) = db.get_record("SRC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("OUT", EpicsValue::String("TARGET".into()))
            .unwrap();
        inst.put_common_field("HIHI", EpicsValue::Double(1.0))
            .unwrap();
        inst.put_common_field("HHSV", EpicsValue::Short(AlarmSeverity::Invalid as i16))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("SRC", &mut visited, 0)
        .await
        .unwrap();

    // TARGET should now hold IVOV (42), not the original VAL (7).
    let v = db.get_pv("TARGET").await.unwrap();
    assert!(
        matches!(v, EpicsValue::Double(d) if (d - 42.0).abs() < 1e-9),
        "TARGET must receive IVOV via OVAL: got {v:?}"
    );
    // Source record's OVAL must also reflect IVOV (the C convention).
    let oval = db.get_pv("SRC.OVAL").await.unwrap();
    assert!(
        matches!(oval, EpicsValue::Double(d) if (d - 42.0).abs() < 1e-9),
        "SRC.OVAL must equal IVOV: got {oval:?}"
    );
}

#[tokio::test]
async fn test_bo_ivoa_set_to_ivov_writes_rval() {
    use epics_base_rs::server::records::bo::BoRecord;

    let db = PvDatabase::new();
    let mut bo = BoRecord::new(0);
    bo.ivoa = 2;
    bo.ivov = 1;
    db.add_record("BO_SRC", Box::new(bo)).await.unwrap();
    if let Some(rec) = db.get_record("BO_SRC").await {
        let mut inst = rec.write().await;
        inst.common.nsev = AlarmSeverity::Invalid;
        inst.common.nsta = epics_base_rs::server::recgbl::alarm_status::SOFT_ALARM;
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("BO_SRC", &mut visited, 0)
        .await
        .unwrap();

    // After IVOA=2, RVAL must equal IVOV (=1) — pre-fix it stayed at 0.
    // RVAL is DBF_ULONG (boRecord.dbd.pod:252).
    let rval = db.get_pv("BO_SRC.RVAL").await.unwrap();
    assert!(
        matches!(rval, EpicsValue::ULong(1)),
        "BO_SRC.RVAL must equal IVOV(1): got {rval:?}"
    );
}

#[tokio::test]
async fn test_calcout_ivoa_set_to_ivov_writes_oval_only() {
    use epics_base_rs::server::records::calcout::CalcoutRecord;

    let db = PvDatabase::new();
    db.add_record(
        "OUT_TGT",
        Box::new(epics_base_rs::server::records::ao::AoRecord::new(0.0)),
    )
    .await
    .unwrap();

    let mut co = CalcoutRecord::default();
    co.ivoa = 2;
    co.ivov = 17.5;
    co.val = 99.9;
    co.oval = 99.9;
    co.calc = "A".to_string();
    db.add_record("CO_SRC", Box::new(co)).await.unwrap();
    if let Some(rec) = db.get_record("CO_SRC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("OUT", EpicsValue::String("OUT_TGT".into()))
            .unwrap();
        inst.put_common_field("HIHI", EpicsValue::Double(1.0))
            .unwrap();
        inst.put_common_field("HHSV", EpicsValue::Short(AlarmSeverity::Invalid as i16))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("CO_SRC", &mut visited, 0)
        .await
        .unwrap();

    // OUT_TGT must receive OVAL=IVOV (17.5), not the calc result.
    let v = db.get_pv("OUT_TGT").await.unwrap();
    assert!(
        matches!(v, EpicsValue::Double(d) if (d - 17.5).abs() < 1e-9),
        "OUT_TGT must receive IVOV via OVAL: got {v:?}"
    );
}

#[tokio::test]
async fn test_sim_mode_input() {
    let db = PvDatabase::new();
    db.add_record("SIM_SW", Box::new(AoRecord::new(1.0)))
        .await
        .unwrap();
    db.add_record("SIM_VAL", Box::new(AoRecord::new(99.0)))
        .await
        .unwrap();

    let mut ai = AiRecord::new(0.0);
    ai.siml = "SIM_SW".to_string();
    ai.siol = "SIM_VAL".to_string();
    ai.sims = 1;
    db.add_record("SIM_AI", Box::new(ai)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("SIM_AI", &mut visited, 0)
        .await
        .unwrap();

    let val = db.get_pv("SIM_AI").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 99.0).abs() < 1e-10),
        other => panic!("expected Double(99.0), got {:?}", other),
    }

    let sevr = db.get_pv("SIM_AI.SEVR").await.unwrap();
    assert!(matches!(sevr, EpicsValue::Short(1)));
}

/// A simulated value runs the record's full alarm tail like a real one.
/// C `aiRecord.c`: `readValue()` raises `recGblSetSevr(prec,
/// SIMM_ALARM, prec->sims)` (MAXIMIZE) and `process()` still runs
/// `checkAlarms` + `recGblResetAlarms` on the simulated VAL. So a sim
/// VAL of 99 trips HIHI, and because HHSV (MAJOR) outranks SIMM (MINOR)
/// the limit alarm must WIN — the pre-fix direct-commit clobbered it
/// (and never even evaluated the limit), reporting only MINOR/SIMM.
#[tokio::test]
async fn test_sim_value_trips_own_limit_and_maximizes_over_simm() {
    use epics_base_rs::server::recgbl::alarm_status;

    let db = PvDatabase::new();
    db.add_record("SIM_SW2", Box::new(AoRecord::new(1.0)))
        .await
        .unwrap();
    db.add_record("SIM_VAL2", Box::new(AoRecord::new(99.0)))
        .await
        .unwrap();

    let mut ai = AiRecord::new(0.0);
    ai.siml = "SIM_SW2".to_string();
    ai.siol = "SIM_VAL2".to_string();
    ai.sims = 1; // SIMM severity = MINOR
    db.add_record("SIM_AI2", Box::new(ai)).await.unwrap();
    if let Some(rec) = db.get_record("SIM_AI2").await {
        let mut inst = rec.write().await;
        inst.put_common_field("HIHI", EpicsValue::Double(50.0))
            .unwrap();
        inst.put_common_field("HHSV", EpicsValue::Short(AlarmSeverity::Major as i16))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("SIM_AI2", &mut visited, 0)
        .await
        .unwrap();

    // VAL=99 > HIHI=50 → HIHI MAJOR maximizes over the SIMM MINOR.
    let sevr = db.get_pv("SIM_AI2.SEVR").await.unwrap();
    assert!(
        matches!(sevr, EpicsValue::Short(2)),
        "sim limit MAJOR must win over SIMM MINOR: got {sevr:?}"
    );
    let stat = db.get_pv("SIM_AI2.STAT").await.unwrap();
    assert!(
        matches!(stat, EpicsValue::Short(s) if s as u16 == alarm_status::HIHI_ALARM),
        "STAT must be HIHI_ALARM, not SIMM_ALARM: got {stat:?}"
    );
}

#[tokio::test]
async fn test_sim_mode_toggle() {
    let db = PvDatabase::new();
    db.add_record("SIM_SW", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("SIM_VAL", Box::new(AoRecord::new(42.0)))
        .await
        .unwrap();
    db.add_record("REAL_SRC", Box::new(AoRecord::new(10.0)))
        .await
        .unwrap();

    let mut ai = AiRecord::new(0.0);
    ai.siml = "SIM_SW".to_string();
    ai.siol = "SIM_VAL".to_string();
    db.add_record("TEST_AI", Box::new(ai)).await.unwrap();

    if let Some(rec) = db.get_record("TEST_AI").await {
        let mut inst = rec.write().await;
        inst.put_common_field("INP", EpicsValue::String("REAL_SRC".into()))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("TEST_AI", &mut visited, 0)
        .await
        .unwrap();
    let val = db.get_pv("TEST_AI").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 10.0).abs() < 1e-10),
        other => panic!("expected Double(10.0), got {:?}", other),
    }

    db.put_pv("SIM_SW", EpicsValue::Double(1.0)).await.unwrap();
    let mut visited = HashSet::new();
    db.process_record_with_links("TEST_AI", &mut visited, 0)
        .await
        .unwrap();
    let val = db.get_pv("TEST_AI").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 42.0).abs() < 1e-10),
        other => panic!("expected Double(42.0), got {:?}", other),
    }
}

#[tokio::test]
async fn test_sim_mode_output() {
    let db = PvDatabase::new();
    db.add_record("SIM_SW", Box::new(AoRecord::new(1.0)))
        .await
        .unwrap();
    db.add_record("SIM_OUT", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    let mut ao = AoRecord::new(77.0);
    ao.siml = "SIM_SW".to_string();
    ao.siol = "SIM_OUT".to_string();
    db.add_record("TEST_AO", Box::new(ao)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("TEST_AO", &mut visited, 0)
        .await
        .unwrap();

    let val = db.get_pv("SIM_OUT").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 77.0).abs() < 1e-10),
        other => panic!("expected Double(77.0), got {:?}", other),
    }
}

/// A SIMM-mode **input** record whose SIOL points at a NON-LOCAL record
/// must read the simulated value through the external CA path, not a
/// local lookup. C `readValue` reads SIOL via `dbGetLink`, and
/// `dbInitLink` (dbLink.c:118-130) made the non-local SIOL a CA link, so
/// the read is `dbCaGetLink`. The pre-fix port special-cased only a
/// local `ParsedLink::Db` SIOL, so a non-local SIOL read nothing yet
/// still returned `Simulated` — the record froze with no value. This is
/// the INPUT twin of the OUT-link locality fallback.
#[tokio::test]
async fn test_sim_mode_input_nonlocal_db_siol() {
    use epics_base_rs::server::database::LinkSet;
    struct ValueCaLset(f64);
    impl LinkSet for ValueCaLset {
        fn is_connected(&self, _: &str) -> bool {
            true
        }
        fn get_value(&self, name: &str) -> Option<EpicsValue> {
            // The bare non-local SIOL record name reaches the CA lset
            // via the read-locality fallback `resolve_external_pv`.
            (name == "REMOTE:SIM").then_some(EpicsValue::Double(self.0))
        }
    }

    let db = PvDatabase::new();
    db.register_link_set("ca", Arc::new(ValueCaLset(73.0)))
        .await;
    db.add_record("SIM_SW", Box::new(AoRecord::new(1.0)))
        .await
        .unwrap();

    let mut ai = AiRecord::new(0.0);
    ai.siml = "SIM_SW".to_string();
    // REMOTE:SIM is never added locally → dbInitLink makes it a CA link.
    ai.siol = "REMOTE:SIM".to_string();
    ai.sims = 1;
    db.add_record("SIM_AI_NL", Box::new(ai)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("SIM_AI_NL", &mut visited, 0)
        .await
        .unwrap();

    let val = db.get_pv("SIM_AI_NL").await.unwrap();
    assert!(
        matches!(val, EpicsValue::Double(v) if (v - 73.0).abs() < 1e-10),
        "non-local Db SIOL must read the remote sim value into VAL: got {val:?}"
    );
}

/// A SIMM-mode **output** record whose SIOL points at a NON-LOCAL
/// record must write the simulated value through the external CA put
/// path (C `writeValue` → `dbPutLink` → `dbCaPutLink`), not a local
/// `dbPut`. OUTPUT twin of `test_sim_mode_input_nonlocal_db_siol`; the
/// pre-fix port special-cased only a local `ParsedLink::Db` SIOL, so a
/// non-local SIOL write went nowhere.
#[tokio::test]
async fn test_sim_mode_output_nonlocal_db_siol() {
    use std::sync::Mutex;

    use epics_base_rs::server::database::LinkPutOp;

    let writes = Arc::new(Mutex::new(Vec::new()));
    let db = PvDatabase::new();
    db.register_link_set(
        "ca",
        Arc::new(CapturingLset {
            writes: writes.clone(),
        }),
    )
    .await;
    db.add_record("SIM_SW", Box::new(AoRecord::new(1.0)))
        .await
        .unwrap();

    let mut ao = AoRecord::new(55.0);
    ao.siml = "SIM_SW".to_string();
    // REMOTE:OUT is never added locally → dbInitLink makes it a CA link.
    ao.siol = "REMOTE:OUT".to_string();
    db.add_record("TEST_AO_NL", Box::new(ao)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("TEST_AO_NL", &mut visited, 0)
        .await
        .unwrap();

    let captured = writes.lock().unwrap();
    assert_eq!(
        captured.len(),
        1,
        "the non-local SIOL must drive exactly one external put_value"
    );
    assert_eq!(
        captured[0].0, "REMOTE:OUT",
        "put_value must receive the bare SIOL record name"
    );
    assert_eq!(
        captured[0].1.to_f64(),
        Some(55.0),
        "put_value must receive the simulated output value"
    );
    assert_eq!(
        captured[0].2,
        LinkPutOp::Plain,
        "a SIMM-mode simulation write is a Plain put"
    );
}

#[tokio::test]
async fn test_sdis_disable_skips_process() {
    let db = PvDatabase::new();
    db.add_record("DISABLE_SW", Box::new(AoRecord::new(1.0)))
        .await
        .unwrap();
    db.add_record("TARGET", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    if let Some(rec) = db.get_record("TARGET").await {
        let mut inst = rec.write().await;
        inst.put_common_field("SDIS", EpicsValue::String("DISABLE_SW".into()))
            .unwrap();
        inst.put_common_field("DISS", EpicsValue::Short(1)).unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("TARGET", &mut visited, 0)
        .await
        .unwrap();

    let rec = db.get_record("TARGET").await.unwrap();
    let inst = rec.read().await;
    // C `menuAlarmStat.dbd`: DISABLE = 18.
    assert_eq!(
        inst.common.stat,
        epics_base_rs::server::recgbl::alarm_status::DISABLE_ALARM
    );
    assert_eq!(inst.common.sevr, AlarmSeverity::Minor);

    drop(inst);
    db.put_pv("DISABLE_SW", EpicsValue::Double(0.0))
        .await
        .unwrap();
    let mut visited = HashSet::new();
    db.process_record_with_links("TARGET", &mut visited, 0)
        .await
        .unwrap();

    let rec = db.get_record("TARGET").await.unwrap();
    let inst = rec.read().await;
    assert_ne!(
        inst.common.stat,
        epics_base_rs::server::recgbl::alarm_status::DISABLE_ALARM
    );
}

/// C `dbGetLink(&precord->sdis, DBR_SHORT, &precord->disa, 0, 0)`
/// reads the SDIS link for ANY type. The pre-fix port refreshed `disa`
/// only for a `ParsedLink::Db` SDIS, so a constant (and CA/PVA) SDIS was
/// silently ignored — `disa` stayed at its default and a record meant to
/// be disabled by a constant SDIS kept processing. Boundary: constant
/// value == DISV (disabled) vs != DISV (enabled).
#[tokio::test]
async fn test_sdis_constant_link_refreshes_disa() {
    let db = PvDatabase::new();
    db.add_record("TARGET", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    // Constant SDIS "1" — equals the default DISV (1) → disabled.
    if let Some(rec) = db.get_record("TARGET").await {
        let mut inst = rec.write().await;
        inst.put_common_field("SDIS", EpicsValue::String("1".into()))
            .unwrap();
        inst.put_common_field("DISS", EpicsValue::Short(1)).unwrap();
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("TARGET", &mut visited, 0)
        .await
        .unwrap();
    {
        let rec = db.get_record("TARGET").await.unwrap();
        let inst = rec.read().await;
        assert_eq!(
            inst.common.disa, 1,
            "constant SDIS '1' must refresh disa to 1 (was ignored pre-fix)"
        );
        assert_eq!(
            inst.common.stat,
            epics_base_rs::server::recgbl::alarm_status::DISABLE_ALARM,
            "disa==disv must disable the record"
        );
    }

    // Constant SDIS "0" — differs from DISV (1) → re-enabled. Proves the
    // refresh reads the actual constant value, not a hard-coded disable.
    if let Some(rec) = db.get_record("TARGET").await {
        let mut inst = rec.write().await;
        inst.put_common_field("SDIS", EpicsValue::String("0".into()))
            .unwrap();
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("TARGET", &mut visited, 0)
        .await
        .unwrap();
    {
        let rec = db.get_record("TARGET").await.unwrap();
        let inst = rec.read().await;
        assert_eq!(
            inst.common.disa, 0,
            "constant SDIS '0' must refresh disa to 0"
        );
        assert_ne!(
            inst.common.stat,
            epics_base_rs::server::recgbl::alarm_status::DISABLE_ALARM,
            "disa!=disv must leave the record enabled"
        );
    }
}

#[tokio::test]
async fn test_phas_scan_order() {
    let db = PvDatabase::new();

    db.add_record("REC_C", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("REC_A", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("REC_B", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    for (name, phas) in &[("REC_C", 2i16), ("REC_A", 0), ("REC_B", 1)] {
        if let Some(rec) = db.get_record(name).await {
            let mut inst = rec.write().await;
            inst.put_common_field("PHAS", EpicsValue::Short(*phas))
                .unwrap();
            let result = inst
                .put_common_field("SCAN", EpicsValue::String("1 second".into()))
                .unwrap();
            if let CommonFieldPutResult::ScanChanged {
                old_scan,
                new_scan,
                phas: p,
            } = result
            {
                drop(inst);
                db.update_scan_index(name, old_scan, new_scan, p, p).await;
            }
        }
    }

    let names = db.records_for_scan(ScanType::Sec1).await;
    assert_eq!(names, vec!["REC_A", "REC_B", "REC_C"]);
}

#[tokio::test]
async fn test_depth_limit() {
    let db = PvDatabase::new();
    for i in 0..20 {
        db.add_record(&format!("CHAIN_{i}"), Box::new(AoRecord::new(0.0)))
            .await
            .unwrap();
    }
    for i in 0..19 {
        if let Some(rec) = db.get_record(&format!("CHAIN_{i}")).await {
            let mut inst = rec.write().await;
            inst.put_common_field(
                "FLNK",
                EpicsValue::String(format!("CHAIN_{}", i + 1).into()),
            )
            .unwrap();
        }
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("CHAIN_0", &mut visited, 0)
        .await
        .unwrap();
    assert!(visited.len() <= 17);
    assert!(visited.contains("CHAIN_0"));
}

#[tokio::test]
async fn test_disp_blocks_ca_put() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    if let Some(rec) = db.get_record("REC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("DISP", EpicsValue::Char(1)).unwrap();
    }

    let result = db
        .put_record_field_from_ca("REC", "VAL", EpicsValue::Double(42.0))
        .await;
    assert!(matches!(result, Err(CaError::PutDisabled(_))));
}

#[tokio::test]
async fn test_disp_allows_disp_write() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    if let Some(rec) = db.get_record("REC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("DISP", EpicsValue::Char(1)).unwrap();
    }

    let result = db
        .put_record_field_from_ca("REC", "DISP", EpicsValue::Char(0))
        .await;
    assert!(result.is_ok());

    let rec = db.get_record("REC").await.unwrap();
    let inst = rec.read().await;
    assert!(!inst.common.disp);
}

#[tokio::test]
async fn test_disp_bypassed_by_internal_put() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    if let Some(rec) = db.get_record("REC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("DISP", EpicsValue::Char(1)).unwrap();
    }

    let result = db.put_pv("REC", EpicsValue::Double(42.0)).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_proc_triggers_processing() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.put_pv("REC", EpicsValue::Double(42.0)).await.unwrap();
    let result = db
        .put_record_field_from_ca("REC", "PROC", EpicsValue::Char(1))
        .await;
    assert!(result.is_ok());
    let rec = db.get_record("REC").await.unwrap();
    let inst = rec.read().await;
    assert!(!inst.common.udf);
}

#[tokio::test]
async fn test_proc_works_any_scan() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("REC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("SCAN", EpicsValue::String("1 second".into()))
            .unwrap();
    }
    let result = db
        .put_record_field_from_ca("REC", "PROC", EpicsValue::Char(1))
        .await;
    assert!(result.is_ok());
    let rec = db.get_record("REC").await.unwrap();
    let inst = rec.read().await;
    assert!(!inst.common.udf);
}

#[tokio::test]
async fn test_proc_bypasses_disp() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("REC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("DISP", EpicsValue::Char(1)).unwrap();
    }
    let result = db
        .put_record_field_from_ca("REC", "PROC", EpicsValue::Char(1))
        .await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_proc_while_pact() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let result = db
        .put_record_field_from_ca("REC", "PROC", EpicsValue::Char(1))
        .await;
    assert!(result.is_ok());
    let rec = db.get_record("REC").await.unwrap();
    let inst = rec.read().await;
    assert!(!inst.common.udf);
}

#[tokio::test]
async fn test_lcnt_ca_write_rejected() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let result = db
        .put_record_field_from_ca("REC", "LCNT", EpicsValue::Short(0))
        .await;
    assert!(matches!(result, Err(CaError::ReadOnlyField(_))));
}

#[tokio::test]
async fn test_ca_put_scan_index_update() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.put_record_field_from_ca("REC", "SCAN", EpicsValue::String("1 second".into()))
        .await
        .unwrap();
    let names = db.records_for_scan(ScanType::Sec1).await;
    assert!(names.contains(&"REC".to_string()));
}

// --- Mock DeviceSupport for write/read counting ---

struct MockDeviceSupport {
    read_count: Arc<AtomicU32>,
    write_count: Arc<AtomicU32>,
    dtyp_name: String,
}

impl MockDeviceSupport {
    fn new(dtyp: &str, read_count: Arc<AtomicU32>, write_count: Arc<AtomicU32>) -> Self {
        Self {
            read_count,
            write_count,
            dtyp_name: dtyp.to_string(),
        }
    }
}

impl epics_base_rs::server::device_support::DeviceSupport for MockDeviceSupport {
    fn read(
        &mut self,
        _record: &mut dyn Record,
    ) -> epics_base_rs::error::CaResult<epics_base_rs::server::device_support::DeviceReadOutcome>
    {
        self.read_count.fetch_add(1, Ordering::SeqCst);
        Ok(epics_base_rs::server::device_support::DeviceReadOutcome::ok())
    }
    fn write(&mut self, _record: &mut dyn Record) -> epics_base_rs::error::CaResult<()> {
        self.write_count.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }
    fn dtyp(&self) -> &str {
        &self.dtyp_name
    }
}

#[tokio::test]
async fn test_ca_put_no_double_device_write() {
    let db = PvDatabase::new();
    db.add_record("AO_REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let read_count = Arc::new(AtomicU32::new(0));
    let write_count = Arc::new(AtomicU32::new(0));
    let mock = MockDeviceSupport::new("MockDev", read_count.clone(), write_count.clone());
    if let Some(rec) = db.get_record("AO_REC").await {
        let mut inst = rec.write().await;
        inst.common.dtyp = "MockDev".to_string();
        inst.device = Some(Box::new(mock));
    }
    db.put_record_field_from_ca("AO_REC", "VAL", EpicsValue::Double(42.0))
        .await
        .unwrap();
    assert_eq!(write_count.load(Ordering::SeqCst), 1);
}

// epics-base f2fe9d12 (devBiSoftRaw): a `bi` record with
// `DTYP="Raw Soft Channel"`, MASK set, and a soft INP link must mask
// the link value into RVAL before the RVAL→VAL convert. The framework
// must route the INP value to `apply_raw_input` (not `set_val`).
#[tokio::test]
async fn test_bi_raw_soft_channel_inp_applies_mask() {
    let db = PvDatabase::new();
    db.add_record("SRC_LI", Box::new(LonginRecord::new(0)))
        .await
        .unwrap();
    db.add_record("BI_RAW", Box::new(BiRecord::new(0)))
        .await
        .unwrap();
    db.put_record_field_from_ca("SRC_LI", "VAL", EpicsValue::Long(0xFF))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("BI_RAW").await {
        let mut inst = rec.write().await;
        inst.common.dtyp = "Raw Soft Channel".to_string();
        inst.common.inp = "SRC_LI".to_string();
        inst.parsed_inp = epics_base_rs::server::record::parse_link_v2(&inst.common.inp);
        inst.record
            .put_field("MASK", EpicsValue::Long(0x0F))
            .unwrap();
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("BI_RAW", &mut visited, 0)
        .await
        .unwrap();
    if let Some(rec) = db.get_record("BI_RAW").await {
        let inst = rec.read().await;
        let rval = inst.record.get_field("RVAL");
        // RVAL is DBF_ULONG (biRecord.dbd.pod:199).
        assert_eq!(
            rval,
            Some(EpicsValue::ULong(0x0F)),
            "MASK must clamp RVAL to low nibble"
        );
        let val = inst.record.get_field("VAL");
        assert_eq!(
            val,
            Some(EpicsValue::Enum(1)),
            "masked-non-zero RVAL → VAL=1"
        );
    }
}

#[tokio::test]
async fn test_input_record_no_device_write() {
    let db = PvDatabase::new();
    db.add_record("AI_REC", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();
    let read_count = Arc::new(AtomicU32::new(0));
    let write_count = Arc::new(AtomicU32::new(0));
    let mock = MockDeviceSupport::new("MockDev", read_count.clone(), write_count.clone());
    if let Some(rec) = db.get_record("AI_REC").await {
        let mut inst = rec.write().await;
        inst.common.dtyp = "MockDev".to_string();
        inst.device = Some(Box::new(mock));
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("AI_REC", &mut visited, 0)
        .await
        .unwrap();
    assert_eq!(read_count.load(Ordering::SeqCst), 1);
    assert_eq!(write_count.load(Ordering::SeqCst), 0);
}

// Device support that attaches a fixed userTag to its reading, like a
// timing receiver delivering a pulse-id. `epicsTimeStamp` carries no
// tag, so C device support writes `prec->utag` directly during
// `read()` (alongside `prec->time`, TSE=-2); the Rust framework picks
// it up from `last_utag()`.
struct UtagDeviceSupport {
    utag: u64,
}

impl epics_base_rs::server::device_support::DeviceSupport for UtagDeviceSupport {
    fn read(
        &mut self,
        _record: &mut dyn Record,
    ) -> epics_base_rs::error::CaResult<epics_base_rs::server::device_support::DeviceReadOutcome>
    {
        Ok(epics_base_rs::server::device_support::DeviceReadOutcome::ok())
    }
    fn write(&mut self, _record: &mut dyn Record) -> epics_base_rs::error::CaResult<()> {
        Ok(())
    }
    fn dtyp(&self) -> &str {
        "UtagDev"
    }
    fn last_utag(&self) -> Option<u64> {
        Some(self.utag)
    }
}

#[tokio::test]
async fn test_device_support_utag_adopted_into_common() {
    // A device that reports a userTag via `last_utag()` must have it
    // adopted into `common.utag` when the record is processed, mirroring
    // C device support writing `prec->utag` directly. Bit 31 set
    // (0x9000_0000) guards against any narrowing/sign mishandling on the
    // adoption path.
    let db = PvDatabase::new();
    db.add_record("AI_UTAG", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("AI_UTAG").await {
        let mut inst = rec.write().await;
        inst.common.dtyp = "UtagDev".to_string();
        inst.device = Some(Box::new(UtagDeviceSupport { utag: 0x9000_0000 }));
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("AI_UTAG", &mut visited, 0)
        .await
        .unwrap();
    if let Some(rec) = db.get_record("AI_UTAG").await {
        let inst = rec.read().await;
        assert_eq!(
            inst.common.utag, 0x9000_0000,
            "device-reported userTag must be adopted into common.utag"
        );
    }
}

#[tokio::test]
async fn test_non_passive_output_ca_put_defers_write_until_scan() {
    // C `dbAccess.c::dbPutField:1263-1266` only processes a record on a
    // put when `precord->scan == 0` (Passive). A CA put to a non-Passive
    // (here 1-second-scanned) output record updates VAL but does NOT
    // process — the device write happens on the next scan, not at put.
    let db = PvDatabase::new();
    db.add_record("AO_NP", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let read_count = Arc::new(AtomicU32::new(0));
    let write_count = Arc::new(AtomicU32::new(0));
    let mock = MockDeviceSupport::new("MockDev", read_count.clone(), write_count.clone());
    if let Some(rec) = db.get_record("AO_NP").await {
        let mut inst = rec.write().await;
        inst.common.dtyp = "MockDev".to_string();
        inst.common.scan = ScanType::Sec1;
        inst.device = Some(Box::new(mock));
    }
    db.put_record_field_from_ca("AO_NP", "VAL", EpicsValue::Double(42.0))
        .await
        .unwrap();
    assert_eq!(
        write_count.load(Ordering::SeqCst),
        0,
        "put to a non-Passive record must not process/write at put time"
    );

    // The periodic scan processes the record and writes the new VAL.
    let mut visited = HashSet::new();
    db.process_record_with_links("AO_NP", &mut visited, 0)
        .await
        .unwrap();
    assert_eq!(
        write_count.load(Ordering::SeqCst),
        1,
        "the scan cycle writes the value the put staged"
    );
}

#[tokio::test]
async fn test_proc_triggers_device_write() {
    let db = PvDatabase::new();
    db.add_record("AO_PROC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let read_count = Arc::new(AtomicU32::new(0));
    let write_count = Arc::new(AtomicU32::new(0));
    let mock = MockDeviceSupport::new("MockDev", read_count.clone(), write_count.clone());
    if let Some(rec) = db.get_record("AO_PROC").await {
        let mut inst = rec.write().await;
        inst.common.dtyp = "MockDev".to_string();
        inst.device = Some(Box::new(mock));
    }
    db.put_record_field_from_ca("AO_PROC", "PROC", EpicsValue::Char(1))
        .await
        .unwrap();
    assert_eq!(write_count.load(Ordering::SeqCst), 1);
}

// --- Scan Index Fix tests ---

#[tokio::test]
async fn test_phas_change_updates_scan_index() {
    let db = PvDatabase::new();
    db.add_record("REC_A", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("REC_B", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    for (name, phas) in &[("REC_A", 10i16), ("REC_B", 5)] {
        if let Some(rec) = db.get_record(name).await {
            let mut inst = rec.write().await;
            inst.put_common_field("PHAS", EpicsValue::Short(*phas))
                .unwrap();
            let result = inst
                .put_common_field("SCAN", EpicsValue::String("1 second".into()))
                .unwrap();
            if let CommonFieldPutResult::ScanChanged {
                old_scan,
                new_scan,
                phas: p,
            } = result
            {
                drop(inst);
                db.update_scan_index(name, old_scan, new_scan, p, p).await;
            }
        }
    }
    let names = db.records_for_scan(ScanType::Sec1).await;
    assert_eq!(names, vec!["REC_B", "REC_A"]);

    if let Some(rec) = db.get_record("REC_A").await {
        let mut inst = rec.write().await;
        let result = inst.put_common_field("PHAS", EpicsValue::Short(0)).unwrap();
        if let CommonFieldPutResult::PhasChanged {
            scan,
            old_phas,
            new_phas,
        } = result
        {
            drop(inst);
            db.update_scan_index("REC_A", scan, scan, old_phas, new_phas)
                .await;
        }
    }
    let names = db.records_for_scan(ScanType::Sec1).await;
    assert_eq!(names, vec!["REC_A", "REC_B"]);
}

#[tokio::test]
async fn test_scan_change_preserves_phas() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("REC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("PHAS", EpicsValue::Short(3)).unwrap();
        let result = inst
            .put_common_field("SCAN", EpicsValue::String("1 second".into()))
            .unwrap();
        match result {
            CommonFieldPutResult::ScanChanged { phas, .. } => assert_eq!(phas, 3),
            other => panic!("expected ScanChanged, got {:?}", other),
        }
    }
}

#[tokio::test]
async fn test_phas_change_passive_no_index() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("REC").await {
        let mut inst = rec.write().await;
        let result = inst.put_common_field("PHAS", EpicsValue::Short(5)).unwrap();
        assert_eq!(result, CommonFieldPutResult::NoChange);
    }
}

// --- Async Processing Contract tests ---

struct AsyncRecord {
    val: f64,
}
impl Record for AsyncRecord {
    fn record_type(&self) -> &'static str {
        "async_test"
    }
    fn process(&mut self) -> epics_base_rs::error::CaResult<ProcessOutcome> {
        Ok(ProcessOutcome::async_pending())
    }
    fn get_field(&self, name: &str) -> Option<EpicsValue> {
        match name {
            "VAL" => Some(EpicsValue::Double(self.val)),
            _ => None,
        }
    }
    fn put_field(&mut self, name: &str, value: EpicsValue) -> epics_base_rs::error::CaResult<()> {
        match name {
            "VAL" => {
                if let EpicsValue::Double(v) = value {
                    self.val = v;
                    Ok(())
                } else {
                    Err(CaError::InvalidValue("bad".into()))
                }
            }
            _ => Err(CaError::FieldNotFound(name.into())),
        }
    }
    fn field_list(&self) -> &'static [FieldDesc] {
        &[]
    }
}

#[tokio::test]
async fn test_async_pending_skips_post_process() {
    let db = PvDatabase::new();
    db.add_record("ASYNC", Box::new(AsyncRecord { val: 0.0 }))
        .await
        .unwrap();
    db.add_record("FLNK_TARGET", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("ASYNC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("FLNK", EpicsValue::String("FLNK_TARGET".into()))
            .unwrap();
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC", &mut visited, 0)
        .await
        .unwrap();
    assert!(visited.contains("ASYNC"));
    assert!(!visited.contains("FLNK_TARGET"));
    let rec = db.get_record("ASYNC").await.unwrap();
    let inst = rec.read().await;
    assert!(inst.common.udf);
}

#[tokio::test]
async fn test_complete_async_record() {
    let db = PvDatabase::new();
    db.add_record("ASYNC", Box::new(AsyncRecord { val: 42.0 }))
        .await
        .unwrap();
    db.add_record("FLNK_TARGET", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("ASYNC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("FLNK", EpicsValue::String("FLNK_TARGET".into()))
            .unwrap();
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC", &mut visited, 0)
        .await
        .unwrap();
    assert!(!visited.contains("FLNK_TARGET"));
    db.complete_async_record("ASYNC").await.unwrap();
    let rec = db.get_record("ASYNC").await.unwrap();
    let inst = rec.read().await;
    assert!(!inst.common.udf);
}

/// Defect 1 regression: the async-completion path
/// (`complete_async_record_inner`) must post SEVR/STAT/AMSG with
/// their per-field C masks — exactly like the synchronous path and
/// `process_local` — not collapse them onto one record-wide mask.
///
/// C `recGblResetAlarms` posts SEVR with `DBE_VALUE` only. The pre-fix
/// async path pushed SEVR into `changed_fields`, which `notify_from_
/// snapshot` posts with the record-wide `event_mask` that carries
/// `DBE_ALARM` on an alarm transition. So a `DBE_ALARM`-only SEVR
/// subscriber was wrongly notified, and a `DBE_VALUE`-only SEVR
/// subscriber on a stat-only transition would have been missed.
///
/// This test drives an alarm transition through `complete_async_record`
/// and asserts:
///  * a `DBE_VALUE`-only SEVR subscriber RECEIVES the event,
///  * a `DBE_ALARM`-only SEVR subscriber does NOT (SEVR is DBE_VALUE).
/// Async record stub that raises a MAJOR `STATE_ALARM` from its
/// `check_alarms` hook — used to drive an alarm transition through
/// the async-completion path.
struct AsyncAlarmingRecord;
impl Record for AsyncAlarmingRecord {
    fn record_type(&self) -> &'static str {
        "async_alarm_test"
    }
    fn process(&mut self) -> epics_base_rs::error::CaResult<ProcessOutcome> {
        Ok(ProcessOutcome::async_pending())
    }
    fn check_alarms(&mut self, common: &mut epics_base_rs::server::record::CommonFields) {
        use epics_base_rs::server::recgbl::{self, alarm_status};
        recgbl::rec_gbl_set_sevr(
            common,
            alarm_status::STATE_ALARM,
            epics_base_rs::server::record::AlarmSeverity::Major,
        );
    }
    fn get_field(&self, name: &str) -> Option<EpicsValue> {
        match name {
            "VAL" => Some(EpicsValue::Double(1.0)),
            _ => None,
        }
    }
    fn put_field(&mut self, name: &str, _value: EpicsValue) -> epics_base_rs::error::CaResult<()> {
        match name {
            "VAL" => Ok(()),
            _ => Err(CaError::FieldNotFound(name.into())),
        }
    }
    fn field_list(&self) -> &'static [FieldDesc] {
        &[]
    }
}

#[tokio::test]
async fn test_complete_async_posts_sevr_with_per_field_mask() {
    use epics_base_rs::server::recgbl::EventMask;
    use epics_base_rs::server::record::AlarmSeverity;
    use epics_base_rs::types::DbFieldType;

    let db = PvDatabase::new();
    db.add_record("ASYNC_SEVR", Box::new(AsyncAlarmingRecord))
        .await
        .unwrap();

    if let Some(rec) = db.get_record("ASYNC_SEVR").await {
        let mut inst = rec.write().await;
        inst.common.udf = false;
    }

    // First cycle: record reports async_pending (PACT set).
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC_SEVR", &mut visited, 0)
        .await
        .unwrap();

    // Subscribe to SEVR twice: one DBE_VALUE-only, one DBE_ALARM-only.
    let (mut sevr_value_rx, mut sevr_alarm_rx) = {
        let rec = db.get_record("ASYNC_SEVR").await.unwrap();
        let mut inst = rec.write().await;
        let v = inst
            .add_subscriber("SEVR", 21, DbFieldType::Short, EventMask::VALUE.bits())
            .expect("DBE_VALUE SEVR subscription accepted");
        let a = inst
            .add_subscriber("SEVR", 22, DbFieldType::Short, EventMask::ALARM.bits())
            .expect("DBE_ALARM SEVR subscription accepted");
        (v, a)
    };

    // Complete the async cycle — alarm transition NoAlarm -> Major.
    db.complete_async_record("ASYNC_SEVR").await.unwrap();

    {
        let rec = db.get_record("ASYNC_SEVR").await.unwrap();
        let inst = rec.read().await;
        assert_eq!(
            inst.common.sevr,
            AlarmSeverity::Major,
            "completion must raise Major"
        );
    }

    // DBE_VALUE SEVR subscriber MUST receive the event — SEVR posts
    // with DBE_VALUE.
    assert!(
        sevr_value_rx.try_recv().is_ok(),
        "DBE_VALUE SEVR subscriber must receive the SEVR change"
    );
    // DBE_ALARM-only SEVR subscriber must NOT — SEVR's C mask is
    // DBE_VALUE only, never DBE_ALARM.
    assert!(
        sevr_alarm_rx.try_recv().is_err(),
        "DBE_ALARM-only SEVR subscriber must NOT receive SEVR \
         (per-field mask collapsed onto record-wide ALARM mask)"
    );
}

// C parity (dbAccess.c::dbProcess:537-559): a second
// `process_record_with_links` against a PACT-active record must NOT
// re-enter `record.process()`. The first attempt must bail silently
// (lcnt counting up); after MAX_LOCK=10 consecutive bails, SCAN_ALARM /
// INVALID must be raised with "Async in progress" amsg and VAL must be
// posted with DBE_VALUE|DBE_LOG|DBE_ALARM.
#[tokio::test]
async fn test_pact_entry_guard_silent_bail_until_max_lock() {
    use epics_base_rs::server::record::AlarmSeverity;

    let db = PvDatabase::new();
    db.add_record("ASYNC_PACT", Box::new(AsyncRecord { val: 0.0 }))
        .await
        .unwrap();

    // Drive ASYNC_PACT into PACT=true (async pending, lock released).
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC_PACT", &mut visited, 0)
        .await
        .unwrap();
    {
        let rec = db.get_record("ASYNC_PACT").await.unwrap();
        let inst = rec.read().await;
        assert!(
            inst.is_processing(),
            "first cycle must leave PACT=true (AsyncPending)"
        );
        assert_eq!(inst.common.lcnt, 0, "first cycle must reset lcnt");
        assert_eq!(inst.common.sevr, AlarmSeverity::NoAlarm);
    }

    // Up to MAX_LOCK = 10 re-entries while PACT=true must NOT raise alarm.
    for i in 1..=10 {
        let mut visited = HashSet::new();
        db.process_record_with_links("ASYNC_PACT", &mut visited, 0)
            .await
            .unwrap();
        let rec = db.get_record("ASYNC_PACT").await.unwrap();
        let inst = rec.read().await;
        assert!(inst.is_processing(), "must remain PACT=true (iter {i})");
        assert_eq!(inst.common.lcnt, i as i16, "lcnt must increment per bail");
        assert_eq!(
            inst.common.sevr,
            AlarmSeverity::NoAlarm,
            "no SCAN_ALARM yet (iter {i})"
        );
    }

    // 11th attempt while pact (lcnt==10 before increment >= MAX_LOCK)
    // must raise SCAN_ALARM/INVALID and post VAL monitor.
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC_PACT", &mut visited, 0)
        .await
        .unwrap();
    let rec = db.get_record("ASYNC_PACT").await.unwrap();
    let inst = rec.read().await;
    assert!(inst.is_processing(), "PACT still true post-alarm-raise");
    assert_eq!(inst.common.sevr, AlarmSeverity::Invalid);
    assert_eq!(
        inst.common.stat,
        epics_base_rs::server::recgbl::alarm_status::SCAN_ALARM
    );
    assert_eq!(inst.common.amsg, "Async in progress");
}

// C `dbAccess.c:539-541` — when TPRO is set on a record whose PACT is
// true, dbProcess prints "<thread>: dbProcess of Active '<name>' with
// RPRO=<n>" before the bail decision. The Rust port emits the same
// line via eprintln; this test exercises the path and verifies (a)
// TPRO=true does not interfere with the bail decision (lcnt still
// increments) and (b) RPRO state is preserved through the guard so
// the diagnostic value is meaningful.
#[tokio::test]
async fn test_pact_entry_guard_tpro_diagnostic_does_not_change_bail_outcome() {
    let db = PvDatabase::new();
    db.add_record("ASYNC_TPRO", Box::new(AsyncRecord { val: 0.0 }))
        .await
        .unwrap();

    // Set TPRO=true and RPRO=true so the diagnostic line carries
    // observable state.
    {
        let rec = db.get_record("ASYNC_TPRO").await.unwrap();
        let mut inst = rec.write().await;
        inst.common.tpro = true;
        inst.common.rpro = true;
    }

    // Cycle 1: drive into PACT.
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC_TPRO", &mut visited, 0)
        .await
        .unwrap();
    {
        let rec = db.get_record("ASYNC_TPRO").await.unwrap();
        let inst = rec.read().await;
        assert!(inst.is_processing(), "must enter PACT");
        assert!(inst.common.tpro, "TPRO must be preserved");
        assert!(inst.common.rpro, "RPRO must be preserved across PACT entry");
    }

    // Re-entry while PACT=true: bail with lcnt increment. Diagnostic
    // is emitted as a side effect (eprintln) but the bail outcome
    // matches the non-TPRO case (verified by the silent-bail test).
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC_TPRO", &mut visited, 0)
        .await
        .unwrap();
    let rec = db.get_record("ASYNC_TPRO").await.unwrap();
    let inst = rec.read().await;
    assert!(inst.is_processing(), "still PACT after bail");
    assert_eq!(inst.common.lcnt, 1, "lcnt must have advanced");
    assert!(
        inst.common.rpro,
        "RPRO must remain unchanged by the diagnostic path"
    );
}

// After PACT clears via complete_async_record, the next process must
// reset lcnt to 0 (mirrors C `else { precord->lcnt = 0; }`).
#[tokio::test]
async fn test_pact_entry_guard_resets_lcnt_after_completion() {
    let db = PvDatabase::new();
    db.add_record("ASYNC_RESET", Box::new(AsyncRecord { val: 0.0 }))
        .await
        .unwrap();

    // Cycle 1: kick off async, accumulate lcnt via re-entries.
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC_RESET", &mut visited, 0)
        .await
        .unwrap();
    for _ in 0..3 {
        let mut visited = HashSet::new();
        db.process_record_with_links("ASYNC_RESET", &mut visited, 0)
            .await
            .unwrap();
    }
    {
        let rec = db.get_record("ASYNC_RESET").await.unwrap();
        assert_eq!(rec.read().await.common.lcnt, 3);
    }

    // Complete the async; this clears PACT.
    db.complete_async_record("ASYNC_RESET").await.unwrap();

    // Next process_record_with_links should reset lcnt (path: enters
    // body since PACT is now false).
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC_RESET", &mut visited, 0)
        .await
        .unwrap();
    let rec = db.get_record("ASYNC_RESET").await.unwrap();
    let inst = rec.read().await;
    assert_eq!(inst.common.lcnt, 0, "lcnt must reset when PACT clears");
}

// Regression: when a record returns `AsyncPending` paired with a
// `ReprocessAfter` action (the timer-owned continuation pattern used
// by scaler DLY / calc AFTC), the spawned timer fire must call
// `process_record_continuation` and bypass the PACT entry guard so
// the record's `process()` runs again to advance the state machine.
// The foreign-caller guard (FLNK / scan / CA put) is still in
// effect — `test_pact_entry_guard_silent_bail_until_max_lock` above
// covers that case.
#[tokio::test]
async fn test_reprocess_after_continuation_bypasses_pact_guard() {
    use epics_base_rs::server::record::{ProcessAction, ProcessOutcome, RecordProcessResult};
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU32, Ordering};

    struct ContinuationRecord {
        process_count: Arc<AtomicU32>,
    }

    impl Record for ContinuationRecord {
        fn record_type(&self) -> &'static str {
            "continuation_test"
        }
        fn process(&mut self) -> epics_base_rs::error::CaResult<ProcessOutcome> {
            let n = self.process_count.fetch_add(1, Ordering::SeqCst);
            if n == 0 {
                // First process: arm the timer-driven continuation.
                Ok(ProcessOutcome {
                    result: RecordProcessResult::AsyncPending,
                    actions: vec![ProcessAction::ReprocessAfter(
                        std::time::Duration::from_millis(20),
                    )],
                    device_did_compute: false,
                })
            } else {
                // Continuation reached: complete cleanly, clear PACT.
                Ok(ProcessOutcome::complete())
            }
        }
        fn get_field(&self, _name: &str) -> Option<EpicsValue> {
            None
        }
        fn put_field(
            &mut self,
            _name: &str,
            _value: EpicsValue,
        ) -> epics_base_rs::error::CaResult<()> {
            Ok(())
        }
        fn field_list(&self) -> &'static [FieldDesc] {
            &[]
        }
    }

    let process_count = Arc::new(AtomicU32::new(0));
    let db = PvDatabase::new();
    db.add_record(
        "CONT_REC",
        Box::new(ContinuationRecord {
            process_count: process_count.clone(),
        }),
    )
    .await
    .unwrap();

    // First process: returns AsyncPending + ReprocessAfter(20ms).
    let mut visited = HashSet::new();
    db.process_record_with_links("CONT_REC", &mut visited, 0)
        .await
        .unwrap();

    // PACT should be set immediately after AsyncPending returns.
    {
        let rec = db.get_record("CONT_REC").await.unwrap();
        assert!(
            rec.read().await.is_processing(),
            "PACT must be true after AsyncPending"
        );
    }
    assert_eq!(process_count.load(Ordering::SeqCst), 1);

    // A foreign caller during the wait must hit the entry guard (bail
    // silently) — proves the guard still protects against FLNK/scan
    // dual-fire while the continuation timer is pending.
    let mut visited = HashSet::new();
    db.process_record_with_links("CONT_REC", &mut visited, 0)
        .await
        .unwrap();
    assert_eq!(
        process_count.load(Ordering::SeqCst),
        1,
        "foreign re-entry during AsyncPending must NOT call process()"
    );

    // Wait for the ReprocessAfter timer to fire.
    tokio::time::sleep(std::time::Duration::from_millis(80)).await;

    // Continuation fired: process() ran a second time despite
    // pact=true.
    assert_eq!(
        process_count.load(Ordering::SeqCst),
        2,
        "ReprocessAfter timer must call process() again — owner-driven \
         continuation bypasses the PACT entry guard"
    );

    // BUG 1 regression — when the continuation's `process()` returns
    // `Complete` (not async-pending again), the `processing` flag set
    // on the original `AsyncPending` MUST be cleared. The continuation
    // path does NOT go through `complete_async_record`, so without an
    // explicit clear in `process_record_with_links_inner` the flag
    // stayed `true` forever. C parity: an async record's completion
    // re-entry clears `pact` inside `process()` (`aiRecord.c` second
    // pass). A leaked `processing=true` would make every later foreign
    // `process_record_with_links` trip the PACT entry guard.
    {
        let rec = db.get_record("CONT_REC").await.unwrap();
        assert!(
            !rec.read().await.is_processing(),
            "BUG 1: completed ReprocessAfter continuation must clear PACT"
        );
    }

    // A foreign caller after the continuation completed must actually
    // run `process()` again — proving the PACT entry guard no longer
    // fires (it would if `processing` had leaked true).
    let mut visited = HashSet::new();
    db.process_record_with_links("CONT_REC", &mut visited, 0)
        .await
        .unwrap();
    assert_eq!(
        process_count.load(Ordering::SeqCst),
        3,
        "BUG 1: after the continuation cleared PACT, a foreign process \
         must run process() again instead of bailing at the entry guard"
    );
}

// --- Monitor Mask tests ---

/// epics-base 3.15.7 — a server-side `dbnd` (deadband) filter
/// attached to a subscriber must drop sub-threshold value changes
/// while letting through deltas that cross the threshold. Mirrors
/// the per-subscription filter chain semantics that the JSON-name
/// parser (future commit) will wire in for real CA channels.
#[tokio::test]
async fn test_dbnd_filter_drops_subthreshold_changes() {
    use epics_base_rs::server::database::filters::DeadbandFilter;
    use epics_base_rs::server::recgbl::EventMask;
    use std::sync::Arc;

    let db = PvDatabase::new();
    db.add_record("DBND:REC", Box::new(AoRecord::new(10.0)))
        .await
        .unwrap();
    let rec = db.get_record("DBND:REC").await.unwrap();
    let mut rx = {
        let mut inst = rec.write().await;
        let rx = inst
            .add_subscriber(
                "VAL",
                1,
                epics_base_rs::types::DbFieldType::Double,
                EventMask::VALUE.bits(),
            )
            .expect("subscribe");
        let attached =
            inst.attach_filter_to_last_subscriber("VAL", Arc::new(DeadbandFilter::absolute(1.0)));
        assert!(attached, "filter must attach to the just-added subscriber");
        rx
    };

    // 11.0: first event always passes (no `last_sent` baseline yet).
    {
        let mut inst = rec.write().await;
        inst.record
            .put_field("VAL", EpicsValue::Double(11.0))
            .unwrap();
        inst.notify_field("VAL", EventMask::VALUE);
    }
    rx.try_recv()
        .expect("first value passes the deadband filter");

    // 11.4: |delta|=0.4 < 1.0 → silenced.
    {
        let mut inst = rec.write().await;
        inst.record
            .put_field("VAL", EpicsValue::Double(11.4))
            .unwrap();
        inst.notify_field("VAL", EventMask::VALUE);
    }
    assert!(
        rx.try_recv().is_err(),
        "sub-threshold change must be filtered out"
    );

    // 12.5: |delta|=1.1 >= 1.0 → passes.
    {
        let mut inst = rec.write().await;
        inst.record
            .put_field("VAL", EpicsValue::Double(12.5))
            .unwrap();
        inst.notify_field("VAL", EventMask::VALUE);
    }
    rx.try_recv().expect("above-threshold change passes");
}

/// epics-base 446e0d4a — value filters MUST pass alarm-only events
/// through regardless of the deadband state. Otherwise an alarm
/// triggered mid-deadband-window would be silenced and clients
/// would miss the state change.
#[tokio::test]
async fn test_dbnd_filter_passes_alarm_events() {
    use epics_base_rs::server::database::filters::DeadbandFilter;
    use epics_base_rs::server::recgbl::EventMask;
    use std::sync::Arc;

    let db = PvDatabase::new();
    db.add_record("DBND:ALR", Box::new(AoRecord::new(50.0)))
        .await
        .unwrap();
    let rec = db.get_record("DBND:ALR").await.unwrap();
    let mut rx = {
        let mut inst = rec.write().await;
        let rx = inst
            .add_subscriber(
                "VAL",
                1,
                epics_base_rs::types::DbFieldType::Double,
                (EventMask::VALUE | EventMask::ALARM).bits(),
            )
            .expect("subscribe");
        inst.attach_filter_to_last_subscriber("VAL", Arc::new(DeadbandFilter::absolute(10.0)));
        rx
    };

    // Seed the filter state with one value event.
    {
        let mut inst = rec.write().await;
        inst.record
            .put_field("VAL", EpicsValue::Double(50.0))
            .unwrap();
        inst.notify_field("VAL", EventMask::VALUE);
    }
    rx.try_recv().expect("seed value");

    // A 50.5 value-only update is silenced by the deadband (delta 0.5 < 10).
    {
        let mut inst = rec.write().await;
        inst.record
            .put_field("VAL", EpicsValue::Double(50.5))
            .unwrap();
        inst.notify_field("VAL", EventMask::VALUE);
    }
    assert!(rx.try_recv().is_err(), "sub-threshold value silenced");

    // But an ALARM-tagged emission with the SAME value MUST pass —
    // the filter's "always-pass alarm" rule.
    {
        let inst = rec.read().await;
        inst.notify_field("VAL", EventMask::ALARM);
    }
    rx.try_recv().expect("alarm event passes the filter");
}

#[tokio::test]
async fn test_notify_field_respects_mask() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(42.0)))
        .await
        .unwrap();
    let rec = db.get_record("REC").await.unwrap();
    let (mut value_rx, mut alarm_rx) = {
        let mut inst = rec.write().await;
        let value_rx = inst
            .add_subscriber(
                "VAL",
                1,
                epics_base_rs::types::DbFieldType::Double,
                EventMask::VALUE.bits(),
            )
            .expect("subscribe should not be capped at default");
        let alarm_rx = inst
            .add_subscriber(
                "VAL",
                2,
                epics_base_rs::types::DbFieldType::Double,
                EventMask::ALARM.bits(),
            )
            .expect("subscribe should not be capped at default");
        (value_rx, alarm_rx)
    };
    {
        let inst = rec.read().await;
        inst.notify_field("VAL", EventMask::VALUE);
    }
    assert!(value_rx.try_recv().is_ok());
    assert!(alarm_rx.try_recv().is_err());
}

/// C `dbAccess.c:575-577` clears `precord->rpro = FALSE; precord->putf =
/// FALSE` and arms `callNotifyCompletion = TRUE` BEFORE the alarm
/// check whenever SDIS evaluates to DISV. Pre-fix Rust only
/// reset nsta/nsev and updated the alarm — rpro/putf leaked into the
/// next cycle and pending dbNotify completion callbacks stalled.
#[tokio::test]
async fn test_sdis_disable_clears_rpro_and_putf() {
    let db = PvDatabase::new();
    db.add_record("DIS_SW", Box::new(AoRecord::new(1.0)))
        .await
        .unwrap();
    db.add_record("DIS_TGT", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("DIS_TGT").await {
        let mut inst = rec.write().await;
        inst.put_common_field("SDIS", EpicsValue::String("DIS_SW".into()))
            .unwrap();
        // Pre-set rpro=true, putf=true so the disable path's clear is
        // observable.
        inst.common.rpro = true;
        inst.common.putf = true;
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("DIS_TGT", &mut visited, 0)
        .await
        .unwrap();

    let rec = db.get_record("DIS_TGT").await.unwrap();
    let inst = rec.read().await;
    assert!(
        !inst.common.rpro,
        "SDIS disable must clear rpro (C dbAccess.c:575). Pre-fix this leaked."
    );
    assert!(
        !inst.common.putf,
        "SDIS disable must clear putf (C dbAccess.c:576). Pre-fix this leaked."
    );
}

/// C `dbAccess.c:622-623` runs `dbNotifyCompletion(precord)` at
/// `all_done` for the disable bail path because `callNotifyCompletion
/// = TRUE` was set at line 577. A CA WRITE_NOTIFY landing on a
/// disabled record must release its caller. Pre-fix the
/// put_notify_tx was never fired, stranding the call until socket
/// disconnect.
#[tokio::test]
async fn test_sdis_disable_fires_put_notify_completion() {
    let db = PvDatabase::new();
    db.add_record("DIS_NOT_SW", Box::new(AoRecord::new(1.0)))
        .await
        .unwrap();
    db.add_record("DIS_NOT_TGT", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("DIS_NOT_TGT").await {
        let mut inst = rec.write().await;
        inst.put_common_field("SDIS", EpicsValue::String("DIS_NOT_SW".into()))
            .unwrap();
    }

    // Arm a put-notify wait-set on the disabled target (pending=1 for the
    // originating record). The disable path must take it and `leave`,
    // draining the set to zero and firing the completion oneshot.
    let (tx, rx) = epics_base_rs::runtime::sync::oneshot::channel();
    {
        let rec = db.get_record("DIS_NOT_TGT").await.unwrap();
        let mut inst = rec.write().await;
        inst.notify = Some(NotifyWaitSet::new(tx));
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("DIS_NOT_TGT", &mut visited, 0)
        .await
        .unwrap();

    // rx should be ready — completion was sent via the disable bail.
    rx.await
        .expect("disable bail must fire put-notify completion (C dbAccess.c:622)");
    // membership must be taken (not left dangling for the next cycle).
    let rec = db.get_record("DIS_NOT_TGT").await.unwrap();
    assert!(
        rec.read().await.notify.is_none(),
        "put-notify wait-set membership must be cleared after firing"
    );
}

// ---------------------------------------------------------------------------
// Put-notify wait-set: CA WRITE_NOTIFY completion must wait for the WHOLE
// chain — the originating record AND every FLNK/OUT PP target it drives,
// synchronous or async — exactly like C `dbNotify.c` keeps every record in
// the `waitList` until `dbNotifyCompletion` drains it to empty. The four
// cases below are written per invariant boundary, not per narrative:
//   * no async member in the chain   → completes synchronously (Ok(None))
//   * async member reached via FLNK  → deferred (Ok(Some(rx)), fires later)
//   * async member reached via OUT PP→ deferred (same, other dispatch edge)
//   * second WRITE_NOTIFY in-flight  → refused (Ok→Err PutCallbackInProgress)
// ---------------------------------------------------------------------------

/// Boundary: a fully synchronous chain (originating record + a sync FLNK
/// target) drains the wait-set within the put call, so the put reports
/// immediate completion (`Ok(None)`) — no receiver is handed back.
#[tokio::test]
async fn test_put_notify_sync_chain_completes_immediately() {
    let db = PvDatabase::new();
    db.add_record("PN_SYNC_SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("PN_SYNC_TGT", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("PN_SYNC_SRC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("FLNK", EpicsValue::String("PN_SYNC_TGT".into()))
            .unwrap();
    }

    let result = db
        .put_record_field_from_ca("PN_SYNC_SRC", "VAL", EpicsValue::Double(3.0))
        .await
        .expect("put must succeed");
    assert!(
        result.is_none(),
        "a fully synchronous chain drains the wait-set in-call → Ok(None); \
         got a deferred receiver instead"
    );
}

/// Boundary (the finding): a synchronous originating record whose FLNK
/// target is async must DEFER completion. Pre-fix the originating record
/// fired its completion the instant its own sync cycle ended, reporting
/// WRITE_NOTIFY done while the async FLNK target was still in flight. Now
/// the put returns a receiver that fires only when the async target's
/// `complete_async_record` runs.
#[tokio::test]
async fn test_put_notify_defers_for_async_flnk_target() {
    let db = PvDatabase::new();
    db.add_record("PN_FLNK_SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("PN_FLNK_TGT", Box::new(AsyncRecord { val: 0.0 }))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("PN_FLNK_SRC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("FLNK", EpicsValue::String("PN_FLNK_TGT".into()))
            .unwrap();
    }

    let result = db
        .put_record_field_from_ca("PN_FLNK_SRC", "VAL", EpicsValue::Double(4.0))
        .await
        .expect("put must succeed");
    let mut rx = match result {
        Some(rx) => rx,
        None => panic!(
            "an async FLNK target must defer completion — \
             the put returned immediate (Ok(None)) instead of a receiver"
        ),
    };
    // The async FLNK target is in flight; completion MUST NOT have fired.
    assert!(
        matches!(
            rx.try_recv(),
            Err(epics_base_rs::runtime::sync::oneshot::error::TryRecvError::Empty)
        ),
        "completion fired while the async FLNK target was still pending \
         (the exact pre-fix defect)"
    );
    // Complete the async target — only now may the wait-set drain to zero.
    db.complete_async_record("PN_FLNK_TGT").await.unwrap();
    rx.await
        .expect("completion must fire once the async FLNK target completes");
}

/// Boundary: same deferral, reached through an OUT `PP` link instead of
/// FLNK — the other dispatch edge that calls `processTarget`/`dbNotifyAdd`.
#[tokio::test]
async fn test_put_notify_defers_for_async_out_pp_target() {
    let db = PvDatabase::new();
    db.add_record("PN_OUT_SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("PN_OUT_TGT", Box::new(AsyncRecord { val: 0.0 }))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("PN_OUT_SRC").await {
        let mut inst = rec.write().await;
        inst.put_common_field("OUT", EpicsValue::String("PN_OUT_TGT PP".into()))
            .unwrap();
    }

    let result = db
        .put_record_field_from_ca("PN_OUT_SRC", "VAL", EpicsValue::Double(5.0))
        .await
        .expect("put must succeed");
    let mut rx = match result {
        Some(rx) => rx,
        None => panic!(
            "an async OUT PP target must defer completion — \
             the put returned immediate (Ok(None)) instead of a receiver"
        ),
    };
    assert!(
        matches!(
            rx.try_recv(),
            Err(epics_base_rs::runtime::sync::oneshot::error::TryRecvError::Empty)
        ),
        "completion fired while the async OUT PP target was still pending"
    );
    db.complete_async_record("PN_OUT_TGT").await.unwrap();
    rx.await
        .expect("completion must fire once the async OUT PP target completes");
}

/// Boundary: a second WRITE_NOTIFY on a record whose put-notify is still
/// in flight is refused (C returns S_db_Blocked / ECA_PUTCBINPROG).
/// Silently overwriting the wait-set would drop the prior `Sender`, waking
/// the prior caller's receiver with a `RecvError` the CA dispatcher treats
/// as success.
#[tokio::test]
async fn test_put_notify_refuses_second_in_flight() {
    let db = PvDatabase::new();
    db.add_record("PN_DBL", Box::new(AsyncRecord { val: 0.0 }))
        .await
        .unwrap();

    // First put: the record goes async-pending and keeps its wait-set
    // membership for the duration of the device round trip.
    let first = db
        .put_record_field_from_ca("PN_DBL", "VAL", EpicsValue::Double(1.0))
        .await
        .expect("first put must succeed");
    assert!(
        first.is_some(),
        "async record's first put must return a deferred receiver"
    );

    // Second put while the first is still in flight → refused.
    let second = db
        .put_record_field_from_ca("PN_DBL", "VAL", EpicsValue::Double(2.0))
        .await;
    assert!(
        matches!(second, Err(CaError::PutCallbackInProgress(_))),
        "a second WRITE_NOTIFY on an in-flight record must be refused with \
         PutCallbackInProgress; got {second:?}"
    );
}

#[tokio::test]
async fn test_sdis_disable_notifies_alarm() {
    // C `dbAccess.c:587-592` — the disable branch of `dbProcess` posts:
    //   db_post_events(&precord->stat, DBE_VALUE);            // STAT
    //   db_post_events(&precord->sevr, DBE_VALUE);            // SEVR
    //   db_post_events(&precord->VAL,  DBE_VALUE|DBE_ALARM);  // value field
    // Only the *value field* carries DBE_ALARM; STAT/SEVR are posted
    // with DBE_VALUE alone. A DBE_ALARM subscriber must therefore be
    // attached to the value field (VAL) to observe the disable event —
    // a DBE_ALARM-only subscription on .STAT/.SEVR would NOT be
    // notified, matching C semantics.
    let db = PvDatabase::new();
    db.add_record("DISABLE_SW", Box::new(AoRecord::new(1.0)))
        .await
        .unwrap();
    db.add_record("TARGET", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("TARGET").await {
        let mut inst = rec.write().await;
        inst.put_common_field("SDIS", EpicsValue::String("DISABLE_SW".into()))
            .unwrap();
        inst.put_common_field("DISS", EpicsValue::Short(1)).unwrap();
    }
    let mut alarm_rx = {
        let rec = db.get_record("TARGET").await.unwrap();
        let mut inst = rec.write().await;
        // DBE_ALARM subscriber on the value field — C posts VAL with
        // DBE_VALUE|DBE_ALARM in the disable branch (dbAccess.c:590-592).
        inst.add_subscriber(
            "VAL",
            1,
            epics_base_rs::types::DbFieldType::Double,
            EventMask::ALARM.bits(),
        )
        .expect("subscribe should not be capped at default")
    };
    let mut visited = HashSet::new();
    db.process_record_with_links("TARGET", &mut visited, 0)
        .await
        .unwrap();
    assert!(alarm_rx.try_recv().is_ok());
}

// --- UDF in database context ---

#[tokio::test]
async fn test_udf_cleared_by_process_with_links() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let rec = db.get_record("REC").await.unwrap();
    assert!(rec.read().await.common.udf);
    let mut visited = HashSet::new();
    db.process_record_with_links("REC", &mut visited, 0)
        .await
        .unwrap();
    assert!(!rec.read().await.common.udf);
}

#[tokio::test]
async fn test_udf_not_cleared_by_clears_udf_false() {
    struct NoClearRecord {
        val: f64,
    }
    impl Record for NoClearRecord {
        fn record_type(&self) -> &'static str {
            "noclear"
        }
        fn get_field(&self, name: &str) -> Option<EpicsValue> {
            match name {
                "VAL" => Some(EpicsValue::Double(self.val)),
                _ => None,
            }
        }
        fn put_field(
            &mut self,
            name: &str,
            value: EpicsValue,
        ) -> epics_base_rs::error::CaResult<()> {
            match name {
                "VAL" => {
                    if let EpicsValue::Double(v) = value {
                        self.val = v;
                        Ok(())
                    } else {
                        Err(CaError::InvalidValue("bad".into()))
                    }
                }
                _ => Err(CaError::FieldNotFound(name.into())),
            }
        }
        fn field_list(&self) -> &'static [FieldDesc] {
            &[]
        }
        fn clears_udf(&self) -> bool {
            false
        }
    }

    let db = PvDatabase::new();
    db.add_record("REC", Box::new(NoClearRecord { val: 0.0 }))
        .await
        .unwrap();
    let rec = db.get_record("REC").await.unwrap();
    assert!(rec.read().await.common.udf);
    let mut visited = HashSet::new();
    db.process_record_with_links("REC", &mut visited, 0)
        .await
        .unwrap();
    assert!(rec.read().await.common.udf);
}

#[tokio::test]
async fn test_constant_inp_link() {
    let db = PvDatabase::new();
    db.add_record("AI_CONST", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("AI_CONST").await {
        let mut inst = rec.write().await;
        inst.put_common_field("INP", EpicsValue::String("3.15".into()))
            .unwrap();
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("AI_CONST", &mut visited, 0)
        .await
        .unwrap();
    let val = db.get_pv("AI_CONST").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 3.15).abs() < 1e-10),
        other => panic!("expected Double(3.15), got {:?}", other),
    }
}

#[tokio::test]
async fn test_calc_multi_input_db_links() {
    use epics_base_rs::server::records::calc::CalcRecord;
    let db = PvDatabase::new();
    db.add_record("SRC_A", Box::new(AoRecord::new(10.0)))
        .await
        .unwrap();
    db.add_record("SRC_B", Box::new(AoRecord::new(20.0)))
        .await
        .unwrap();
    let mut calc = CalcRecord::new("A+B");
    calc.inpa = "SRC_A".to_string();
    calc.inpb = "SRC_B".to_string();
    db.add_record("CALC_REC", Box::new(calc)).await.unwrap();
    let mut visited = HashSet::new();
    db.process_record_with_links("CALC_REC", &mut visited, 0)
        .await
        .unwrap();
    let val = db.get_pv("CALC_REC").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 30.0).abs() < 1e-10),
        other => panic!("expected Double(30.0), got {:?}", other),
    }
}

/// Defect 3 regression: a `ProcessPassive` (PP) multi-input link
/// (`INPA..INPL` for calc/sel/sub/aSub) must process its passive
/// source record BEFORE the value is read — C `dbGetLink` behaviour.
/// Before the fix the multi-input fetch loop used `read_link_with_alarm`
/// (bare `get_pv`, no PP processing), so a PP input link read a stale
/// source value. The single-INP path already did this via
/// `read_link_value_soft`.
#[tokio::test]
async fn test_calc_multi_input_pp_processes_passive_source() {
    use epics_base_rs::server::records::calc::CalcRecord;

    let db = PvDatabase::new();

    // SRC: a passive calc whose VAL computes to 42 only when processed.
    // Its stored VAL starts at the default 0.0.
    let src = CalcRecord::new("42");
    db.add_record("PP_SRC", Box::new(src)).await.unwrap();

    // DST: INPA = "PP_SRC PP" (process-passive). CALC="A" copies INPA.
    let mut dst = CalcRecord::new("A");
    dst.inpa = "PP_SRC PP".to_string();
    db.add_record("PP_DST", Box::new(dst)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("PP_DST", &mut visited, 0)
        .await
        .unwrap();

    // DST must see 42: the PP link processed PP_SRC first, computing
    // its VAL=42 before the value was read. A stale read would yield 0.
    let val = db.get_pv("PP_DST").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!(
            (v - 42.0).abs() < 1e-10,
            "PP multi-input link must process source first: expected 42, got {v}"
        ),
        other => panic!("expected Double(42.0), got {other:?}"),
    }
    // The source itself must have been processed (VAL latched to 42).
    let src_val = db.get_pv("PP_SRC").await.unwrap();
    match src_val {
        EpicsValue::Double(v) => assert!(
            (v - 42.0).abs() < 1e-10,
            "PP_SRC must have been processed by the PP link, VAL={v}"
        ),
        other => panic!("expected Double(42.0), got {other:?}"),
    }
}

/// Defect 3 control: an `NPP` (no-process-passive) multi-input link
/// must NOT process its passive source — it reads whatever stale
/// value the source currently holds.
#[tokio::test]
async fn test_calc_multi_input_npp_does_not_process_source() {
    use epics_base_rs::server::records::calc::CalcRecord;

    let db = PvDatabase::new();

    let src = CalcRecord::new("42");
    db.add_record("NPP_SRC", Box::new(src)).await.unwrap();

    let mut dst = CalcRecord::new("A");
    dst.inpa = "NPP_SRC NPP".to_string();
    db.add_record("NPP_DST", Box::new(dst)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("NPP_DST", &mut visited, 0)
        .await
        .unwrap();

    // NPP_SRC was never processed, so its VAL stays at the default 0.0
    // and DST reads 0, not 42.
    let val = db.get_pv("NPP_DST").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!(
            v.abs() < 1e-10,
            "NPP multi-input link must NOT process source: expected 0, got {v}"
        ),
        other => panic!("expected Double(0.0), got {other:?}"),
    }
}

/// A **modifier-less** (bare) multi-input link must behave like NPP —
/// C `dbParseLink` (`dbStaticLib.c:2252,2369-2371`) leaves `pvlOptPP`
/// unset for a bare link, so `dbDbGetValue` (`dbDbLink.c:175`) does NOT
/// process the passive source on read. Before the fix `parse_link_v2`
/// defaulted a bare link to `ProcessPassive`, so `BARE_DST` would have
/// spuriously processed `BARE_SRC` and read 42; after the fix it reads
/// the stale 0.
#[tokio::test]
async fn test_calc_multi_input_bare_does_not_process_source() {
    use epics_base_rs::server::records::calc::CalcRecord;

    let db = PvDatabase::new();

    let src = CalcRecord::new("42");
    db.add_record("BARE_SRC", Box::new(src)).await.unwrap();

    let mut dst = CalcRecord::new("A");
    // No modifier — must default to NPP, NOT ProcessPassive.
    dst.inpa = "BARE_SRC".to_string();
    db.add_record("BARE_DST", Box::new(dst)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("BARE_DST", &mut visited, 0)
        .await
        .unwrap();

    let val = db.get_pv("BARE_DST").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!(
            v.abs() < 1e-10,
            "bare multi-input link is NPP and must NOT process its source: expected 0, got {v}"
        ),
        other => panic!("expected Double(0.0), got {other:?}"),
    }
    // BARE_SRC must still hold its unprocessed default.
    let src_val = db.get_pv("BARE_SRC").await.unwrap();
    match src_val {
        EpicsValue::Double(v) => assert!(
            v.abs() < 1e-10,
            "bare INP must leave BARE_SRC unprocessed, VAL={v}"
        ),
        other => panic!("expected Double(0.0), got {other:?}"),
    }
}

/// Defect 1 regression (CRITICAL): two passive calc records whose
/// `INPA` PP links point at each other (`A.INPA="B PP"`,
/// `B.INPA="A PP"`) form a PP-link cycle. Before the fix
/// `process_passive_db_source` created a FRESH `visited` set and
/// reset depth to 0 on every PP hop, so neither `MAX_LINK_DEPTH`
/// nor the `visited` cycle guard fired across the hop — the cycle
/// recursed unboundedly to a stack overflow / SIGABRT.
///
/// C terminates this cycle because `calcRecord.c::process` sets
/// `prec->pact = TRUE` *before* `fetch_values()` (calcRecord.c:119),
/// so the re-entrant `dbProcess` hits `if (precord->pact) goto
/// all_done;` (dbAccess.c:537) and bails after one bounce. The Rust
/// fix threads the caller's `visited` set / `depth` through the PP
/// hop so the existing `visited.insert` guard
/// (`process_record_with_links_inner`) fires instead.
///
/// This test passing at all proves the fix: a regression re-aborts
/// the whole test process with a stack overflow.
#[tokio::test]
async fn test_calc_pp_link_cycle_terminates() {
    use epics_base_rs::server::records::calc::CalcRecord;

    let db = PvDatabase::new();

    // CALC_A.INPA = "CALC_B PP", CALC_B.INPA = "CALC_A PP".
    // Both passive, both CALC="A" (copy the input).
    let mut a = CalcRecord::new("A");
    a.inpa = "CALC_B PP".to_string();
    db.add_record("CALC_A", Box::new(a)).await.unwrap();

    let mut b = CalcRecord::new("A");
    b.inpa = "CALC_A PP".to_string();
    db.add_record("CALC_B", Box::new(b)).await.unwrap();

    // Must return cleanly (Ok) without overflowing the stack — the
    // cycle guard terminates the A->B->A bounce.
    let mut visited = HashSet::new();
    let result = db
        .process_record_with_links("CALC_A", &mut visited, 0)
        .await;
    assert!(
        result.is_ok(),
        "PP-link A<->B cycle must terminate cleanly, got {result:?}"
    );

    // Both records read a finite value (default 0.0 — neither has a
    // real source). The point is that processing completed at all.
    let va = db.get_pv("CALC_A").await.unwrap();
    let vb = db.get_pv("CALC_B").await.unwrap();
    match (va, vb) {
        (EpicsValue::Double(x), EpicsValue::Double(y)) => {
            assert!(
                x.is_finite() && y.is_finite(),
                "cycle must leave finite values, got A={x} B={y}"
            );
        }
        other => panic!("expected Double values, got {other:?}"),
    }
}

#[tokio::test]
async fn test_calc_constant_inputs() {
    use epics_base_rs::server::records::calc::CalcRecord;
    let db = PvDatabase::new();
    let mut calc = CalcRecord::new("A+B");
    calc.inpa = "5".to_string();
    calc.inpb = "3.5".to_string();
    db.add_record("CALC_CONST", Box::new(calc)).await.unwrap();
    let mut visited = HashSet::new();
    db.process_record_with_links("CALC_CONST", &mut visited, 0)
        .await
        .unwrap();
    let val = db.get_pv("CALC_CONST").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 8.5).abs() < 1e-10),
        other => panic!("expected Double(8.5), got {:?}", other),
    }
}

// C parity (calcRecord.dbd.pod:716-744): calc record carries the same
// HIHI/HIGH/LOW/LOLO/HHSV/HSV/LSV/LLSV alarm-limit fields as
// ai/ao/longin/longout. The Rust port omitted them — put_field for
// HIHI silently no-op'd because `common.analog_alarm` was None for
// rtype="calc".
#[tokio::test]
async fn test_calc_record_has_analog_alarm_limits() {
    use epics_base_rs::server::records::calc::CalcRecord;

    let db = PvDatabase::new();
    let mut calc = CalcRecord::new("A");
    calc.inpa = "15".to_string(); // VAL will compute to 15
    db.add_record("CALC_LIM", Box::new(calc)).await.unwrap();

    // Configure HIHI=10, HHSV=MAJOR. Put goes through put_record_field_from_ca
    // which routes to common.analog_alarm.
    db.put_record_field_from_ca("CALC_LIM", "HIHI", EpicsValue::Double(10.0))
        .await
        .unwrap();
    db.put_record_field_from_ca("CALC_LIM", "HHSV", EpicsValue::String("MAJOR".into()))
        .await
        .unwrap();

    // Read back — verifies the put landed in common.analog_alarm.
    let hihi = {
        let rec = db.get_record("CALC_LIM").await.unwrap();
        let inst = rec.read().await;
        inst.resolve_field("HIHI").and_then(|v| v.to_f64()).unwrap()
    };
    assert_eq!(hihi, 10.0);

    // Process — CALC="A" with A=15 → VAL=15 > HIHI=10 → HIHI_ALARM/MAJOR.
    let mut visited = HashSet::new();
    db.process_record_with_links("CALC_LIM", &mut visited, 0)
        .await
        .unwrap();
    let rec = db.get_record("CALC_LIM").await.unwrap();
    let inst = rec.read().await;
    assert_eq!(
        inst.common.sevr,
        epics_base_rs::server::record::AlarmSeverity::Major,
        "VAL=15, HIHI=10, HHSV=MAJOR — must raise HIHI alarm",
    );
    assert_eq!(
        inst.common.stat,
        epics_base_rs::server::recgbl::alarm_status::HIHI_ALARM,
    );
}

// C parity (calcRecord.c::checkAlarms:339-381): with AFTC > 0 the
// alarm-range integer is exponentially smoothed, so a brief excursion
// above HIHI does NOT immediately raise the severity until the filter
// converges.
#[tokio::test]
async fn test_calc_record_aftc_filter_delays_alarm() {
    use epics_base_rs::server::records::calc::CalcRecord;

    let db = PvDatabase::new();
    let mut calc = CalcRecord::new("A");
    calc.inpa = "1".to_string();
    calc.aftc = 5.0; // 5-second filter time-constant
    db.add_record("CALC_AFTC", Box::new(calc)).await.unwrap();
    db.put_record_field_from_ca("CALC_AFTC", "HIHI", EpicsValue::Double(10.0))
        .await
        .unwrap();
    db.put_record_field_from_ca("CALC_AFTC", "HHSV", EpicsValue::String("MAJOR".into()))
        .await
        .unwrap();

    // First process — filter seeds with NoAlarm (alarm_range=3, Normal).
    let mut visited = HashSet::new();
    db.process_record_with_links("CALC_AFTC", &mut visited, 0)
        .await
        .unwrap();

    // Set VAL=15 (HIHI condition) and process. With aftc=5s and dt
    // very small (sub-second between processes), alpha=5/(eps+5)≈1.0,
    // and filtered_range stays at 3 (Normal). The new alarm range (5)
    // must be smoothed out by the filter — alarm must NOT fire on the
    // first transition.
    let rec = db.get_record("CALC_AFTC").await.unwrap();
    {
        let mut inst = rec.write().await;
        let _ = inst.record.put_field("VAL", EpicsValue::Double(15.0));
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("CALC_AFTC", &mut visited, 0)
        .await
        .unwrap();
    let inst = rec.read().await;
    // afvl must have been updated (filter is engaged)
    let afvl = inst
        .record
        .get_field("AFVL")
        .and_then(|v| v.to_f64())
        .unwrap_or(0.0);
    assert!(afvl != 0.0, "AFVL must be updated when AFTC > 0");
}

#[tokio::test]
async fn test_fanout_all() {
    use epics_base_rs::server::records::fanout::FanoutRecord;
    let db = PvDatabase::new();
    let mut fanout = FanoutRecord::new();
    fanout.selm = 0;
    fanout.lnk1 = "TARGET_1".to_string();
    fanout.lnk2 = "TARGET_2".to_string();
    db.add_record("FANOUT", Box::new(fanout)).await.unwrap();
    db.add_record("TARGET_1", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("TARGET_2", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let mut visited = HashSet::new();
    db.process_record_with_links("FANOUT", &mut visited, 0)
        .await
        .unwrap();
    assert!(visited.contains("FANOUT"));
    assert!(visited.contains("TARGET_1"));
    assert!(visited.contains("TARGET_2"));
}

#[tokio::test]
async fn test_fanout_specified() {
    // C parity (fanoutRecord.c:114): SELM=Specified selects the link
    // at index `SELN + OFFS`, 0-based over LNK0..LNKF. With SELN=1,
    // OFFS=0 the selected link is LNK1 (NOT LNK2 — the pre-fix port
    // omitted LNK0 and was off by one).
    use epics_base_rs::server::records::fanout::FanoutRecord;
    let db = PvDatabase::new();
    let mut fanout = FanoutRecord::new();
    fanout.selm = 1;
    fanout.seln = 1;
    db.add_record("FANOUT", Box::new(fanout)).await.unwrap();
    db.add_record("T1", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("T2", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("FANOUT").await {
        let mut inst = rec.write().await;
        inst.record
            .put_field("LNK1", EpicsValue::String("T1".into()))
            .unwrap();
        inst.record
            .put_field("LNK2", EpicsValue::String("T2".into()))
            .unwrap();
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("FANOUT", &mut visited, 0)
        .await
        .unwrap();
    assert!(visited.contains("FANOUT"));
    // SELN=1 → LNK1 → T1 processed; LNK2/T2 NOT processed.
    assert!(visited.contains("T1"));
    assert!(!visited.contains("T2"));
}

#[tokio::test]
async fn test_dfanout_value_write() {
    use epics_base_rs::server::records::dfanout::DfanoutRecord;
    let db = PvDatabase::new();
    let mut dfan = DfanoutRecord::new(42.0);
    dfan.selm = 0;
    dfan.outa = "DEST_A".to_string();
    dfan.outb = "DEST_B".to_string();
    db.add_record("DFAN", Box::new(dfan)).await.unwrap();
    db.add_record("DEST_A", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("DEST_B", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let mut visited = HashSet::new();
    db.process_record_with_links("DFAN", &mut visited, 0)
        .await
        .unwrap();
    let val_a = db.get_pv("DEST_A").await.unwrap();
    match val_a {
        EpicsValue::Double(v) => assert!((v - 42.0).abs() < 1e-10),
        other => panic!("expected Double(42.0), got {:?}", other),
    }
    let val_b = db.get_pv("DEST_B").await.unwrap();
    match val_b {
        EpicsValue::Double(v) => assert!((v - 42.0).abs() < 1e-10),
        other => panic!("expected Double(42.0), got {:?}", other),
    }
}

/// C `dfanoutRecord.c:115-122` reads VAL from DOL on every process
/// cycle when `omsl == menuOmslclosed_loop`. The Rust port previously
/// omitted dfanout from the DOL-eligible record-type list in
/// `processing.rs::process_record_with_links_inner`, so a dfanout
/// configured with OMSL=closed_loop never sourced VAL from DOL —
/// every cycle silently kept the previously-cached VAL.
#[tokio::test]
async fn test_dfanout_omsl_closed_loop_sources_val_from_dol() {
    use epics_base_rs::server::records::dfanout::DfanoutRecord;

    let db = PvDatabase::new();

    // Upstream setpoint source.
    db.add_record("DOL_SRC", Box::new(AoRecord::new(7.5)))
        .await
        .unwrap();

    // dfanout with OMSL=closed_loop and DOL=DOL_SRC. SELM=0 (All)
    // distributes VAL to OUTA + OUTB.
    let mut dfan = DfanoutRecord::new(0.0);
    dfan.selm = 0;
    dfan.outa = "DFAN_DEST_A".to_string();
    dfan.outb = "DFAN_DEST_B".to_string();
    dfan.dol = "DOL_SRC".to_string();
    dfan.omsl = 1; // closed_loop (menuOmslclosed_loop)
    db.add_record("DFAN_OMSL", Box::new(dfan)).await.unwrap();

    db.add_record("DFAN_DEST_A", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("DFAN_DEST_B", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("DFAN_OMSL", &mut visited, 0)
        .await
        .unwrap();

    // DOL_SRC's VAL (7.5) must have flowed through DOL → dfanout.VAL → OUTA/OUTB.
    let val_a = db.get_pv("DFAN_DEST_A").await.unwrap();
    assert!(
        matches!(val_a, EpicsValue::Double(v) if (v - 7.5).abs() < 1e-10),
        "DFAN_DEST_A must reflect DOL_SRC (=7.5), got {val_a:?}"
    );
    let val_b = db.get_pv("DFAN_DEST_B").await.unwrap();
    assert!(
        matches!(val_b, EpicsValue::Double(v) if (v - 7.5).abs() < 1e-10),
        "DFAN_DEST_B must reflect DOL_SRC (=7.5), got {val_b:?}"
    );
}

/// Companion to the OMSL=closed_loop test: with OMSL=supervisory
/// (default), DOL must NOT be evaluated even if a DOL link is set —
/// VAL remains under operator control. This pins the gating so a
/// future refactor cannot silently widen the closed-loop scope.
#[tokio::test]
async fn test_dfanout_omsl_supervisory_ignores_dol() {
    use epics_base_rs::server::records::dfanout::DfanoutRecord;

    let db = PvDatabase::new();
    db.add_record("DOL_SRC2", Box::new(AoRecord::new(99.0)))
        .await
        .unwrap();

    let mut dfan = DfanoutRecord::new(3.0);
    dfan.selm = 0;
    dfan.outa = "DFAN_DEST_A2".to_string();
    dfan.dol = "DOL_SRC2".to_string();
    dfan.omsl = 0; // supervisory (menuOmslsupervisory)
    db.add_record("DFAN_SUP", Box::new(dfan)).await.unwrap();
    db.add_record("DFAN_DEST_A2", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("DFAN_SUP", &mut visited, 0)
        .await
        .unwrap();

    let val_a = db.get_pv("DFAN_DEST_A2").await.unwrap();
    assert!(
        matches!(val_a, EpicsValue::Double(v) if (v - 3.0).abs() < 1e-10),
        "OMSL=supervisory must keep the operator-staged VAL (=3.0), got {val_a:?}"
    );
}

#[tokio::test]
async fn test_seq_dol_lnk_dispatch() {
    use epics_base_rs::server::records::seq::SeqRecord;
    let db = PvDatabase::new();
    db.add_record("SEQ_SRC1", Box::new(AoRecord::new(100.0)))
        .await
        .unwrap();
    db.add_record("SEQ_SRC2", Box::new(AoRecord::new(200.0)))
        .await
        .unwrap();
    db.add_record("SEQ_DEST1", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("SEQ_DEST2", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let mut seq = SeqRecord::new();
    seq.selm = 0;
    seq.dol1 = "SEQ_SRC1".to_string();
    seq.lnk1 = "SEQ_DEST1".to_string();
    seq.dol2 = "SEQ_SRC2".to_string();
    seq.lnk2 = "SEQ_DEST2".to_string();
    db.add_record("SEQ_REC", Box::new(seq)).await.unwrap();
    let mut visited = HashSet::new();
    db.process_record_with_links("SEQ_REC", &mut visited, 0)
        .await
        .unwrap();
    let val1 = db.get_pv("SEQ_DEST1").await.unwrap();
    match val1 {
        EpicsValue::Double(v) => assert!((v - 100.0).abs() < 1e-10),
        other => panic!("expected Double(100.0), got {:?}", other),
    }
    let val2 = db.get_pv("SEQ_DEST2").await.unwrap();
    match val2 {
        EpicsValue::Double(v) => assert!((v - 200.0).abs() < 1e-10),
        other => panic!("expected Double(200.0), got {:?}", other),
    }
}

// A process-counting target. `process()` bumps the shared counter so a
// test can prove whether a link DID or DID NOT process its target.
struct CountingTarget {
    process_count: Arc<AtomicU32>,
}

impl Record for CountingTarget {
    fn record_type(&self) -> &'static str {
        "counting_target"
    }
    fn process(&mut self) -> epics_base_rs::error::CaResult<ProcessOutcome> {
        self.process_count.fetch_add(1, Ordering::SeqCst);
        Ok(ProcessOutcome::complete())
    }
    fn get_field(&self, _name: &str) -> Option<EpicsValue> {
        None
    }
    fn put_field(&mut self, _name: &str, _value: EpicsValue) -> epics_base_rs::error::CaResult<()> {
        Ok(())
    }
    fn field_list(&self) -> &'static [FieldDesc] {
        &[]
    }
}

// BUG 1 regression — seq `LNKn` is `DBF_OUTLINK` (`seqRecord.dbd.pod:316`)
// driven via `dbPutLink` (`seqRecord.c:264`). `dbDbPutValue`
// (`dbDbLink.c:388`) processes the target only when the link carries an
// explicit `PP` modifier. A bare (modifier-less) seq LNKn is NPP — the
// target value is written but the target is NOT processed.
// `parse_link_v2`/`parse_output_link_v2` default a modifier-less link
// to NPP (`NoProcess`) like C `dbParseLink`, so the `MultiOut::Seq` arm
// needs no per-call downgrade.
#[tokio::test]
async fn test_seq_bare_lnk_does_not_process_passive_target() {
    use epics_base_rs::server::records::seq::SeqRecord;
    let db = PvDatabase::new();

    let bare_count = Arc::new(AtomicU32::new(0));
    let pp_count = Arc::new(AtomicU32::new(0));
    db.add_record(
        "SEQ_BARE_TGT",
        Box::new(CountingTarget {
            process_count: bare_count.clone(),
        }),
    )
    .await
    .unwrap();
    db.add_record(
        "SEQ_PP_TGT",
        Box::new(CountingTarget {
            process_count: pp_count.clone(),
        }),
    )
    .await
    .unwrap();

    let mut seq = SeqRecord::new();
    seq.selm = 0;
    // Group 1: bare LNK — must NOT process the Passive target.
    seq.do1 = 11.0;
    seq.lnk1 = "SEQ_BARE_TGT".to_string();
    // Group 2: explicit PP LNK — must process the Passive target.
    seq.do2 = 22.0;
    seq.lnk2 = "SEQ_PP_TGT PP".to_string();
    db.add_record("SEQ_NPP_REC", Box::new(seq)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("SEQ_NPP_REC", &mut visited, 0)
        .await
        .unwrap();

    assert_eq!(
        bare_count.load(Ordering::SeqCst),
        0,
        "bare seq LNKn (NPP) must NOT process its Passive target"
    );
    assert_eq!(
        pp_count.load(Ordering::SeqCst),
        1,
        "explicit-PP seq LNKn must process its Passive target"
    );
}

// R0604 regression — a record's `WriteDbLink` OUT write must land BEFORE
// the producing record's FLNK fires. C record support performs
// `dbPutLink()` for OUT links before `recGblFwdLink()`
// (transformRecord.c:608-619, scalerRecord.c:457-480), so a downstream
// FLNK target that reads the written PV observes the new value. Pre-fix
// the framework ran the FLNK tail first, leaving the target stale.
struct WriteThenFlnkProducer;
impl Record for WriteThenFlnkProducer {
    fn record_type(&self) -> &'static str {
        "write_flnk_producer"
    }
    fn process(&mut self) -> epics_base_rs::error::CaResult<ProcessOutcome> {
        Ok(ProcessOutcome::complete_with(vec![
            ProcessAction::WriteDbLink {
                link_field: "OUT",
                value: EpicsValue::Double(42.0),
            },
        ]))
    }
    fn get_field(&self, name: &str) -> Option<EpicsValue> {
        match name {
            "OUT" => Some(EpicsValue::String("WF_TARGET".into())),
            _ => None,
        }
    }
    fn put_field(&mut self, _name: &str, _value: EpicsValue) -> epics_base_rs::error::CaResult<()> {
        Ok(())
    }
    fn field_list(&self) -> &'static [FieldDesc] {
        &[]
    }
}

#[tokio::test]
async fn test_write_db_link_runs_before_flnk_target_reads_fresh() {
    let db = PvDatabase::new();
    // Target the producer writes 42.0 into.
    db.add_record("WF_TARGET", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    // FLNK observer reads WF_TARGET via its INP during its own process.
    db.add_record("WF_OBSERVER", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("WF_OBSERVER").await {
        let mut inst = rec.write().await;
        inst.put_common_field("INP", EpicsValue::String("WF_TARGET".into()))
            .unwrap();
    }
    // Producer: WriteDbLink → WF_TARGET, FLNK → WF_OBSERVER.
    db.add_record("WF_PRODUCER", Box::new(WriteThenFlnkProducer))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("WF_PRODUCER").await {
        let mut inst = rec.write().await;
        inst.put_common_field("FLNK", EpicsValue::String("WF_OBSERVER".into()))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("WF_PRODUCER", &mut visited, 0)
        .await
        .unwrap();

    // The OUT write ran before FLNK, so the observer read the fresh 42.0.
    let observed = db.get_pv("WF_OBSERVER").await.unwrap();
    match observed {
        EpicsValue::Double(v) => assert!(
            (v - 42.0).abs() < 1e-10,
            "FLNK observer must read the post-WriteDbLink value 42.0, got {v}"
        ),
        other => panic!("expected Double(42.0), got {other:?}"),
    }
}

/// Poll an atomic counter until it reaches `want`, then settle so any
/// erroneous extra effect would also have landed. The sseq machine
/// completes via spawned per-step re-entries, so the kicking call returns
/// before the later steps' `LNKn` writes happen.
async fn poll_atomic_reaches(label: &str, counter: &Arc<AtomicU32>, want: u32) {
    for _ in 0..400 {
        if counter.load(Ordering::SeqCst) >= want {
            tokio::time::sleep(std::time::Duration::from_millis(30)).await;
            return;
        }
        tokio::time::sleep(std::time::Duration::from_millis(5)).await;
    }
    panic!(
        "{label}: counter reached {} (< {want}) before timeout",
        counter.load(Ordering::SeqCst)
    );
}

/// Poll a PV until it equals `want`, with a timeout. Used to wait out the
/// sseq machine's per-step `DLYn` delays + async re-entries.
async fn poll_pv_double(db: &PvDatabase, pv: &str, want: f64) {
    for _ in 0..400 {
        if let Ok(EpicsValue::Double(v)) = db.get_pv(pv).await {
            if (v - want).abs() < 1e-10 {
                return;
            }
        }
        tokio::time::sleep(std::time::Duration::from_millis(5)).await;
    }
    panic!(
        "{pv}: did not reach {want} before timeout (last {:?})",
        db.get_pv(pv).await
    );
}

// BUG 1 regression — sseq `LNKn` is `DBF_OUTLINK` driven via `dbPutLink`
// → `dbDbPutValue` (`dbDbLink.c:388`). A bare sseq LNKn is NPP and must
// not process its target; an explicit-PP LNKn must.
#[tokio::test]
async fn test_sseq_bare_lnk_does_not_process_passive_target() {
    use epics_base_rs::server::records::sseq::SseqRecord;
    let db = PvDatabase::new();

    let bare_count = Arc::new(AtomicU32::new(0));
    let pp_count = Arc::new(AtomicU32::new(0));
    db.add_record(
        "SSEQ_BARE_TGT",
        Box::new(CountingTarget {
            process_count: bare_count.clone(),
        }),
    )
    .await
    .unwrap();
    db.add_record(
        "SSEQ_PP_TGT",
        Box::new(CountingTarget {
            process_count: pp_count.clone(),
        }),
    )
    .await
    .unwrap();

    let mut sseq = SseqRecord::new();
    sseq.selm = 0;
    // Step 1: bare LNK — must NOT process the Passive target.
    sseq.put_field("DO1", EpicsValue::Double(11.0)).unwrap();
    sseq.put_field("LNK1", EpicsValue::String("SSEQ_BARE_TGT".into()))
        .unwrap();
    // Step 2: explicit PP LNK — must process the Passive target.
    sseq.put_field("DO2", EpicsValue::Double(22.0)).unwrap();
    sseq.put_field("LNK2", EpicsValue::String("SSEQ_PP_TGT PP".into()))
        .unwrap();
    db.add_record("SSEQ_NPP_REC", Box::new(sseq)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("SSEQ_NPP_REC", &mut visited, 0)
        .await
        .unwrap();
    // Step 2 (the PP target) is written in a later continuation; wait for
    // it, then the settle window lets a stray bare-target process land too.
    poll_atomic_reaches("sseq PP step", &pp_count, 1).await;

    assert_eq!(
        bare_count.load(Ordering::SeqCst),
        0,
        "bare sseq LNKn (NPP) must NOT process its Passive target"
    );
    assert_eq!(
        pp_count.load(Ordering::SeqCst),
        1,
        "explicit-PP sseq LNKn must process its Passive target"
    );
}

// sseq per-step DLYn regression — C `sseqRecord.c::processNextLink`
// schedules each selected step's LNKn write after its DLYn delay
// (`callbackRequestDelayed`), exactly as the base `seqRecord` does for
// DLY0..DLYF. The async machine ports this with a per-step
// `ReprocessAfter(DLYn)`.
#[tokio::test]
async fn test_sseq_per_step_dly_delays_step_write() {
    use epics_base_rs::server::records::sseq::SseqRecord;
    let db = PvDatabase::new();

    // Two Passive targets driven by explicit-PP LNKn so they accept
    // the written value. Step 1 carries a 0.3 s DLY1, step 2 has no
    // delay.
    db.add_record("SSEQ_DLY_TGT1", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("SSEQ_DLY_TGT2", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    let mut sseq = SseqRecord::new();
    sseq.selm = 0; // All steps selected.
    // Step 1: delayed write.
    sseq.put_field("DLY1", EpicsValue::Double(0.3)).unwrap();
    sseq.put_field("DO1", EpicsValue::Double(11.0)).unwrap();
    sseq.put_field("LNK1", EpicsValue::String("SSEQ_DLY_TGT1 PP".into()))
        .unwrap();
    // Step 2: no delay (but dispatched only after step 1 completes).
    sseq.put_field("DLY2", EpicsValue::Double(0.0)).unwrap();
    sseq.put_field("DO2", EpicsValue::Double(22.0)).unwrap();
    sseq.put_field("LNK2", EpicsValue::String("SSEQ_DLY_TGT2 PP".into()))
        .unwrap();
    db.add_record("SSEQ_DLY_REC", Box::new(sseq)).await.unwrap();

    // Kick the sequence. The async machine returns to the caller after the
    // first step is *scheduled* (PACT set); the per-step writes happen in
    // spawned re-entries, so the kick does NOT block until completion.
    let mut visited = HashSet::new();
    db.process_record_with_links("SSEQ_DLY_REC", &mut visited, 0)
        .await
        .unwrap();

    // Before DLY1 (0.3 s) elapses, step 1's value must NOT be written yet,
    // and step 2 must not fire before step 1.
    tokio::time::sleep(std::time::Duration::from_millis(100)).await;
    assert_eq!(
        db.get_pv("SSEQ_DLY_TGT1").await.unwrap(),
        EpicsValue::Double(0.0),
        "step 1 LNKn must not fire before its DLY1 delay elapses"
    );
    assert_eq!(
        db.get_pv("SSEQ_DLY_TGT2").await.unwrap(),
        EpicsValue::Double(0.0),
        "step 2 must not fire before step 1's delay completes"
    );

    // After DLY1 elapses, step 1 writes, then step 2 writes after it.
    poll_pv_double(&db, "SSEQ_DLY_TGT1", 11.0).await;
    poll_pv_double(&db, "SSEQ_DLY_TGT2", 22.0).await;
}

#[tokio::test]
async fn test_sel_nvl_link() {
    use epics_base_rs::server::records::sel::SelRecord;
    let db = PvDatabase::new();
    db.add_record("NVL_SRC", Box::new(AoRecord::new(2.0)))
        .await
        .unwrap();
    let mut sel = SelRecord::default();
    sel.selm = 0;
    sel.nvl = "NVL_SRC".to_string();
    sel.a = 10.0;
    sel.b = 20.0;
    sel.c = 30.0;
    db.add_record("SEL_REC", Box::new(sel)).await.unwrap();
    let mut visited = HashSet::new();
    db.process_record_with_links("SEL_REC", &mut visited, 0)
        .await
        .unwrap();
    let seln = db.get_pv("SEL_REC.SELN").await.unwrap();
    match seln {
        EpicsValue::UShort(v) => assert_eq!(v, 2),
        other => panic!("expected UShort(2), got {:?}", other),
    }
    let val = db.get_pv("SEL_REC").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 30.0).abs() < 1e-10),
        other => panic!("expected Double(30.0), got {:?}", other),
    }
}

// SELN is DBF_USHORT (selRecord.dbd.pod:295): an NVL link value in the
// upper unsigned half (32768..65535) must reach SELN intact. The former
// f64->i16 carrier saturated such a value to 32767, losing the high half.
#[tokio::test]
async fn test_sel_nvl_link_high_index_unsigned() {
    use epics_base_rs::server::records::sel::SelRecord;
    let db = PvDatabase::new();
    db.add_record("NVL_SRC_HI", Box::new(AoRecord::new(40000.0)))
        .await
        .unwrap();
    let mut sel = SelRecord::default();
    sel.selm = 0;
    sel.nvl = "NVL_SRC_HI".to_string();
    db.add_record("SEL_REC_HI", Box::new(sel)).await.unwrap();
    let mut visited = HashSet::new();
    db.process_record_with_links("SEL_REC_HI", &mut visited, 0)
        .await
        .unwrap();
    let seln = db.get_pv("SEL_REC_HI.SELN").await.unwrap();
    match seln {
        EpicsValue::UShort(v) => assert_eq!(v, 40000, "high SELN must survive the NVL link"),
        other => panic!("expected UShort(40000), got {:?}", other),
    }
}

#[tokio::test]
async fn test_dol_cp_link_registration() {
    let db = PvDatabase::new();
    db.add_record("MTR", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let mut ao = AoRecord::new(0.0);
    ao.omsl = 1;
    ao.dol = "MTR CP".to_string();
    db.add_record("MOTOR_POS", Box::new(ao)).await.unwrap();
    db.setup_cp_links().await;
    let targets = db.get_cp_targets("MTR").await;
    assert_eq!(targets.len(), 1);
    assert_eq!(targets[0].record, "MOTOR_POS");
    assert!(!targets[0].passive_only, "CP link must not be passive_only");
}

#[tokio::test]
async fn test_dol_cp_link_triggers_processing() {
    let db = PvDatabase::new();
    db.add_record("SRC", Box::new(AoRecord::new(10.0)))
        .await
        .unwrap();
    let mut ao = AoRecord::new(0.0);
    ao.omsl = 1;
    ao.dol = "SRC CP".to_string();
    db.add_record("DST", Box::new(ao)).await.unwrap();
    db.setup_cp_links().await;
    let mut visited = HashSet::new();
    db.process_record_with_links("SRC", &mut visited, 0)
        .await
        .unwrap();
    let val = db.get_pv("DST").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!((v - 10.0).abs() < 1e-10),
        other => panic!("expected Double(10.0), got {:?}", other),
    }
}

/// A CPP link registers as `passive_only` (distinct from CP). Collapsing
/// CPP into CP loses C's `precord->scan == 0` gate (`dbCa.c:994`).
#[tokio::test]
async fn test_cpp_link_registration_is_passive_only() {
    let db = PvDatabase::new();
    db.add_record("SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let mut ao = AoRecord::new(0.0);
    ao.omsl = 1;
    ao.dol = "SRC CPP".to_string();
    db.add_record("DST", Box::new(ao)).await.unwrap();
    db.setup_cp_links().await;
    let targets = db.get_cp_targets("SRC").await;
    assert_eq!(targets.len(), 1);
    assert_eq!(targets[0].record, "DST");
    assert!(
        targets[0].passive_only,
        "CPP link must register as passive_only"
    );
}

/// CPP gate (`dbCa.c:854,994,1072`): on a source change, a CPP link
/// processes the link-holder only when its SCAN is Passive. A non-Passive
/// CPP target must NOT be processed by the dispatch — its own periodic scan
/// owns it. Boundary: target SCAN != Passive.
#[tokio::test]
async fn test_cpp_link_skips_nonpassive_target() {
    let db = PvDatabase::new();
    db.add_record("SRC", Box::new(AoRecord::new(10.0)))
        .await
        .unwrap();
    let mut ao = AoRecord::new(0.0);
    ao.omsl = 1;
    ao.dol = "SRC CPP".to_string();
    db.add_record("DST", Box::new(ao)).await.unwrap();
    if let Some(rec_arc) = db.get_record("DST").await {
        rec_arc.write().await.common.scan = ScanType::Sec1;
    }
    db.setup_cp_links().await;
    let mut visited = HashSet::new();
    db.process_record_with_links("SRC", &mut visited, 0)
        .await
        .unwrap();
    let val = db.get_pv("DST").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!(
            v.abs() < 1e-10,
            "non-Passive CPP target was processed (VAL={v}); CPP must skip it"
        ),
        other => panic!("expected Double, got {:?}", other),
    }
}

/// CPP gate, complementary boundary: a CPP link DOES process the link-holder
/// when its SCAN is Passive (the default). Boundary: target SCAN == Passive.
#[tokio::test]
async fn test_cpp_link_processes_passive_target() {
    let db = PvDatabase::new();
    db.add_record("SRC", Box::new(AoRecord::new(10.0)))
        .await
        .unwrap();
    let mut ao = AoRecord::new(0.0);
    ao.omsl = 1;
    ao.dol = "SRC CPP".to_string();
    db.add_record("DST", Box::new(ao)).await.unwrap();
    // DST keeps the default Passive SCAN.
    db.setup_cp_links().await;
    let mut visited = HashSet::new();
    db.process_record_with_links("SRC", &mut visited, 0)
        .await
        .unwrap();
    let val = db.get_pv("DST").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!(
            (v - 10.0).abs() < 1e-10,
            "Passive CPP target was not processed (VAL={v})"
        ),
        other => panic!("expected Double, got {:?}", other),
    }
}

/// CP (not CPP) processes the link-holder regardless of its SCAN
/// (`dbCa.c:993` adds CA_DBPROCESS unconditionally). A non-Passive CP target
/// IS processed — the boundary that distinguishes CP from CPP.
#[tokio::test]
async fn test_cp_link_processes_nonpassive_target() {
    let db = PvDatabase::new();
    db.add_record("SRC", Box::new(AoRecord::new(10.0)))
        .await
        .unwrap();
    let mut ao = AoRecord::new(0.0);
    ao.omsl = 1;
    ao.dol = "SRC CP".to_string();
    db.add_record("DST", Box::new(ao)).await.unwrap();
    if let Some(rec_arc) = db.get_record("DST").await {
        rec_arc.write().await.common.scan = ScanType::Sec1;
    }
    db.setup_cp_links().await;
    let mut visited = HashSet::new();
    db.process_record_with_links("SRC", &mut visited, 0)
        .await
        .unwrap();
    let val = db.get_pv("DST").await.unwrap();
    match val {
        EpicsValue::Double(v) => assert!(
            (v - 10.0).abs() < 1e-10,
            "non-Passive CP target was not processed (VAL={v}); CP must always process"
        ),
        other => panic!("expected Double, got {:?}", other),
    }
}

/// When the same source→target edge is registered from both a CP and a CPP
/// link, CP dominates: the merged edge is NOT passive_only — an
/// unconditional CP CA_DBPROCESS overrides the CPP scan gate (`dbCa.c:993`).
#[tokio::test]
async fn test_cp_overrides_cpp_for_same_edge() {
    let db = PvDatabase::new();
    db.add_record("SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let mut ao = AoRecord::new(0.0);
    ao.omsl = 1;
    ao.dol = "SRC CP".to_string(); // CP edge SRC -> DST
    db.add_record("DST", Box::new(ao)).await.unwrap();
    // Second SRC -> DST edge via INP, this time CPP.
    if let Some(rec_arc) = db.get_record("DST").await {
        rec_arc.write().await.common.inp = "SRC CPP".to_string();
    }
    db.setup_cp_links().await;
    let targets = db.get_cp_targets("SRC").await;
    assert_eq!(
        targets.len(),
        1,
        "CP and CPP to the same edge must merge to one"
    );
    assert_eq!(targets[0].record, "DST");
    assert!(
        !targets[0].passive_only,
        "CP must override CPP on a merged edge"
    );
}

#[tokio::test]
async fn test_seq_dol_cp_link_registration() {
    use epics_base_rs::server::records::seq::SeqRecord;
    let db = PvDatabase::new();
    db.add_record("SENSOR", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let mut seq = SeqRecord::default();
    seq.dol1 = "SENSOR CP".to_string();
    db.add_record("MY_SEQ", Box::new(seq)).await.unwrap();
    db.setup_cp_links().await;
    let targets = db.get_cp_targets("SENSOR").await;
    assert_eq!(targets.len(), 1);
    assert_eq!(targets[0].record, "MY_SEQ");
    assert!(!targets[0].passive_only, "CP link must not be passive_only");
}

#[tokio::test]
async fn test_sel_nvl_cp_link_registration() {
    use epics_base_rs::server::records::sel::SelRecord;
    let db = PvDatabase::new();
    db.add_record("INDEX_SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let mut sel = SelRecord::default();
    sel.nvl = "INDEX_SRC CP".to_string();
    db.add_record("MY_SEL", Box::new(sel)).await.unwrap();
    db.setup_cp_links().await;
    let targets = db.get_cp_targets("INDEX_SRC").await;
    assert_eq!(targets.len(), 1);
    assert_eq!(targets[0].record, "MY_SEL");
    assert!(!targets[0].passive_only, "CP link must not be passive_only");
}

#[tokio::test]
async fn test_sdis_cp_link_registration() {
    let db = PvDatabase::new();
    db.add_record("DISABLE_SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("GUARDED", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec_arc) = db.get_record("GUARDED").await {
        rec_arc.write().await.common.sdis = "DISABLE_SRC CP".to_string();
    }
    db.setup_cp_links().await;
    let targets = db.get_cp_targets("DISABLE_SRC").await;
    assert_eq!(targets.len(), 1);
    assert_eq!(targets[0].record, "GUARDED");
    assert!(!targets[0].passive_only, "CP link must not be passive_only");
}

/// C `epicsTimeEventBestTime = -1` (epicsTime.h:103). The C path
/// (`recGbl.c::recGblGetTimeStampSimm:324-328`) calls
/// `epicsTimeGetEvent(-1)` unconditionally — that delegates to
/// `generalTimeGetEventPriority(-1)` (BestTime providers). A device
/// support that wants to keep its own timestamp must signal
/// TSE = -2 (epicsTimeEventDeviceTime), not -1.
///
/// Regression: the pre-fix Rust port read TSE=-1 as
/// "device-provided with BestTime fallback" and gated the call on
/// UNIX_EPOCH. A stale device write of any non-epoch SystemTime
/// suppressed every subsequent BestTime refresh.
#[tokio::test]
async fn test_tse_minus1_always_overwrites_via_best_time() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    // Stale but non-epoch timestamp — exactly the case the pre-fix
    // path mis-classified as "device-provided, keep".
    let stale = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1234567);
    if let Some(rec) = db.get_record("REC").await {
        let mut inst = rec.write().await;
        inst.common.tse = -1;
        inst.common.time = stale;
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("REC", &mut visited, 0)
        .await
        .unwrap();
    let rec = db.get_record("REC").await.unwrap();
    let inst = rec.read().await;
    assert_ne!(
        inst.common.time, stale,
        "TSE=-1 must always overwrite via generalTime BestTime, matching \
         C `epicsTimeGetEvent(-1)` called unconditionally"
    );
}

#[tokio::test]
async fn test_tse_minus2_keeps_time_unchanged() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let fixed_time = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(999);
    if let Some(rec) = db.get_record("REC").await {
        let mut inst = rec.write().await;
        inst.common.tse = -2;
        inst.common.time = fixed_time;
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("REC", &mut visited, 0)
        .await
        .unwrap();
    let rec = db.get_record("REC").await.unwrap();
    let inst = rec.read().await;
    assert_eq!(inst.common.time, fixed_time);
}

#[tokio::test]
async fn test_putf_read_only_from_ca() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let result = db
        .put_record_field_from_ca("REC", "PUTF", EpicsValue::Char(1))
        .await;
    assert!(result.is_err());
}

#[tokio::test]
async fn test_rpro_causes_reprocessing() {
    let db = PvDatabase::new();
    db.add_record("SRC", Box::new(AoRecord::new(10.0)))
        .await
        .unwrap();
    db.add_record("DEST", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("DEST").await {
        let mut inst = rec.write().await;
        inst.put_common_field("INP", EpicsValue::String("SRC".into()))
            .unwrap();
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("DEST", &mut visited, 0)
        .await
        .unwrap();
    let val = db.get_pv("DEST").await.unwrap();
    assert_eq!(val.to_f64().unwrap() as i64, 10);

    db.put_pv_no_process("SRC", EpicsValue::Double(20.0))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("DEST").await {
        let mut inst = rec.write().await;
        inst.common.rpro = true;
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("DEST", &mut visited, 0)
        .await
        .unwrap();
    let val = db.get_pv("DEST").await.unwrap();
    assert_eq!(val.to_f64().unwrap() as i64, 20);
    let rec = db.get_record("DEST").await.unwrap();
    let inst = rec.read().await;
    assert!(!inst.common.rpro);
}

#[tokio::test]
async fn test_tsel_cp_link_registration() {
    let db = PvDatabase::new();
    db.add_record("TSE_SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("TARGET", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec_arc) = db.get_record("TARGET").await {
        let mut inst = rec_arc.write().await;
        inst.common.tsel = "TSE_SRC CP".to_string();
        inst.parsed_tsel = parse_link_v2(&inst.common.tsel);
    }
    db.setup_cp_links().await;
    let targets = db.get_cp_targets("TSE_SRC").await;
    assert_eq!(targets.len(), 1);
    assert_eq!(targets[0].record, "TARGET");
    assert!(!targets[0].passive_only, "CP link must not be passive_only");
}

/// a record whose `TSEL` is a time-link at another record's `.TIME`
/// field (`DBLINK_FLAG_TSELisTIME`) adopts the source's timestamp AND
/// userTag, mirroring C `recGblGetTimeStampSimm` (recGbl.c:317) copying
/// both through `dbGetTimeStampTag(plink, &prec->time, &prec->utag)`.
/// Pre-fix only `common.time` was copied and the source's `utag` was
/// dropped.
#[tokio::test]
async fn test_tsel_time_link_copies_source_time_and_utag() {
    let db = PvDatabase::new();
    db.add_record("TSE_SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("TS_DST", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();

    // Source carries a known timestamp and a bit-31 userTag; the bit-31
    // value pins that the u64 utag is copied verbatim (no narrowing or
    // reset on the way through processing).
    let src_time = std::time::UNIX_EPOCH + std::time::Duration::new(1_700_000_000, 123);
    let src_utag: u64 = 0x9000_0000;
    {
        let rec = db.get_record("TSE_SRC").await.unwrap();
        let mut inst = rec.write().await;
        inst.common.time = src_time;
        inst.common.utag = src_utag;
    }

    // Target's TSEL points at the source's `.TIME` field.
    {
        let rec = db.get_record("TS_DST").await.unwrap();
        let mut inst = rec.write().await;
        inst.common.tsel = "TSE_SRC.TIME".to_string();
        inst.parsed_tsel = parse_link_v2(&inst.common.tsel);
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("TS_DST", &mut visited, 0)
        .await
        .unwrap();

    let rec = db.get_record("TS_DST").await.unwrap();
    let inst = rec.read().await;
    assert_eq!(
        inst.common.time, src_time,
        "TSEL .TIME link must adopt the source's timestamp"
    );
    assert_eq!(
        inst.common.utag, src_utag,
        "TSEL .TIME link must also adopt the source's utag (recGbl.c:317)"
    );
    assert_eq!(
        inst.common.tse, -2,
        "adopting device/link time marks TSE=-2"
    );
}

#[tokio::test]
async fn test_tsel_ca_time_link_copies_source_time() {
    // C `TSEL_modified` (dbLink.c:80-86) sets DBLINK_FLAG_TSELisTIME for
    // ANY PV_LINK TSEL whose pvname contains `.TIME`, set before the
    // DB-vs-CA decision (dbLink.c:118) — so a CA TSEL `.TIME` link copies
    // the link's cached timestamp via dbGetTimeStampTag (recGbl.c:317),
    // exactly like a local-DB link. CA wire carries no userTag, so utag
    // stays 0.
    use epics_base_rs::server::database::LinkSet;
    struct TimeCaLset {
        secs: i64,
        nsec: i32,
    }
    impl LinkSet for TimeCaLset {
        fn is_connected(&self, _: &str) -> bool {
            true
        }
        fn get_value(&self, _: &str) -> Option<EpicsValue> {
            Some(EpicsValue::Double(1.0))
        }
        fn time_stamp(&self, name: &str) -> Option<(i64, i32, u64)> {
            // Only the source record name (with `.TIME` stripped) should
            // reach the lset, mirroring C `TSEL_modified` truncating the
            // pvname at `.TIME`.
            assert_eq!(name, "TSE_SRC", "TSEL .TIME must strip the .TIME suffix");
            Some((self.secs, self.nsec, 0))
        }
    }

    let db = PvDatabase::new();
    db.register_link_set(
        "ca",
        Arc::new(TimeCaLset {
            secs: 1_700_000_000,
            nsec: 456,
        }),
    )
    .await;
    db.add_record("TS_CADST", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();
    {
        let rec = db.get_record("TS_CADST").await.unwrap();
        let mut inst = rec.write().await;
        inst.common.tsel = "ca://TSE_SRC.TIME".to_string();
        inst.parsed_tsel = parse_link_v2(&inst.common.tsel);
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("TS_CADST", &mut visited, 0)
        .await
        .unwrap();

    let rec = db.get_record("TS_CADST").await.unwrap();
    let inst = rec.read().await;
    let expected = std::time::UNIX_EPOCH + std::time::Duration::new(1_700_000_000, 456);
    assert_eq!(
        inst.common.time, expected,
        "CA TSEL .TIME link must adopt the CA link's cached timestamp"
    );
    assert_eq!(inst.common.utag, 0, "CA wire carries no userTag");
    assert_eq!(inst.common.tse, -2, "adopting link time marks TSE=-2");
}

#[tokio::test]
async fn test_tsel_nonlocal_db_time_link_copies_remote_time() {
    // A bare TSEL `.TIME` link (no `ca://`, no CP/CPP/CA modifier) whose
    // target record is NOT local. C `dbInitLink` (dbLink.c:115-130) sets
    // `TSELisTIME` and strips `.TIME` BEFORE the DB-vs-CA decision, then
    // `dbDbInitLink` fails for the non-local target so the link becomes a
    // CA link — `dbGetTimeStampTag` reads the remote `.TIME`. The pre-fix
    // Db arm did a local `get_record`, found nothing, and never adopted
    // the timestamp; the record kept its local processing time.
    use epics_base_rs::server::database::LinkSet;
    struct TimeCaLset {
        secs: i64,
        nsec: i32,
    }
    impl LinkSet for TimeCaLset {
        fn is_connected(&self, _: &str) -> bool {
            true
        }
        fn get_value(&self, _: &str) -> Option<EpicsValue> {
            Some(EpicsValue::Double(1.0))
        }
        fn time_stamp(&self, name: &str) -> Option<(i64, i32, u64)> {
            // The bare Db record name (`.TIME` already split into the link
            // field by the parser) reaches the CA lset via the non-local
            // fallback `external_link_time("ca://TSE_SRC")`.
            assert_eq!(
                name, "TSE_SRC",
                "non-local TSEL .TIME must address the bare record"
            );
            Some((self.secs, self.nsec, 0))
        }
    }

    let db = PvDatabase::new();
    db.register_link_set(
        "ca",
        Arc::new(TimeCaLset {
            secs: 1_700_000_123,
            nsec: 789,
        }),
    )
    .await;
    // TSE_SRC is never added locally -> the bare Db TSEL .TIME is non-local.
    db.add_record("TS_NLDST", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();
    {
        let rec = db.get_record("TS_NLDST").await.unwrap();
        let mut inst = rec.write().await;
        inst.common.tsel = "TSE_SRC.TIME".to_string();
        inst.parsed_tsel = parse_link_v2(&inst.common.tsel);
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("TS_NLDST", &mut visited, 0)
        .await
        .unwrap();

    let rec = db.get_record("TS_NLDST").await.unwrap();
    let inst = rec.read().await;
    let expected = std::time::UNIX_EPOCH + std::time::Duration::new(1_700_000_123, 789);
    assert_eq!(
        inst.common.time, expected,
        "non-local Db TSEL .TIME link must adopt the remote .TIME via the CA path"
    );
    assert_eq!(inst.common.tse, -2, "adopting link time marks TSE=-2");
}

#[tokio::test]
async fn test_new_common_fields_get_put() {
    let db = PvDatabase::new();
    db.add_record("REC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    let rec = db.get_record("REC").await.unwrap();

    {
        let inst = rec.read().await;
        assert_eq!(inst.get_common_field("UDFS"), Some(EpicsValue::Short(3)));
    }
    {
        let mut inst = rec.write().await;
        inst.put_common_field("UDFS", EpicsValue::Short(1)).unwrap();
    }
    {
        let inst = rec.read().await;
        assert_eq!(inst.get_common_field("UDFS"), Some(EpicsValue::Short(1)));
    }

    {
        let inst = rec.read().await;
        assert_eq!(inst.get_common_field("SSCN"), Some(EpicsValue::Enum(0)));
    }
    {
        let inst = rec.read().await;
        assert_eq!(inst.get_common_field("BKPT"), Some(EpicsValue::Char(0)));
    }
    {
        let mut inst = rec.write().await;
        inst.put_common_field("BKPT", EpicsValue::Char(1)).unwrap();
    }
    {
        let inst = rec.read().await;
        assert_eq!(inst.get_common_field("BKPT"), Some(EpicsValue::Char(1)));
    }

    {
        let inst = rec.read().await;
        assert_eq!(inst.get_common_field("TSE"), Some(EpicsValue::Short(0)));
    }
    {
        let inst = rec.read().await;
        assert_eq!(
            inst.get_common_field("TSEL"),
            Some(EpicsValue::String(String::new().into()))
        );
    }

    {
        let inst = rec.read().await;
        assert_eq!(inst.get_common_field("PUTF"), Some(EpicsValue::Char(0)));
    }
    {
        let mut inst = rec.write().await;
        let result = inst.put_common_field("PUTF", EpicsValue::Char(1));
        assert!(result.is_err());
    }

    {
        let inst = rec.read().await;
        assert_eq!(inst.get_common_field("RPRO"), Some(EpicsValue::Char(0)));
    }
    {
        let mut inst = rec.write().await;
        inst.put_common_field("RPRO", EpicsValue::Char(1)).unwrap();
    }
    {
        let inst = rec.read().await;
        assert_eq!(inst.get_common_field("RPRO"), Some(EpicsValue::Char(1)));
    }
}

/// epics-base PR #359 (commits 5ba8080f6, aff74638b, 51c5b8f1e,
/// fabc8d06a) regression: NORD monitor events from waveform / aai /
/// aao / subArray must carry the post-process timestamp, not a stale
/// (or zero) timestamp captured before `recGblGetTimeStamp`.
///
/// In the C source the bug was that `db_post_events(prec, &prec->nord, …)`
/// was called inside `readValue()` *before* the record's timestamp was
/// updated, so the very first NORD camonitor update arrived with an
/// undefined timestamp. The upstream fix moved the NORD post into
/// `process()` after `recGblGetTimeStampSimm`, applied across all four
/// array record types.
///
/// In the Rust port the ordering is structural: every notify path
/// (main, AsyncPendingNotify, complete_async_record) calls
/// `apply_timestamp` *before* building the snapshot and invoking
/// `notify_from_snapshot`. This test pins that contract for all four
/// `ArrayKind` variants by subscribing to NORD, processing once, and
/// verifying the delivered MonitorEvent timestamp is fresh.
#[tokio::test]
async fn test_array_records_nord_monitor_uses_post_process_timestamp() {
    use epics_base_rs::server::recgbl::EventMask;
    use epics_base_rs::server::records::waveform::{ArrayKind, WaveformRecord};
    use epics_base_rs::types::{DbFieldType, WallTime};

    for (kind, name) in [
        (ArrayKind::Waveform, "WF_KIND"),
        (ArrayKind::Aai, "AAI_KIND"),
        (ArrayKind::Aao, "AAO_KIND"),
        (ArrayKind::SubArray, "SUBA_KIND"),
    ] {
        let db = PvDatabase::new();
        db.add_record(name, Box::new(WaveformRecord::with_kind(kind)))
            .await
            .unwrap();

        // Configure DOUBLE buffer with NELM=10 — gives the put room
        // to actually move NORD from 0 → N. For subArray, also set
        // INDX=0 / MALM=10 so the slice is valid.
        if let Some(rec) = db.get_record(name).await {
            let mut inst = rec.write().await;
            inst.record.put_field("NELM", EpicsValue::Long(10)).unwrap();
            inst.record
                .put_field("FTVL", EpicsValue::Short(10))
                .unwrap();
            if matches!(kind, ArrayKind::SubArray) {
                inst.record.put_field("INDX", EpicsValue::Long(0)).unwrap();
                inst.record.put_field("MALM", EpicsValue::Long(10)).unwrap();
            }
        }

        // Wall-clock baseline AFTER record setup; the NORD event
        // timestamp must be ≥ this value.
        let start = WallTime::now();

        // Subscribe to NORD with VALUE mask. add_subscriber seeds
        // last_posted with the current NORD (=0), so the next
        // process cycle will treat the 0→N transition as a real
        // change.
        let mut nord_rx = if let Some(rec) = db.get_record(name).await {
            let mut inst = rec.write().await;
            inst.add_subscriber("NORD", 1, DbFieldType::Long, EventMask::VALUE.bits())
        } else {
            None
        }
        .unwrap_or_else(|| panic!("NORD subscription must be accepted for {name}"));

        // Stage the new array onto VAL. set_val updates VAL and
        // implicitly NORD (now =3). Processing applies the
        // timestamp and posts subscribed-field events.
        if let Some(rec) = db.get_record(name).await {
            let mut inst = rec.write().await;
            inst.record
                .set_val(EpicsValue::DoubleArray(vec![1.0, 2.0, 3.0]))
                .unwrap();
        }
        let mut visited = HashSet::new();
        db.process_record_with_links(name, &mut visited, 0)
            .await
            .unwrap();

        let event = nord_rx
            .try_recv()
            .unwrap_or_else(|_| panic!("NORD monitor event must be delivered for {name}"));
        assert!(
            matches!(event.snapshot.value, EpicsValue::Long(3)),
            "{name}: NORD payload should reflect post-set_val length (3), got {:?}",
            event.snapshot.value
        );
        let ts = event.snapshot.timestamp;
        assert!(
            ts != WallTime::UNIX_EPOCH,
            "{name}: NORD event timestamp must not be the epoch sentinel"
        );
        assert!(
            ts >= start,
            "{name}: NORD event timestamp ({ts:?}) must be ≥ pre-process baseline ({start:?})"
        );
    }
}

/// Regression: `complete_async_record_inner`'s subscriber-snapshot loop
/// previously appended every subscribed non-{VAL,SEVR,STAT,UDF} field
/// unconditionally — no `last_posted` change check, no `last_posted`
/// update — while the main path (`process_record_with_links_inner`
/// L794-820) gates on actual change. The asymmetry meant every
/// async-completion cycle re-sent every subscribed auxiliary field even
/// when its value was unchanged, multiplying monitor traffic for
/// records that pair an async write with a sticky metadata field
/// subscription.
///
/// This test pins the post-fix behaviour for both halves of the gate:
/// (a) unchanged → no event; (b) changed → event flows through.
#[tokio::test]
async fn test_complete_async_record_gates_subscribed_field_on_change() {
    use epics_base_rs::server::recgbl::EventMask;
    use epics_base_rs::types::DbFieldType;

    let db = PvDatabase::new();
    db.add_record("ASYNC_GATE", Box::new(AsyncRecord { val: 0.0 }))
        .await
        .unwrap();

    // Seed DESC to a known value so add_subscriber's last_posted
    // initialiser captures it.
    if let Some(rec) = db.get_record("ASYNC_GATE").await {
        let mut inst = rec.write().await;
        inst.put_common_field("DESC", EpicsValue::String("alpha".into()))
            .unwrap();
    }

    let mut desc_rx = if let Some(rec) = db.get_record("ASYNC_GATE").await {
        let mut inst = rec.write().await;
        inst.add_subscriber("DESC", 7, DbFieldType::String, EventMask::VALUE.bits())
    } else {
        None
    }
    .expect("DESC subscription must be accepted");

    // Drive process → AsyncPending early-return, then async completion.
    // DESC value unchanged since subscription, so the gate must
    // suppress the event.
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC_GATE", &mut visited, 0)
        .await
        .unwrap();
    db.complete_async_record("ASYNC_GATE").await.unwrap();

    assert!(
        desc_rx.try_recv().is_err(),
        "DESC unchanged across async-completion → must NOT post a duplicate event"
    );

    // Change DESC, re-run process+complete. The new value must flow.
    if let Some(rec) = db.get_record("ASYNC_GATE").await {
        let mut inst = rec.write().await;
        inst.put_common_field("DESC", EpicsValue::String("beta".into()))
            .unwrap();
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC_GATE", &mut visited, 0)
        .await
        .unwrap();
    db.complete_async_record("ASYNC_GATE").await.unwrap();

    let event = desc_rx
        .try_recv()
        .expect("DESC change must produce a post-completion event");
    assert!(
        matches!(event.snapshot.value, EpicsValue::String(ref s) if s == "beta"),
        "DESC event payload should reflect post-change value, got {:?}",
        event.snapshot.value
    );

    // And another no-op cycle after the change must again be silent.
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC_GATE", &mut visited, 0)
        .await
        .unwrap();
    db.complete_async_record("ASYNC_GATE").await.unwrap();
    assert!(
        desc_rx.try_recv().is_err(),
        "DESC stable after the change → no further events"
    );
}

/// Regression: `put_pv_and_post_with_origin` (and the no-origin
/// alias used by the CA gateway monitor forwarder) writes only the
/// explicitly-named field to subscribers. For array-family records
/// (waveform/aai/aao/subArray) a put to VAL implicitly updates NORD
/// via the record's `put_field("VAL", …)` side-effect, but the
/// pre-fix code never told NORD subscribers about the new length.
/// Result: a CA gateway forwarding upstream waveform monitors
/// updated VAL on the shadow PV but left downstream NORD subscribers
/// stuck at their last seen length — frozen-element-count bug
/// observable in PyDM image views computing height from element
/// count.
///
/// The fix snapshots NORD before and after the put and, when changed,
/// posts a NORD event with the same fresh timestamp as the VAL event.
/// This test pins the behaviour for waveform; the same code path
/// applies to aai/aao/subArray since they share the WaveformRecord
/// implementation.
#[tokio::test]
async fn test_put_pv_and_post_propagates_nord_side_effect_on_waveform() {
    use epics_base_rs::server::recgbl::EventMask;
    use epics_base_rs::server::records::waveform::{ArrayKind, WaveformRecord};
    use epics_base_rs::types::DbFieldType;

    let db = PvDatabase::new();
    db.add_record(
        "WF_GW",
        Box::new(WaveformRecord::with_kind(ArrayKind::Waveform)),
    )
    .await
    .unwrap();
    if let Some(rec) = db.get_record("WF_GW").await {
        let mut inst = rec.write().await;
        inst.record.put_field("NELM", EpicsValue::Long(10)).unwrap();
        inst.record
            .put_field("FTVL", EpicsValue::Short(10))
            .unwrap();
    }

    // Subscribe to NORD and VAL separately. add_subscriber seeds
    // last_posted with current values (NORD=0, VAL=empty array) so
    // the next change is treated as new.
    let (mut nord_rx, mut val_rx) = if let Some(rec) = db.get_record("WF_GW").await {
        let mut inst = rec.write().await;
        let n = inst.add_subscriber("NORD", 1, DbFieldType::Long, EventMask::VALUE.bits());
        let v = inst.add_subscriber("VAL", 2, DbFieldType::Double, EventMask::VALUE.bits());
        (n, v)
    } else {
        (None, None)
    };
    let nord_rx = nord_rx.as_mut().expect("NORD subscription accepted");
    let val_rx = val_rx.as_mut().expect("VAL subscription accepted");

    // Drive the gateway-style put: VAL update via put_pv_and_post,
    // no record processing. NORD must be reported alongside.
    db.put_pv_and_post("WF_GW", EpicsValue::DoubleArray(vec![1.0, 2.0, 3.0, 4.0]))
        .await
        .unwrap();

    let val_event = val_rx
        .try_recv()
        .expect("VAL event must be delivered after put_pv_and_post");
    let nord_event = nord_rx
        .try_recv()
        .expect("NORD event must be delivered after put_pv_and_post (side-effect of VAL)");
    assert!(
        matches!(nord_event.snapshot.value, EpicsValue::Long(4)),
        "NORD event should reflect post-put length (4), got {:?}",
        nord_event.snapshot.value
    );
    // VAL and NORD events must carry the SAME timestamp — both
    // observed the put within one critical section so they reflect
    // the same wall-clock snapshot.
    assert_eq!(
        val_event.snapshot.timestamp, nord_event.snapshot.timestamp,
        "VAL and NORD side-effect events must share the put's timestamp"
    );

    // No-op re-put with the same array: NORD didn't change, so no
    // duplicate NORD event.
    db.put_pv_and_post("WF_GW", EpicsValue::DoubleArray(vec![1.0, 2.0, 3.0, 4.0]))
        .await
        .unwrap();
    assert!(
        nord_rx.try_recv().is_err(),
        "NORD unchanged → no duplicate NORD event"
    );
}

/// epics-base commit f1e83b2 (2017) regression: output records must
/// update their TIME stamp BEFORE writing to OUT-link targets so that
/// downstream records (or anyone reading the source's TIME via TSEL)
/// see the post-process value, not the previous cycle's stale one.
///
/// In the C source the bug pattern was `recGblGetTimeStamp()` placed
/// AFTER `writeValue()` (the OUT-link write), so a downstream record
/// triggered by the OUT cascade would read the stale TIME until the
/// next process cycle.
///
/// In the Rust port the order is structural in
/// `process_record_with_links_inner`:
/// 1. `apply_timestamp` at L623 — TIME = now
/// 2. OUT stage at L668-764 — captures `out_info` (link, value)
/// 3. snapshot built / `notify_from_snapshot` at L866
/// 4. `write_db_link_value` at L870 — actual OUT-link write that
///    cascades downstream processing
///
/// This test pins the contract: when an SRC ao record with an OUT
/// link to a Passive DST processes, BOTH records' `common.time`
/// values must be ≥ the wall-clock baseline captured before
/// processing began. The test deliberately does not exercise the
/// downstream subscriber path (DST is an ai whose process()
/// recomputes VAL from RVAL, washing out the put_pv side-effect)
/// — the timestamp invariant is the load-bearing assertion here.
#[tokio::test]
async fn test_output_link_cascade_uses_post_process_source_timestamp() {
    use std::time::SystemTime;

    let db = PvDatabase::new();
    db.add_record("TS_SRC", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("TS_DST", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("TS_SRC").await {
        let mut inst = rec.write().await;
        // Explicit `PP` — C `dbDbPutValue` processes the OUT-link
        // target only on an explicit PP flag (a bare OUT link is NPP
        // and would only write the value). This test exercises the
        // cascade, so the PP modifier is required.
        inst.put_common_field("OUT", EpicsValue::String("TS_DST PP".into()))
            .unwrap();
    }

    let baseline = SystemTime::now();

    // Drive the source. SRC processes → apply_timestamp → OUT stage
    // captures (TS_DST, val) → snapshot/notify → write_db_link_value
    // cascades into TS_DST processing (which itself runs
    // apply_timestamp).
    if let Some(rec) = db.get_record("TS_SRC").await {
        let mut inst = rec.write().await;
        inst.record.set_val(EpicsValue::Double(7.5)).unwrap();
    }
    let mut visited = HashSet::new();
    db.process_record_with_links("TS_SRC", &mut visited, 0)
        .await
        .unwrap();

    // SRC's `common.time` must be ≥ baseline — it was updated by
    // apply_timestamp before write_db_link_value ran.
    let src_time = db
        .get_record("TS_SRC")
        .await
        .expect("TS_SRC exists")
        .read()
        .await
        .common
        .time;
    assert!(
        src_time >= baseline,
        "SRC.common.time ({src_time:?}) must be post-baseline ({baseline:?}) — \
         apply_timestamp must run before OUT write"
    );

    // DST's `common.time` must also be ≥ baseline — its own
    // apply_timestamp ran on the cascaded process call. (If the
    // cascade were broken or skipped, DST.common.time would be
    // UNIX_EPOCH from its uninitialised default.)
    let dst_time = db
        .get_record("TS_DST")
        .await
        .expect("TS_DST exists")
        .read()
        .await
        .common
        .time;
    assert!(
        dst_time >= baseline,
        "DST.common.time ({dst_time:?}) must be post-baseline ({baseline:?}) — \
         OUT cascade must drive Passive DST through process_record_with_links"
    );
}

/// f1e83b2 (second half) regression: for asynchronous output records
/// the timestamp must be updated AGAIN at completion, so the monitor
/// event reflects when the device write actually finished — not when
/// the process cycle started.
///
/// In the C source `recGblGetTimeStampSimm` is called inside the
/// `if (pact)` branch of process(), which fires at the async
/// completion callback.
///
/// In the Rust port `complete_async_record_inner` calls
/// `apply_timestamp` at L1192 before building the snapshot at
/// L1259-1262 and invoking `notify_from_snapshot` at L1351.
///
/// This test pins that contract by sleeping a small but measurable
/// interval between the synchronous `process_record_with_links`
/// (which puts the AsyncRecord into AsyncPending and returns) and
/// the `complete_async_record` call. The delivered VAL event must
/// carry a timestamp ≥ the post-sleep wall-clock instant — proving
/// the snapshot was timestamped at completion, not at process
/// start.
#[tokio::test]
async fn test_complete_async_record_updates_timestamp_at_completion() {
    use epics_base_rs::server::recgbl::EventMask;
    use epics_base_rs::types::{DbFieldType, WallTime};
    use std::time::Duration;

    let db = PvDatabase::new();
    db.add_record("ASYNC_TS", Box::new(AsyncRecord { val: 1.0 }))
        .await
        .unwrap();

    let mut val_rx = if let Some(rec) = db.get_record("ASYNC_TS").await {
        let mut inst = rec.write().await;
        inst.add_subscriber("VAL", 9, DbFieldType::Double, EventMask::VALUE.bits())
    } else {
        None
    }
    .expect("VAL subscription accepted");

    // First half: process → AsyncPending early return; no notify yet.
    let mut visited = HashSet::new();
    db.process_record_with_links("ASYNC_TS", &mut visited, 0)
        .await
        .unwrap();
    assert!(
        val_rx.try_recv().is_err(),
        "AsyncPending early-return must not deliver VAL event yet"
    );

    // Sleep a measurable interval so the completion timestamp is
    // distinguishable from the process-start timestamp.
    tokio::time::sleep(Duration::from_millis(20)).await;
    let post_sleep = WallTime::now();

    // Second half: completion fires snapshot/notify with a fresh
    // apply_timestamp.
    db.complete_async_record("ASYNC_TS").await.unwrap();
    let event = val_rx
        .try_recv()
        .expect("VAL event must be delivered at async completion");
    assert!(
        event.snapshot.timestamp >= post_sleep,
        "completion event timestamp ({:?}) must be ≥ post-sleep ({post_sleep:?}) — \
         apply_timestamp must run at async completion, not at process start",
        event.snapshot.timestamp
    );
}

/// epics-base PR #6c573b4 integration regression: a longout record
/// with `OOPT=On_Change` (1) must still emit its initial OUT-link
/// write on the very first process cycle even though val == pval ==
/// 0 satisfies the "no change" comparison. The C bug skipped that
/// initial write because outpvt was initialised to OUT_LINK_UNCHANGED;
/// the fix flipped the initial outpvt to EXEC_OUTPUT.
///
/// In the Rust port the equivalent flag is `LongoutRecord::first_output_done`
/// (`crates/epics-base-rs/src/server/records/longout.rs:69`):
/// `compute_should_output` short-circuits to `true` while it is
/// false, then the framework's `on_output_complete` flips it to
/// `true` after the OUT link / device write succeeds.
///
/// This test pins the integration: a first process cycle with
/// OOPT=1 must drive write_db_link_value (observed via the target
/// record's `common.time` advancing past baseline), and a second
/// no-op process cycle must not.
#[tokio::test]
async fn test_longout_oopt_on_change_first_cycle_emits_then_suppresses() {
    use epics_base_rs::server::records::longout::LongoutRecord;
    use std::time::SystemTime;

    let db = PvDatabase::new();
    db.add_record("LO_SRC", Box::new(LongoutRecord::new(0)))
        .await
        .unwrap();
    db.add_record("LO_DST", Box::new(LongoutRecord::new(0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("LO_SRC").await {
        let mut inst = rec.write().await;
        // Explicit `PP` — a bare OUT link is NPP (C `dbDbPutValue`);
        // this test observes the cascade via the target's timestamp,
        // so the OUT link must process the target.
        inst.put_common_field("OUT", EpicsValue::String("LO_DST PP".into()))
            .unwrap();
        inst.record.put_field("OOPT", EpicsValue::Short(1)).unwrap();
    }

    let baseline = SystemTime::now();

    // First cycle: val == pval == 0 satisfies "no change", but the
    // first-output-done guard forces the OUT cascade to fire.
    let mut visited = HashSet::new();
    db.process_record_with_links("LO_SRC", &mut visited, 0)
        .await
        .unwrap();

    let dst_time_after_first = db
        .get_record("LO_DST")
        .await
        .expect("LO_DST exists")
        .read()
        .await
        .common
        .time;
    assert!(
        dst_time_after_first >= baseline,
        "first-cycle OOPT=On_Change must drive OUT cascade (DST.time {dst_time_after_first:?} \
         must be ≥ baseline {baseline:?}); pre-fix the cascade was suppressed"
    );

    // Confirm the framework latched first_output_done=true.
    let src_first_done = db
        .get_record("LO_SRC")
        .await
        .expect("LO_SRC exists")
        .read()
        .await
        .record
        .get_field("VAL")
        .is_some();
    assert!(src_first_done, "SRC must have processed at least once");

    // Second cycle with VAL still 0: OOPT=1 should now suppress
    // the cascade because val == pval and the first-cycle guard is
    // off. Capture DST's time before to detect any unwanted
    // re-process.
    let dst_time_before_second = dst_time_after_first;
    tokio::time::sleep(std::time::Duration::from_millis(5)).await;
    let mut visited = HashSet::new();
    db.process_record_with_links("LO_SRC", &mut visited, 0)
        .await
        .unwrap();
    let dst_time_after_second = db
        .get_record("LO_DST")
        .await
        .expect("LO_DST exists")
        .read()
        .await
        .common
        .time;
    assert_eq!(
        dst_time_after_second, dst_time_before_second,
        "second-cycle OOPT=On_Change with val==pval must NOT re-trigger OUT cascade — \
         DST.time should not advance from {dst_time_before_second:?} to {dst_time_after_second:?}"
    );
}

/// epics-base commit 62c11c2 (2019) regression: a record whose OUT
/// link points at itself ("self link") must not trigger an infinite
/// RPRO/PUTF reprocessing loop. The C bug computed
/// `dstset = pdst.procThread==NULL` without checking psrc==pdst, so
/// when the self-link write fired processTarget the dst-side state
/// (= same record) was set up for RPRO and the record was scheduled
/// to reprocess after the current pass completed — which would
/// re-fire the self-link, ad infinitum.
///
/// In the Rust port the equivalent guard is the `visited: HashSet<String>`
/// passed through every `process_record_with_links_inner` call:
/// `visited.insert(name)` returns false for the second call on the
/// same record, and the function returns Ok(()) immediately. The CP
/// dispatch path (`dispatch_cp_targets`) and the RPRO recheck at L942
/// likewise bail out on self-targets via the same guard.
///
/// This test pins the contract: a longout with OUT="<self>" must
/// process exactly once per `process_record_with_links` call and the
/// call must complete promptly (we use a 1s timeout to fail fast on
/// infinite recursion regressions).
#[tokio::test]
async fn test_self_link_out_does_not_loop() {
    use epics_base_rs::server::records::longout::LongoutRecord;
    use std::time::Duration;

    let db = PvDatabase::new();
    db.add_record("SELF_LO", Box::new(LongoutRecord::new(0)))
        .await
        .unwrap();
    if let Some(rec) = db.get_record("SELF_LO").await {
        let mut inst = rec.write().await;
        // OUT="SELF_LO.VAL PP" → explicit PP so write_db_link_value
        // attempts to re-process self; this is the case the visited
        // HashSet recursion guard must catch. A bare OUT link is NPP
        // (C `dbDbPutValue`) and would not exercise the guard at all.
        inst.put_common_field("OUT", EpicsValue::String("SELF_LO PP".into()))
            .unwrap();
    }

    // 1-second timeout: if the self-link guard regresses, the
    // process call would never return (infinite recursion via
    // write_db_link_value → process_record_with_links → ...).
    let mut visited = HashSet::new();
    let result = tokio::time::timeout(
        Duration::from_secs(1),
        db.process_record_with_links("SELF_LO", &mut visited, 0),
    )
    .await;

    assert!(
        result.is_ok(),
        "self-link processing must complete within 1s — \
         hang implies the visited HashSet guard regressed"
    );
    result.unwrap().expect("process call must succeed");

    // Confirm the visited set picked up SELF_LO exactly once.
    assert!(visited.contains("SELF_LO"));

    // A subsequent process call (fresh visited) must also complete
    // promptly — the RPRO flag from the first call must not have
    // been left set on the record, otherwise the record would
    // reprocess in a loop after every external put.
    let mut visited2 = HashSet::new();
    let result2 = tokio::time::timeout(
        Duration::from_secs(1),
        db.process_record_with_links("SELF_LO", &mut visited2, 0),
    )
    .await;
    assert!(
        result2.is_ok(),
        "subsequent self-link processing must also complete within 1s"
    );
    result2.unwrap().expect("second process call must succeed");

    // RPRO flag must be cleared after each call, not stuck at true.
    let rpro_after = db
        .get_record("SELF_LO")
        .await
        .expect("SELF_LO exists")
        .read()
        .await
        .common
        .rpro;
    assert!(
        !rpro_after,
        "RPRO must be cleared after self-link processing — \
         stuck-true would queue an infinite reprocess loop"
    );
}

/// epics-base commit 8ac2c87 (2025) regression: writing to a
/// compress record's RES field must reset the circular buffer AND
/// post a monitor event so CA clients see the empty array
/// immediately. Pre-fix C only updated VAL silently — clients
/// observing via camonitor would miss the reset.
///
/// Rust impl: `CompressRecord::put_field("RES", _)` clears
/// nuse/off/val in place and zeros res back to 0
/// (records/compress.rs:260). The framework then runs
/// `process_record_with_links_inner`, whose snapshot path includes
/// VAL via the always-on `include_val` branch for non-deadband
/// records, so the VAL subscriber sees the post-reset empty array.
#[tokio::test]
async fn test_compress_res_write_posts_val_monitor() {
    use epics_base_rs::server::recgbl::EventMask;
    use epics_base_rs::server::records::compress::CompressRecord;
    use epics_base_rs::types::DbFieldType;

    let db = PvDatabase::new();
    db.add_record("CMP_RES", Box::new(CompressRecord::new(8, 4)))
        .await
        .unwrap();

    // Pre-load the buffer with some values so the post-reset state
    // is observably different from the initial zeros.
    if let Some(rec) = db.get_record("CMP_RES").await {
        let mut inst = rec.write().await;
        // Drive values through put_field/process so VAL is updated
        // through the public Record API rather than reaching into
        // the concrete CompressRecord state.
        // CompressRecord's process() pushes from INP — we don't have
        // an INP, so instead manually populate a few VAL entries.
        let arr = EpicsValue::DoubleArray(vec![1.0, 2.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
        let _ = inst.record.put_field("VAL", arr);
    }

    let mut val_rx = if let Some(rec) = db.get_record("CMP_RES").await {
        let mut inst = rec.write().await;
        inst.add_subscriber("VAL", 1, DbFieldType::Double, EventMask::VALUE.bits())
    } else {
        None
    }
    .expect("VAL subscription accepted");

    // Drive RES=1 via the CA put path so processing runs.
    let _ = db
        .put_record_field_from_ca("CMP_RES", "RES", EpicsValue::Short(1))
        .await;

    let event = val_rx
        .try_recv()
        .expect("RES write must trigger a VAL monitor event");
    if let EpicsValue::DoubleArray(v) = &event.snapshot.value {
        // Post-reset: NUSE=0, so VAL should be all zeros (or empty
        // depending on PBUF). Either way, none of {1.0, 2.0, 3.0}
        // should still be present.
        assert!(
            v.iter().all(|&x| x == 0.0),
            "post-reset VAL must be all zeros; got {v:?}"
        );
    } else {
        panic!("VAL must be DoubleArray, got {:?}", event.snapshot.value);
    }

    // RES itself reset back to 0.
    let res = db
        .get_record("CMP_RES")
        .await
        .expect("CMP_RES exists")
        .read()
        .await
        .record
        .get_field("RES")
        .and_then(|v| match v {
            EpicsValue::Short(s) => Some(s),
            _ => None,
        })
        .expect("RES readable");
    assert_eq!(res, 0, "RES must auto-clear after the reset");
}

/// epics-base PR `dabcf89` (2021) regression: when an mbboDirect
/// record initialises with no VAL set (UDF=true on the framework
/// side) but with at least one B0..B1F bit set in the .db file,
/// VAL must be reconstructed from those bits and UDF cleared. The
/// pre-fix C code always derived bits from VAL, so an init like
/// `record(mbboDirect, "...") { field(B3, "1") }` without an
/// initial VAL produced VAL=0 (and UDF stayed true) instead of
/// VAL=8 (UDF=false).
///
/// Rust impl: `MbboDirectRecord::post_init_finalize_undef` is
/// invoked by ioc_builder after both `init_record` passes; it
/// chooses VAL→bits or bits→VAL based on the framework's
/// `common.udf`. We exercise the bits-set / undefined branch
/// directly via the trait method since the full IocBuilder pipeline
/// pulls in many unrelated pieces.
#[tokio::test]
async fn test_mbbo_direct_initialises_val_from_bits_when_undef() {
    use epics_base_rs::server::record::Record;
    use epics_base_rs::server::records::mbbo_direct::MbboDirectRecord;

    let mut rec = MbboDirectRecord::default();
    // Operator set B3=1 in the .db; framework UDF=true (no VAL).
    rec.put_field("B3", EpicsValue::Char(1)).unwrap();
    let mut udf = true;
    rec.post_init_finalize_undef(&mut udf).unwrap();
    assert!(
        !udf,
        "UDF must be cleared once bits supplied an initial value"
    );
    assert!(matches!(rec.get_field("VAL"), Some(EpicsValue::Long(8))));

    // Sibling case: VAL was set explicitly (UDF=false). bits should
    // be derived from VAL.
    let mut rec2 = MbboDirectRecord::default();
    rec2.put_field("VAL", EpicsValue::Long(0b0101)).unwrap();
    let mut udf2 = false;
    rec2.post_init_finalize_undef(&mut udf2).unwrap();
    assert!(!udf2, "UDF stays cleared");
    assert!(matches!(rec2.get_field("VAL"), Some(EpicsValue::Long(5))));
    // bits[0] and bits[2] should reflect VAL=5 (binary 0101).
    assert!(matches!(rec2.get_field("B0"), Some(EpicsValue::Char(1))));
    assert!(matches!(rec2.get_field("B2"), Some(EpicsValue::Char(1))));
    assert!(matches!(rec2.get_field("B1"), Some(EpicsValue::Char(0))));

    // Sibling case: nothing set — UDF stays true, VAL stays 0.
    let mut rec3 = MbboDirectRecord::default();
    let mut udf3 = true;
    rec3.post_init_finalize_undef(&mut udf3).unwrap();
    assert!(udf3, "UDF stays true when nothing initialised");
    assert!(matches!(rec3.get_field("VAL"), Some(EpicsValue::Long(0))));
}

/// epics-base PR `e3c9d590` / `20404003` regression: `lnkCalc` JSON
/// link `{calc:{expr:"...", args:[...], time:"X"}}` parses into
/// `ParsedLink::Calc`, the read path evaluates the expression by
/// fetching each input PV and binding A..L slots, and timestamp
/// passthrough from the chosen input is available via
/// `evaluate_calc_link_with_time`.
#[tokio::test]
async fn test_lnk_calc_parses_evaluates_and_passes_timestamp() {
    use epics_base_rs::server::record::{CalcLink, ParsedLink, parse_link_v2};
    use epics_base_rs::server::records::ai::AiRecord;

    // Parser: full lnkCalc form.
    let parsed = parse_link_v2(r#"{calc:{"expr":"A+B*2","args":["pv_a","pv_b"],"time":"A"}}"#);
    let calc = match parsed {
        ParsedLink::Calc(c) => c,
        other => panic!("expected ParsedLink::Calc, got {other:?}"),
    };
    assert_eq!(calc.expr, "A+B*2");
    assert_eq!(calc.args, vec!["pv_a".to_string(), "pv_b".to_string()]);
    assert_eq!(calc.time_source, Some('A'));

    // Parser without `time` field — time_source must be None.
    let no_time = parse_link_v2(r#"{calc:{"expr":"A","args":["pv_a"]}}"#);
    assert!(matches!(
        no_time,
        ParsedLink::Calc(CalcLink {
            time_source: None,
            ..
        })
    ));

    // Parser rejects args.len() > 12 (calc engine A..L cap).
    let too_many = parse_link_v2(
        r#"{calc:{"expr":"A","args":["a","b","c","d","e","f","g","h","i","j","k","l","m"]}}"#,
    );
    assert!(
        !matches!(too_many, ParsedLink::Calc(_)),
        "13+ args must NOT parse as Calc"
    );

    // Read-path: feed real PVs, evaluate A+B*2.
    let db = PvDatabase::new();
    db.add_record("pv_a", Box::new(AiRecord::new(3.0)))
        .await
        .unwrap();
    db.add_record("pv_b", Box::new(AiRecord::new(5.0)))
        .await
        .unwrap();

    let calc = CalcLink {
        expr: "A+B*2".into(),
        args: vec!["pv_a".into(), "pv_b".into()],
        time_source: Some('A'),
    };
    let parsed = ParsedLink::Calc(calc.clone());
    let mut visited = HashSet::new();
    let value = db
        .read_link_value_soft(&parsed, true, &mut visited, 0)
        .await
        .expect("calc link evaluates");
    match value {
        EpicsValue::Double(v) => assert!((v - 13.0).abs() < 1e-9, "expected 3+5*2=13, got {v}"),
        other => panic!("expected Double, got {other:?}"),
    }

    // Timestamp passthrough: nudge pv_a's common.time to a known
    // value, then verify evaluate_calc_link_with_time returns it.
    let known = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
    if let Some(rec) = db.get_record("pv_a").await {
        rec.write().await.common.time = known;
    }
    let (v, t) = db
        .evaluate_calc_link_with_time(&calc)
        .await
        .expect("calc evaluates with time");
    match v {
        EpicsValue::Double(x) => assert!((x - 13.0).abs() < 1e-9),
        other => panic!("expected Double, got {other:?}"),
    }
    assert_eq!(t, Some(known), "time pulled from pv_a (letter 'A')");
}

/// A `lnkCalc` `{calc:...}` link whose input record is NON-LOCAL must
/// read that input through the external CA path, and its timestamp
/// passthrough must adopt the remote `.TIME` — each `A..L` input is its
/// own `dbInitLink` link, so a non-local input is a CA link. The pre-fix
/// loop read every input with a local-only `get_pv` (and the time source
/// with a local-only `get_record`), so a single non-local input made the
/// whole evaluation return `None` and the time fell back to the
/// consumer's own. Sibling of the non-local Db read / OUT-write / TSEL
/// `.TIME` fixes — same `dbInitLink` locality cause, the lnkCalc inputs.
#[tokio::test]
async fn test_lnk_calc_nonlocal_input_resolves_externally() {
    use epics_base_rs::server::database::LinkSet;
    use epics_base_rs::server::record::CalcLink;
    use epics_base_rs::server::records::ai::AiRecord;

    struct CalcCaLset {
        secs: i64,
        nsec: i32,
    }
    impl LinkSet for CalcCaLset {
        fn is_connected(&self, _: &str) -> bool {
            true
        }
        fn get_value(&self, name: &str) -> Option<EpicsValue> {
            (name == "REMOTE:A").then_some(EpicsValue::Double(10.0))
        }
        fn time_stamp(&self, name: &str) -> Option<(i64, i32, u64)> {
            (name == "REMOTE:A").then_some((self.secs, self.nsec, 0))
        }
    }

    let db = PvDatabase::new();
    db.register_link_set(
        "ca",
        Arc::new(CalcCaLset {
            secs: 1_700_000_456,
            nsec: 321,
        }),
    )
    .await;
    // pv_b is local; REMOTE:A is never added → non-local CA input.
    db.add_record("pv_b", Box::new(AiRecord::new(5.0)))
        .await
        .unwrap();

    let calc = CalcLink {
        expr: "A+B*2".into(),
        args: vec!["REMOTE:A".into(), "pv_b".into()],
        time_source: Some('A'),
    };

    let (value, time) = db
        .evaluate_calc_link_with_time(&calc)
        .await
        .expect("calc with a non-local input must still evaluate");
    match value {
        // 10 (remote A) + 5 (local B) * 2 = 20.
        EpicsValue::Double(v) => assert!(
            (v - 20.0).abs() < 1e-9,
            "non-local calc input must resolve via CA: expected 20, got {v}"
        ),
        other => panic!("expected Double, got {other:?}"),
    }
    let expected = std::time::UNIX_EPOCH + std::time::Duration::new(1_700_000_456, 321);
    assert_eq!(
        time,
        Some(expected),
        "time source 'A' is non-local → adopt the remote .TIME via the CA path"
    );
}

/// Regression: a CA put to `mbbo.VAL` must recompute RVAL/ORAW.
///
/// C `mbboRecord.c::process` (line 217) calls `convert(prec)`
/// unconditionally on every non-pact process — the VAL→RVAL output
/// translation. Pre-fix, `put_record_field_from_ca` called
/// `set_device_did_compute(true)` for *any* VAL put, and `mbbo`
/// interpreted that as "skip the output convert", so RVAL/ORAW kept
/// their stale pre-put value while the OUT link drove the wrong raw.
///
/// With `shft = 4` and no state table, `convert()` yields
/// `RVAL = VAL << 4`. A CA put of VAL=3 must produce RVAL=ORAW=48.
#[tokio::test]
async fn test_ca_put_mbbo_val_recomputes_rval() {
    use epics_base_rs::server::records::mbbo::MbboRecord;

    let db = PvDatabase::new();
    let mut rec = MbboRecord::new(0);
    rec.shft = 4;
    db.add_record("MBBO_CA", Box::new(rec)).await.unwrap();

    db.put_record_field_from_ca("MBBO_CA", "VAL", EpicsValue::Enum(3))
        .await
        .unwrap();

    let rec = db.get_record("MBBO_CA").await.unwrap();
    let inst = rec.read().await;
    assert_eq!(
        inst.record.get_field("VAL"),
        Some(EpicsValue::Enum(3)),
        "VAL holds the CA-written value"
    );
    // RVAL/ORAW are DBF_ULONG (mbboRecord.dbd.pod:620,624).
    assert_eq!(
        inst.record.get_field("RVAL"),
        Some(EpicsValue::ULong(48)),
        "RVAL must be recomputed from the new VAL (3 << 4), not left stale at 0"
    );
    assert_eq!(
        inst.record.get_field("ORAW"),
        Some(EpicsValue::ULong(48)),
        "ORAW must roll forward to the freshly converted RVAL"
    );
}

/// Regression: a CA put to `mbboDirect.VAL` must recompute RVAL/ORAW.
///
/// C `mbboDirectRecord.c::process` (line 198) calls `convert(prec)`
/// unconditionally. With `shft = 4`, `convert()` yields
/// `RVAL = VAL << 4`. A CA put of VAL=5 must produce RVAL=ORAW=80.
#[tokio::test]
async fn test_ca_put_mbbo_direct_val_recomputes_rval() {
    use epics_base_rs::server::records::mbbo_direct::MbboDirectRecord;

    let db = PvDatabase::new();
    let mut rec = MbboDirectRecord::default();
    rec.shft = 4;
    db.add_record("MBBOD_CA", Box::new(rec)).await.unwrap();

    db.put_record_field_from_ca("MBBOD_CA", "VAL", EpicsValue::Long(5))
        .await
        .unwrap();

    let rec = db.get_record("MBBOD_CA").await.unwrap();
    let inst = rec.read().await;
    // RVAL/ORAW are DBF_ULONG (mbboDirectRecord.dbd.pod:167,172).
    assert_eq!(
        inst.record.get_field("RVAL"),
        Some(EpicsValue::ULong(80)),
        "RVAL must be recomputed from the new VAL (5 << 4), not left stale at 0"
    );
    assert_eq!(
        inst.record.get_field("ORAW"),
        Some(EpicsValue::ULong(80)),
        "ORAW must roll forward to the freshly converted RVAL"
    );
}

/// CRITICAL 1 — a record in SIMM (simulation) mode must still run its
/// forward link. C `aiRecord.c:151-168`: simulation is handled inside
/// `readValue()`, then `process()` ALWAYS runs `recGblFwdLink(prec)`
/// (`aiRecord.c:168`). The pre-fix Rust port returned early from
/// `check_simulation_mode`, so FLNK / CP / RPRO were skipped — every
/// link chain downstream of a SIMM-mode record silently broke.
#[tokio::test]
async fn test_simulation_mode_still_fires_forward_link() {
    let db = PvDatabase::new();
    db.add_record("SIM:SRC", Box::new(AoRecord::new(11.0)))
        .await
        .unwrap();
    db.add_record("SIM:FLNK_TARGET", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    let mut ai = AiRecord::new(0.0);
    // SIMM=1 (YES) with SIOL pointing at SIM:SRC — enters simulation.
    ai.simm = 1;
    ai.siol = "SIM:SRC".into();
    db.add_record("SIM:AI", Box::new(ai)).await.unwrap();
    if let Some(rec) = db.get_record("SIM:AI").await {
        let mut inst = rec.write().await;
        inst.put_common_field("FLNK", EpicsValue::String("SIM:FLNK_TARGET".into()))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("SIM:AI", &mut visited, 0)
        .await
        .unwrap();

    assert!(
        visited.contains("SIM:AI"),
        "the simulated record itself must be in the visited set"
    );
    assert!(
        visited.contains("SIM:FLNK_TARGET"),
        "a SIMM-mode record must still dispatch its FLNK forward link \
         (C aiRecord.c:168 recGblFwdLink runs unconditionally): {visited:?}"
    );
}

/// BUG 2 — a simulated `mbbi` is an INPUT record: it must READ the
/// value in from SIOL, not write VAL out to SIOL. `mbbiRecord.c:125-126`
/// declares SIML/SIOL and `mbbiRecord.c:388-394` reads
/// `dbGetLink(&prec->siol, DBR_ULONG, &prec->sval)`. Pre-fix the Rust
/// `is_input` set omitted `mbbi`, so a simulated mbbi fell into the
/// OUTPUT branch and wrote its own VAL out to the SIOL target.
#[tokio::test]
async fn test_simulated_mbbi_reads_siol_not_writes_it() {
    use epics_base_rs::server::records::mbbi::MbbiRecord;

    let db = PvDatabase::new();
    // SIOL source holds the simulated input value (index 3).
    db.add_record("MBBISIM:SRC", Box::new(LonginRecord::new(3)))
        .await
        .unwrap();

    // mbbi starts at index 0; SIMM=1 (YES), SIOL -> the source.
    let mut mbbi = MbbiRecord::new(0);
    mbbi.simm = 1;
    mbbi.siol = "MBBISIM:SRC".into();
    db.add_record("MBBISIM:IN", Box::new(mbbi)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("MBBISIM:IN", &mut visited, 0)
        .await
        .unwrap();

    // The SIOL source must be UNCHANGED — a simulated mbbi must not
    // write its VAL out to SIOL.
    let src = db.get_record("MBBISIM:SRC").await.unwrap();
    let src_val = src.read().await.record.get_field("VAL").unwrap();
    assert_eq!(
        src_val.to_f64().unwrap() as i64,
        3,
        "simulated mbbi must NOT write VAL out to its SIOL target"
    );

    // The mbbi must have READ the value in from SIOL.
    let mbbi_rec = db.get_record("MBBISIM:IN").await.unwrap();
    let mbbi_val = mbbi_rec.read().await.record.get_field("VAL").unwrap();
    assert_eq!(
        mbbi_val.to_f64().unwrap() as i64,
        3,
        "simulated mbbi must read VAL in from SIOL (got {mbbi_val:?})"
    );
}

/// BUG 3 — async-completion FLNK must not recurse into the
/// just-completed record. `complete_async_record_inner` seeds the
/// cycle-guard `visited` set with the record's own name (mirroring the
/// synchronous `process_record_with_links_inner`). An FLNK chain that
/// loops back (A -> FLNK -> B -> FLNK -> A) must terminate, not
/// re-enter A unbounded.
#[tokio::test]
async fn test_async_completion_flnk_cycle_terminates() {
    let db = PvDatabase::new();
    db.add_record("ACYC:A", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("ACYC:B", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    // A -> FLNK -> B -> FLNK -> A : a closed forward-link loop.
    if let Some(rec) = db.get_record("ACYC:A").await {
        let mut inst = rec.write().await;
        inst.put_common_field("FLNK", EpicsValue::String("ACYC:B".into()))
            .unwrap();
    }
    if let Some(rec) = db.get_record("ACYC:B").await {
        let mut inst = rec.write().await;
        inst.put_common_field("FLNK", EpicsValue::String("ACYC:A".into()))
            .unwrap();
    }

    // Driving the async-completion path on A must terminate — pre-fix
    // it re-entered A through B's FLNK because `visited` was never
    // seeded with A's own name. A hung/overflowed run fails the test
    // by timeout/panic; a clean return proves the cycle guard closed.
    db.complete_async_record("ACYC:A").await.unwrap();
}

/// BUG 4 — fanout/seq/sseq must resolve the SELL input link into SELN
/// before SELN is used. C `fanoutRecord.c:103` calls
/// `dbGetLink(&prec->sell, DBR_USHORT, &prec->seln, 0, 0)` at the top
/// of every `process()`. Pre-fix `dispatch_multi_output` read SELN
/// directly from the field and never followed SELL, so a SELL link
/// pointing at another record never updated the selection.
#[tokio::test]
async fn test_fanout_resolves_sell_link_into_seln() {
    use epics_base_rs::server::records::fanout::FanoutRecord;

    let db = PvDatabase::new();
    // SELL source: selects link index 2.
    db.add_record("FANSELL:SRC", Box::new(LonginRecord::new(2)))
        .await
        .unwrap();
    db.add_record("FANSELL:T2", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();
    db.add_record("FANSELL:T0", Box::new(AoRecord::new(0.0)))
        .await
        .unwrap();

    let mut fan = FanoutRecord::new();
    fan.put_field("SELM", EpicsValue::Short(1)).unwrap(); // Specified
    fan.put_field("SELN", EpicsValue::Short(0)).unwrap(); // stale init value
    // SELL points at the source — must resolve to SELN=2 at process.
    fan.put_field("SELL", EpicsValue::String("FANSELL:SRC".into()))
        .unwrap();
    fan.put_field("LNK0", EpicsValue::String("FANSELL:T0 PP".into()))
        .unwrap();
    fan.put_field("LNK2", EpicsValue::String("FANSELL:T2 PP".into()))
        .unwrap();
    db.add_record("FANSELL:FAN", Box::new(fan)).await.unwrap();

    let mut visited = HashSet::new();
    db.process_record_with_links("FANSELL:FAN", &mut visited, 0)
        .await
        .unwrap();

    // SELL resolved SELN to 2 -> SELM=Specified fans out LNK2 only.
    assert!(
        visited.contains("FANSELL:T2"),
        "SELL must resolve SELN=2 so LNK2 is dispatched: {visited:?}"
    );
    assert!(
        !visited.contains("FANSELL:T0"),
        "with SELL-resolved SELN=2, the stale SELN=0 (LNK0) must NOT \
         be dispatched: {visited:?}"
    );
    // SELN must now hold the SELL-resolved value.
    let fan_rec = db.get_record("FANSELL:FAN").await.unwrap();
    let seln = fan_rec.read().await.record.get_field("SELN").unwrap();
    assert_eq!(
        seln,
        EpicsValue::UShort(2),
        "SELN must be updated from the SELL link"
    );
}

/// BUG 5 — `putAcks` (C `dbAccess.c:1303-1315`) compares the written
/// severity against the STORED unacknowledged severity `acks`, not
/// against the current `sevr`; `putAckt` (C `dbAccess.c:1285-1301`)
/// lowers `acks` down to `sevr` when ACKT is set false and
/// `acks > sevr`.
#[tokio::test]
async fn test_acks_put_compares_against_acks_and_ackt_lowers() {
    // putAcks: acks must be cleared when the written severity is >=
    // the STORED acks, even after sevr has dropped below it.
    {
        let rec = AoRecord::new(0.0);
        let mut inst = RecordInstance::new("ACKTEST1".into(), rec);
        // Latched sticky alarm: acks=MAJOR(2); current sevr has since
        // dropped to MINOR(1).
        inst.common.acks = AlarmSeverity::Major;
        inst.common.sevr = AlarmSeverity::Minor;
        // Acknowledge at MAJOR — written sev (2) >= acks (2) -> clear.
        inst.put_common_field("ACKS", EpicsValue::Short(2)).unwrap();
        assert_eq!(
            inst.common.acks,
            AlarmSeverity::NoAlarm,
            "ACKS write at sev>=stored acks must clear acks \
             (C dbAccess.c:1309 compares *psev >= precord->acks)"
        );

        // A second case: written sev BELOW the stored acks must NOT
        // clear it — proving the comparison is against `acks`, not
        // `sevr`. Were it compared against sevr (Minor), a MINOR write
        // would wrongly clear.
        let rec2 = AoRecord::new(0.0);
        let mut inst2 = RecordInstance::new("ACKTEST2".into(), rec2);
        inst2.common.acks = AlarmSeverity::Major;
        inst2.common.sevr = AlarmSeverity::Minor;
        inst2
            .put_common_field("ACKS", EpicsValue::Short(1))
            .unwrap();
        assert_eq!(
            inst2.common.acks,
            AlarmSeverity::Major,
            "ACKS write at sev BELOW stored acks must NOT clear acks; \
             comparing against sevr (Minor) instead would wrongly clear"
        );
    }

    // putAckt: ACKT set false with acks > sevr must lower acks to sevr.
    {
        let rec = AoRecord::new(0.0);
        let mut inst = RecordInstance::new("ACKTEST3".into(), rec);
        inst.common.ackt = true;
        inst.common.acks = AlarmSeverity::Major;
        inst.common.sevr = AlarmSeverity::Minor;
        inst.put_common_field("ACKT", EpicsValue::Short(0)).unwrap();
        assert!(!inst.common.ackt, "ACKT must be cleared");
        assert_eq!(
            inst.common.acks,
            AlarmSeverity::Minor,
            "ACKT=false with acks>sevr must lower acks down to sevr \
             (C dbAccess.c:1294-1297)"
        );
    }
}

/// BUG 2 regression — a bare (modifier-less) OUT link is NPP: the
/// value is written to the target but the target is NOT processed.
/// C `dbDbPutValue` (dbDbLink.c:386-389) calls `processTarget` only
/// when the link carries an explicit `PP` flag (or writes `.PROC`).
#[tokio::test]
async fn test_bare_out_link_does_not_process_target() {
    let db = PvDatabase::new();
    db.add_record("SRC_OUT", Box::new(AoRecord::new(33.0)))
        .await
        .unwrap();
    db.add_record("TGT_OUT", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();

    // Bare OUT link — no PP modifier.
    if let Some(rec) = db.get_record("SRC_OUT").await {
        let mut inst = rec.write().await;
        inst.put_common_field("OUT", EpicsValue::String("TGT_OUT.VAL".into()))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("SRC_OUT", &mut visited, 0)
        .await
        .unwrap();

    // The value must have landed on the target.
    let tgt_val = db.get_pv("TGT_OUT").await.unwrap();
    assert_eq!(
        tgt_val.to_f64().unwrap(),
        33.0,
        "bare OUT link must still write the value to the target"
    );
    // ...but the target must NOT have been processed.
    assert!(
        !visited.contains("TGT_OUT"),
        "bare OUT link (NPP) must NOT process its target: {visited:?}"
    );
}

/// BUG 2 regression (positive case) — an OUT link with an explicit
/// `PP` token DOES process a Passive target, mirroring C
/// `dbDbPutValue` `pvlOptPP` branch.
#[tokio::test]
async fn test_pp_out_link_processes_passive_target() {
    let db = PvDatabase::new();
    db.add_record("SRC_PP", Box::new(AoRecord::new(44.0)))
        .await
        .unwrap();
    db.add_record("TGT_PP", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();

    if let Some(rec) = db.get_record("SRC_PP").await {
        let mut inst = rec.write().await;
        inst.put_common_field("OUT", EpicsValue::String("TGT_PP.VAL PP".into()))
            .unwrap();
    }

    let mut visited = HashSet::new();
    db.process_record_with_links("SRC_PP", &mut visited, 0)
        .await
        .unwrap();

    assert!(
        visited.contains("TGT_PP"),
        "explicit PP OUT link must process its Passive target: {visited:?}"
    );
}

/// Formerly-bypassing path. A foreign full-processing entry
/// (`process_record_with_links`, the normal scan/event/FLNK-dispatch
/// caller) must block while a multi-record transaction holds the
/// member record's advisory write gate via `lock_records`. Before the
/// fix `process_record_with_links` took no gate, so a normal scan of a
/// member could interleave with a QSRV atomic group or pvalink atomic
/// scan epoch.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn mr_r5_foreign_process_blocks_on_held_epoch() {
    let db = PvDatabase::new();
    db.add_record("MR_R5_MEMBER", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();

    // Transaction owner holds the member's gate via `lock_records`.
    let epoch = db.lock_records(["MR_R5_MEMBER"]).await;

    let db2 = db.clone();
    let processed = Arc::new(AtomicU32::new(0));
    let processed2 = processed.clone();
    let h = tokio::spawn(async move {
        // Foreign full-processing entry — must block on the gate the
        // epoch holds.
        let mut visited = HashSet::new();
        let _ = db2
            .process_record_with_links("MR_R5_MEMBER", &mut visited, 0)
            .await;
        processed2.store(1, Ordering::SeqCst);
    });

    // Give the spawned task time to reach (and block on) the gate.
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    assert_eq!(
        processed.load(Ordering::SeqCst),
        0,
        "foreign process_record_with_links must block while a lock_records epoch holds the member gate"
    );

    drop(epoch);
    h.await.unwrap();
    assert_eq!(
        processed.load(Ordering::SeqCst),
        1,
        "foreign process must complete once the epoch is released"
    );
}

/// Owner path. A transaction owner holding a member's advisory
/// write gate via `lock_records` processes that member through the
/// `_already_locked` full-processing entry. The gate `Mutex` is not
/// reentrant, so using the gate-acquiring `process_record_with_links`
/// here would dead-lock the epoch against itself; the `_already_locked`
/// entry must complete without blocking.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn mr_r5_already_locked_process_does_not_self_deadlock() {
    let db = PvDatabase::new();
    db.add_record("MR_R5_OWNED", Box::new(AiRecord::new(0.0)))
        .await
        .unwrap();

    // Owner holds the member gate for the whole transaction.
    let _epoch = db.lock_records(["MR_R5_OWNED"]).await;

    // Processing the member via the `_already_locked` entry while the
    // epoch is held must NOT dead-lock — bounded by a timeout so a
    // regression (reverting to the gate-acquiring entry) fails loudly.
    let mut visited = HashSet::new();
    let res = tokio::time::timeout(
        std::time::Duration::from_secs(5),
        db.process_record_with_links_already_locked("MR_R5_OWNED", &mut visited, 0),
    )
    .await
    .expect("process_record_with_links_already_locked must not dead-lock under a held epoch");
    res.expect("owner-path processing of an owned member must succeed");
    assert!(visited.contains("MR_R5_OWNED"));
}

/// a CA link carries its `MS`/`NMS`/`MSI`/`MSS` modifier in
/// the parsed model, and record processing applies the maximize-severity
/// gate using that switch (uniform with DB links). The CA lset returns
/// the RAW remote alarm (severity + status); processing decides what to
/// fold. Tested by invariant boundary, not by narrative:
///
/// * NMS  → never propagate
/// * MS   → max severity, STAT = LINK_ALARM (remote stat NOT preserved)
/// * MSI  → propagate only when remote sevr == INVALID
/// * MSS  → max severity AND remote STAT preserved (the cited gap)
#[tokio::test]
async fn br_fr3_ca_link_applies_maximize_switch_at_processing() {
    use epics_base_rs::server::database::LinkSet;
    use epics_base_rs::server::recgbl::alarm_status;
    use epics_base_rs::server::record::AlarmSeverity;

    /// CA lset: connected, returns a configurable RAW remote alarm — it
    /// does NOT apply any MS/NMS gate itself (that is record processing's
    /// job for CA links now).
    struct RawCaLset {
        sevr: i32,
        stat: i32,
    }
    impl LinkSet for RawCaLset {
        fn is_connected(&self, _: &str) -> bool {
            true
        }
        fn get_value(&self, _: &str) -> Option<EpicsValue> {
            Some(EpicsValue::Double(7.0))
        }
        fn alarm_severity(&self, _: &str) -> Option<i32> {
            // Mirror the real CA resolver: only a non-zero severity is a
            // contribution worth returning.
            if self.sevr > 0 { Some(self.sevr) } else { None }
        }
        fn alarm_status(&self, _: &str) -> Option<i32> {
            Some(self.stat)
        }
    }

    // Process an ai record whose INP is `inp`, with the CA lset serving
    // the given raw remote (sevr, stat). Returns the record's resulting
    // (SEVR, STAT).
    async fn run(inp: &str, remote_sevr: i32, remote_stat: i32) -> (AlarmSeverity, u16) {
        let db = PvDatabase::new();
        db.register_link_set(
            "ca",
            Arc::new(RawCaLset {
                sevr: remote_sevr,
                stat: remote_stat,
            }),
        )
        .await;
        db.add_record("CADST", Box::new(AiRecord::new(0.0)))
            .await
            .unwrap();
        if let Some(rec) = db.get_record("CADST").await {
            let mut inst = rec.write().await;
            inst.put_common_field("INP", EpicsValue::String(inp.into()))
                .unwrap();
            inst.common.udf = false;
        }
        let mut visited = HashSet::new();
        db.process_record_with_links("CADST", &mut visited, 0)
            .await
            .unwrap();
        let rec = db.get_record("CADST").await.expect("record exists");
        let inst = rec.read().await;
        (inst.common.sevr, inst.common.stat)
    }

    // Remote: MAJOR severity, COMM_ALARM (9) status — distinct from
    // LINK_ALARM (14) so an MSS pass-through is observable.
    const REMOTE_STAT: i32 = alarm_status::COMM_ALARM as i32;

    // NMS — no propagation despite a connected MAJOR remote.
    let (sevr, _stat) = run("ca://REMOTE NMS", 2, REMOTE_STAT).await;
    assert_eq!(
        sevr,
        AlarmSeverity::NoAlarm,
        "NMS must not propagate the remote alarm"
    );

    // MS — lift to remote MAJOR, but surface as the generic LINK_ALARM.
    let (sevr, stat) = run("ca://REMOTE MS", 2, REMOTE_STAT).await;
    assert_eq!(sevr, AlarmSeverity::Major, "MS lifts SEVR to remote MAJOR");
    assert_eq!(
        stat,
        alarm_status::LINK_ALARM,
        "MS surfaces as LINK_ALARM, not the remote STAT"
    );

    // MSS — lift severity AND adopt the remote STAT (the cited gap).
    let (sevr, stat) = run("ca://REMOTE MSS", 2, REMOTE_STAT).await;
    assert_eq!(sevr, AlarmSeverity::Major, "MSS lifts SEVR to remote MAJOR");
    assert_eq!(
        stat,
        alarm_status::COMM_ALARM,
        "MSS must preserve the remote STAT code, not collapse to LINK_ALARM"
    );

    // MSI with a non-INVALID (MAJOR) remote — must NOT propagate.
    let (sevr, _stat) = run("ca://REMOTE MSI", 2, REMOTE_STAT).await;
    assert_eq!(
        sevr,
        AlarmSeverity::NoAlarm,
        "MSI ignores a non-INVALID remote alarm"
    );

    // MSI with an INVALID remote — inherits as LINK_ALARM + INVALID.
    let (sevr, stat) = run("ca://REMOTE MSI", 3, REMOTE_STAT).await;
    assert_eq!(
        sevr,
        AlarmSeverity::Invalid,
        "MSI inherits an INVALID remote alarm"
    );
    assert_eq!(stat, alarm_status::LINK_ALARM, "MSI surfaces as LINK_ALARM");
}

// lsi/lso `menuPost` MPST/APST "Always" mode.
//
// After fix 9587929c an unchanged lsi/lso process cycle posts NO
// VALUE/LOG monitor (C `lsiRecord.c`/`lsoRecord.c` monitor gate on
// `len != olen || memcmp(oval, val, len)`). The MPST/APST menu fields
// restore C's override: an unchanged cycle still posts DBE_VALUE when
// MPST == menuPost_Always and DBE_LOG when APST == menuPost_Always
// (lsiRecord.c:217-220). This test drives an unchanged cycle through
// the link-processing path and asserts the VALUE event fires only when
// MPST is Always.
#[tokio::test]
async fn test_lsi_mpst_always_posts_value_on_unchanged_cycle() {
    use epics_base_rs::server::recgbl::EventMask;
    use epics_base_rs::server::records::lsi::LsiRecord;
    use epics_base_rs::types::DbFieldType;

    async fn unchanged_cycle_posts_value(mpst_always: bool) -> bool {
        let db = PvDatabase::new();
        db.add_record("LSI_MPST", Box::new(LsiRecord::new("hello")))
            .await
            .unwrap();
        if mpst_always {
            // MPST = menuPost_Always (1).
            let rec = db.get_record("LSI_MPST").await.unwrap();
            let mut inst = rec.write().await;
            inst.record.put_field("MPST", EpicsValue::Short(1)).unwrap();
        }

        // Cycle 1 commits oval/olen for the seeded "hello", so cycle 2 is
        // genuinely unchanged (value_changed == false).
        let mut visited = HashSet::new();
        db.process_record_with_links("LSI_MPST", &mut visited, 0)
            .await
            .unwrap();

        // Subscribe to VAL AFTER cycle 1.
        let mut val_rx = {
            let rec = db.get_record("LSI_MPST").await.unwrap();
            let mut inst = rec.write().await;
            inst.add_subscriber("VAL", 71, DbFieldType::Char, EventMask::VALUE.bits())
        }
        .expect("VAL subscription must be accepted");

        // Cycle 2: no new value. Without MPST this posts nothing; with
        // MPST == Always it must still post a DBE_VALUE event.
        let mut visited = HashSet::new();
        db.process_record_with_links("LSI_MPST", &mut visited, 0)
            .await
            .unwrap();

        val_rx.try_recv().is_ok()
    }

    assert!(
        unchanged_cycle_posts_value(true).await,
        "MPST == Always must post a VALUE monitor on an unchanged lsi cycle"
    );
    assert!(
        !unchanged_cycle_posts_value(false).await,
        "MPST == OnChange (default) must NOT post a VALUE monitor on an unchanged lsi cycle"
    );
}