epics-base-rs 0.24.3

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
use std::future::Future;

pub mod db_access;
mod field_io;
pub mod filters;
mod link_set;
mod links;
mod processing;
mod record_lock;
mod scan_index;

pub use link_set::{
    DynLinkSet, LinkDbfType, LinkMetadata, LinkPutOp, LinkSet, LinkSetRegistry, RemoteAlarm,
};
pub use processing::{AsyncDbHandle, AsyncToken};
pub use record_lock::{ManyRecordWriteGuard, RecordWriteGuard};

use crate::error::{CaError, CaResult};
use crate::runtime::sync::RwLock;
use std::collections::{BTreeSet, HashMap};
use std::sync::Arc;

use crate::server::pv::ProcessVariable;
use crate::server::record::{Record, RecordInstance, ScanList};
use crate::types::EpicsValue;

/// What a `.db` definition carries into the creation sink alongside the record
/// itself: the `dbCommon` fields `db_loader::apply_fields` could not route to
/// the record's own `field_list`, and the record's `info(...)` tags.
///
/// It exists so that [`PvDatabase::add_loaded_record`] receives a record's
/// COMPLETE loaded state in one call. A caller cannot add the record and then
/// apply its `.db` fields, because the sink runs C's `iocInit` passes — whose
/// result depends on those fields — before the record is reachable at all.
#[derive(Default, Debug, Clone)]
pub struct RecordLoad {
    /// `dbCommon` fields, in `.db` file order (a later `field(UDF,…)` wins).
    pub common_fields: Vec<(String, EpicsValue)>,
    /// `info(key, "value")` tags.
    pub info_tags: Vec<(String, String)>,
}

impl RecordLoad {
    /// The common fields alone — the shape every `.db` loader path produces
    /// from [`crate::server::db_loader::apply_fields`].
    pub fn from_common_fields(common_fields: Vec<(String, EpicsValue)>) -> Self {
        Self {
            common_fields,
            info_tags: Vec::new(),
        }
    }
}

/// Parse a PV name into (base_name, field_name).
/// "TEMP.EGU" → ("TEMP", "EGU")
/// "TEMP"     → ("TEMP", "VAL")
pub fn parse_pv_name(name: &str) -> (&str, &str) {
    match name.rsplit_once('.') {
        Some((base, field)) => (base, field),
        None => (name, "VAL"),
    }
}

/// C `dbIsValueField` (`dbAccess.c:463-469`): is this field the record
/// type's *value* field?
///
/// A record type's value field is the one the DBD names `VAL` — the DBD
/// parser records exactly that field's index as `indvalFlddes`
/// (`dbLexRoutines.c:777-780`), which is what `dbIsValueField` compares
/// against. Metadata that C/pvxs apply "to VAL only" (e.g. QSRV's
/// `Q:form` → `display.form.index`, `iocsource.cpp:53`) key on this
/// predicate, so it lives beside [`parse_pv_name`], whose `"REC"` → `VAL`
/// default is the other half of the same rule.
pub fn is_value_field(field: &str) -> bool {
    field.eq_ignore_ascii_case("VAL")
}

/// Apply timestamp to a record based on its TSE field.
/// `is_soft` indicates a Soft Channel device type.
///
/// Mirrors C `recGblGetTimeStampSimm` (recGbl.c:310-343). The TSE
/// constants are defined in `epicsTime.h:102-104`:
///
///   - `epicsTimeEventCurrentTime = 0` → wall-clock now
///   - `epicsTimeEventBestTime    = -1` → generalTime BestTime providers
///   - `epicsTimeEventDeviceTime  = -2` → device support already set time
///   - `1..` → event-number providers
///
/// The C path is symmetric: every non-`-2` case unconditionally
/// overwrites `precord->time` via `epicsTimeGetEvent(tse)`, which
/// delegates to `epicsTimeGetCurrent` for `tse==0` and to
/// `generalTimeGetEventPriority` otherwise. Only `-2` (device time)
/// is left untouched because the device support has already written
/// the timestamp before `recGblGetTimeStamp` is called.
fn apply_timestamp(common: &mut super::record::CommonFields, _is_soft: bool) {
    // Single owner of TSE -> TIME resolution; device support that must
    // format the record's resolved time during `read()` routes through the
    // same helper so the two never drift (see `recgbl::get_time_stamp`).
    // For TSE=-2 the helper returns `common.time` unchanged, preserving the
    // device-time "leave it alone" semantics.
    common.time = crate::server::recgbl::get_time_stamp(common.tse, common.time);
}

/// Unified entry in the PV database.
pub enum PvEntry {
    Simple(Arc<ProcessVariable>),
    Record(Arc<RwLock<RecordInstance>>),
}

/// Callback for resolving external PV names (CA/PVA links).
/// Returns the current value of the external PV, or None if unavailable.
///
/// **Async**, for the same reason [`LinkSet`] is: an external link's value
/// lives on a tokio runtime, and a sync closure could only reach it through a
/// blocking bridge that panics on a current-thread runtime. The one caller
/// ([`PvDatabase::resolve_external_pv`]) is already async.
pub type ExternalPvResolver = Arc<
    dyn for<'a> Fn(
            &'a str,
        )
            -> std::pin::Pin<Box<dyn Future<Output = Option<EpicsValue>> + Send + 'a>>
        + Send
        + Sync,
>;

/// Async hook invoked by [`PvDatabase::has_name`] when a name is not yet
/// in the database. Used by the CA gateway and similar proxy components
/// to lazily populate PVs on first search.
///
/// The resolver should:
/// 1. Determine whether the name should be served (e.g., check ACL)
/// 2. Take whatever action is needed to make `has_name` return true on
///    a subsequent call (e.g., subscribe to an upstream IOC and call
///    `add_pv` with a placeholder value)
/// 3. Return `true` if the name is now resolvable, `false` otherwise
///
/// Returning `true` causes `has_name` to re-check the database. The
/// resolver may take some time (TCP search, upstream connect handshake);
/// the caller (UDP search responder, TCP CREATE_CHANNEL handler) will
/// `.await` it.
/// The second argument is the downstream client's socket address when
/// the lookup originates from a CA/PVA search or channel-create on
/// behalf of an identified peer (`None` for host-less internal lookups:
/// preload, iocsh, link processing). the CA gateway needs
/// this to evaluate `.pvlist` `DENY FROM host` rules at search time, the
/// way C ca-gateway's `pvExistTest` passes the client host to
/// `gateAs::findEntry`.
pub type SearchResolver = Arc<
    dyn Fn(
            String,
            Option<std::net::SocketAddr>,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send>>
        + Send
        + Sync,
>;

/// Per-request admission gate for an **already-registered** simple PV.
///
/// A plain IOC's simple PVs are authoritative: once registered they
/// exist unconditionally, so no gate is installed and the cached-PV
/// short-circuit in [`PvDatabase::find_entry_from`] /
/// [`PvDatabase::has_name_from`] is unchanged. A CA gateway is
/// different — its shadow PVs are projections of an upstream that can be
/// host-denied for a given requester or disconnected — so it installs a
/// gate that the lookup path consults *before* returning a cached simple
/// PV. Returning `false` makes the database answer "does not exist" for
/// that requester, exactly as C ca-gateway's `pvExistTest` returns
/// `pverDoesNotExistHere` for a host-denied or disconnected PV
/// (`gateServer.cc:1516-1637`) — without removing the PV object, so its
/// cached value stays available for diagnostics and re-admission.
///
/// The first argument is the filter-suffix-stripped record path (the
/// same key the simple-PV map and the gateway cache use); the second is
/// the requesting peer (`None` for host-less internal lookups). The gate
/// governs **only** simple PVs — records and aliases are never
/// gateway-managed and bypass it.
pub type ExistenceGate = Arc<
    dyn Fn(
            String,
            Option<std::net::SocketAddr>,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send>>
        + Send
        + Sync,
>;

/// Internal state of [`PvDatabase`].
///
/// # Invariant — alias-aware lookup (epics-base PR #336)
///
/// **MUST**: every record-name lookup that originates from an
/// external API (CA/PVA server, link processing, iocsh, bridge
/// providers) MUST go through [`PvDatabase::get_record`] /
/// [`PvDatabase::find_entry`] / [`PvDatabase::has_name`], never
/// `inner.records.read().await.get(...)` directly.
///
/// **MUST NOT**: a function that takes an arbitrary record-name
/// `&str` and reads `inner.records` directly, unless one of:
/// - the function is itself an alias-management primitive
///   (`add_record`, `remove_record`, `add_alias`,
///   `find_entry_no_resolve`, `has_name_no_resolve`,
///   `get_record_no_resolve`, `all_record_names`), OR
/// - the name has been normalised to canonical earlier in the
///   same scope (the `let canonical_owned; let name: &str = ...`
///   pattern in `process_record_with_links_inner` /
///   `complete_async_record_inner` / `put_record_field_from_ca` /
///   `put_pv`).
///
/// **Owner/Gate:** `PvDatabase::get_record` (alias-aware path).
///
/// New code that adds a record-name entry point should call
/// `get_record` first OR run the canonical-normalisation snippet
/// at function entry. Direct `inner.records` access is reserved
/// for the alias-management primitives listed above.
/// One CP/CPP edge in the [`PvDatabaseInner::cp_links`] index: the record
/// to (re)process when the source record changes.
///
/// `passive_only` distinguishes CPP from CP. C adds the `CA_DBPROCESS`
/// action for a CP link unconditionally, but for a CPP link only when the
/// link-holding record's `SCAN` is Passive (`dbCa.c:854,994,1072`). CP
/// edges clear the flag; CPP edges set it, and `dispatch_cp_targets`
/// honours it.
#[derive(Clone, Debug)]
pub struct CpTarget {
    pub record: String,
    pub passive_only: bool,
}

struct PvDatabaseInner {
    simple_pvs: RwLock<HashMap<String, Arc<ProcessVariable>>>,
    records: RwLock<HashMap<String, Arc<RwLock<RecordInstance>>>>,
    /// Scan index: maps scan type → sorted set of
    /// `(PHAS, load_order, record_name)`.
    ///
    /// C parity (`dbScan.c:1052-1095`): `buildScanLists` walks records
    /// in database / record-type **load order** and `addToList`
    /// inserts each after the last element with `phas <= precord->phas`
    /// — so within one PHAS value the scan list is a stable FIFO in
    /// load order. The secondary sort key is the per-record
    /// `load_order` sequence (NOT the record name), so two records
    /// sharing a PHAS scan in the order they were loaded, matching a
    /// C IOC built from the same `.db` file.
    /// Keyed by [`ScanList`], not `ScanType`: a `Passive` or illegal SCAN names
    /// no list (C `scanAdd`, dbScan.c:241-251) and so cannot be a key at all.
    scan_index: RwLock<HashMap<ScanList, BTreeSet<(i16, u64, String)>>>,
    /// Per-record load-order sequence number, assigned monotonically
    /// at `add_record`. Used as the secondary scan-index sort key so
    /// same-PHAS records preserve database load order. Survives a
    /// `remove_record` + re-`add_record` (the re-add gets a fresh,
    /// higher sequence — matching a fresh `.db` reload).
    load_order: RwLock<HashMap<String, u64>>,
    /// Monotonic counter feeding `load_order`.
    load_order_counter: std::sync::atomic::AtomicU64,
    /// CP/CPP link index: maps source_record → target edges to process when
    /// the source changes. Each edge carries the CP-vs-CPP distinction (see
    /// [`CpTarget`]).
    cp_links: RwLock<HashMap<String, Vec<CpTarget>>>,
    /// External (CA/PVA) CP/CPP link index: maps the *external PV name*
    /// (the cross-IOC source, e.g. `OTHER:PV` from `INP="OTHER:PV CP"`)
    /// → holder edges to process when that remote PV changes. The local
    /// [`Self::cp_links`] index is keyed by a local source RECORD that
    /// processes here; a cross-IOC source never processes locally, so its
    /// only trigger is the calink/pvalink CA monitor callback, which calls
    /// [`PvDatabase::dispatch_external_cp_targets`]. Parity with C
    /// `dbCa.c:993-994` `eventCallback` adding `CA_DBPROCESS`.
    external_cp_links: RwLock<HashMap<String, Vec<CpTarget>>>,
    /// Alias map: alternate-name → real-record-name. Mirrors epics-base
    /// PR #336 (alias name validation + parsing). `find_entry` and
    /// related lookups consult this map after the canonical record
    /// table so an alias resolves transparently to its target.
    aliases: RwLock<HashMap<String, String>>,
    /// Single gate that serializes
    /// every `add_pv` / `add_pv_with_hook` / `add_record` /
    /// `add_alias` / `remove_record` / `remove_simple_pv` /
    /// `remove_alias`. Without this, the per-method write-lock
    /// orders (`simple_pvs` first vs. `records` first vs.
    /// `aliases` first) could deadlock under concurrent registrations,
    /// and `add_record`'s post-insert `scan_index.write()` had a
    /// TOCTOU window where `remove_record` could land between the
    /// records map insert and the scan-index insert and leave a
    /// phantom scan entry.
    ///
    /// Holding this mutex makes the cross-namespace `check_name_free`
    /// peek atomic with the target-map insert, eliminates the
    /// scan-index race, and lets `remove_*` purge dangling aliases
    /// without a second pass.
    registration_mutex: tokio::sync::Mutex<()>,
    /// The IOC lifecycle phase — the port's `iocInit` boundary. See
    /// [`DbInitPhase`], [`PvDatabase::begin_load`],
    /// [`PvDatabase::schedule_record_init`] and [`PvDatabase::ioc_init`].
    init_phase: std::sync::Mutex<DbInitPhase>,
    /// Lines queued by the iocsh `afterIocRunning <command>` directive
    /// (epics-base PR #558). Drained by the IOC application after PINI
    /// completes, then re-executed through a fresh IocShell so the
    /// commands run with the database in its post-init state.
    after_ioc_running: std::sync::Mutex<Vec<String>>,
    /// Optional resolver for external PVs (ca://, pva:// links).
    external_resolver: RwLock<Option<ExternalPvResolver>>,
    /// Optional async resolver invoked on `has_name` misses (e.g. CA gateway).
    search_resolver: RwLock<Option<SearchResolver>>,
    /// Optional per-request gate consulted before a *cached* simple PV is
    /// advertised as existing (e.g. CA gateway host/state admission). See
    /// [`ExistenceGate`]. `None` for a plain IOC (short-circuit unchanged).
    existence_gate: RwLock<Option<ExistenceGate>>,
    /// Per-scheme link sets — pluggable backends for `pva://` /
    /// `ca://` link resolution. Consulted before the legacy
    /// [`ExternalPvResolver`] in [`Self::resolve_external_pv`].
    /// Mirrors the C-EPICS lset abstraction.
    link_sets: RwLock<link_set::LinkSetRegistry>,
    /// True once the ScanScheduler has been started for this DB.
    /// Prevents duplicate scan tasks when multiple protocol servers (CA + PVA)
    /// both try to start scanning on the same DB.
    scan_started: std::sync::atomic::AtomicBool,
    /// True once PINI processing has completed. Non-owner schedulers await
    /// this before running their hooks, preserving the "PINI before hooks"
    /// ordering contract.
    pini_done: std::sync::atomic::AtomicBool,
    /// Fired by the scan owner after PINI completes. Non-owners register
    /// interest on this before re-checking `pini_done` to avoid missing the
    /// signal (`notify_waiters` does not store a permit).
    pini_notify: tokio::sync::Notify,
    /// Per-record advisory write gates — the Rust
    /// counterpart of the C-EPICS `dbScanLock` / `dbLocker`
    /// machinery. Every plain CA/PVA write, the QSRV atomic group
    /// PUT/GET, and the pvalink atomic scan-on-update epoch all
    /// acquire these gates, so no two of them can interleave on a
    /// shared record. See [`record_lock`].
    record_locks: record_lock::RecordLockRegistry,
    /// Subroutine functions by name, retained at runtime so the processing
    /// path can re-resolve an aSub's subroutine when its name changes
    /// (C `aSubRecord.c::fetch_values` `registryFunctionFind`, LFLG=READ /
    /// SUBL). Populated once at iocInit from the IocApp/IocBuilder registry;
    /// read-only thereafter.
    subroutine_registry: RwLock<HashMap<String, Arc<crate::server::record::SubroutineFn>>>,
    /// Breakpoint tables by name (C `bptList`), shared by every db-load path so
    /// `ai`/`ao` records with `LINR >= 3` resolve their linearisation table. An
    /// `Arc` snapshot is installed on each record at creation; the master grows
    /// (copy-on-write via [`PvDatabase::add_breaktables`]) as `dbLoadRecords`
    /// loads more `breaktable(...)` definitions, so build-time and runtime
    /// loads share one registry.
    breaktable_registry: RwLock<Arc<crate::server::cvt_bpt::BreakTableRegistry>>,
}

/// Database of all process variables hosted by this server.
#[derive(Clone)]
pub struct PvDatabase {
    inner: Arc<PvDatabaseInner>,
}

/// A record initialisation owed to `iocInit` — the port's `init_record`
/// tail. Built by a record's `refresh_link_status` and handed to
/// [`PvDatabase::schedule_record_init`].
type RecordInit = std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'static>>;

/// The IOC lifecycle phase, and with it the answer to "may a record's links be
/// classified against the database as it stands right now?".
///
/// C runs `init_record` — where a record classifies its links (`checkLinks`,
/// `dbNameToAddr`) — from `iocInit`, i.e. after EVERY `dbLoadRecords` block
/// has been read. A forward reference across two `dbLoadRecords` calls in one
/// `st.cmd` is therefore a LOCAL link, deterministically, and the classified
/// value is final the moment `iocInit` returns (`dbgf` is refused before it).
///
/// The boundary is `iocInit`, NOT a load group: gating on the load group left
/// the multi-`dbLoadRecords` case every real `st.cmd` uses racing 9-in-15
/// (R18-92). So the phase here is an ioc-lifecycle state.
///
/// # The lifecycle is ONE-WAY: `Unloaded → Loading → Running`
///
/// R18-92 modelled it with two states, `Loading` and `Complete`, where
/// `Complete` meant BOTH "never loaded" and "iocInit has run" — so `begin_load`
/// needed a `Complete → Loading` arm to open the phase at all, and that arm ran
/// on a post-iocInit load too. One `dbLoadRecords` typed after `iocInit` then
/// re-armed the queue that only `ioc_init` drains, and every later
/// classification — including every runtime `special()` link re-point — was
/// pushed into a `Vec` nothing polls (R19-62, measured: `iocInit;
/// dbLoadRecords(b.db); dbpf CO.INPA "9.5"` froze `CO.INAV` at 0).
///
/// Splitting the two meanings is what closes it: `Loading` is now produced ONLY
/// from `Unloaded`, so no function in the crate can transition backwards out of
/// `Running`. The one-way-ness is a property of the transitions that exist, not
/// of a runtime check.
enum DbInitPhase {
    /// No load has begun. `iocInit` is owed nothing, so a classification runs
    /// immediately — a programmatically built or unit-test database.
    Unloaded,
    /// Between the first `dbLoadRecords`/builder load and `iocInit`; holds the
    /// classifications owed, in issue order. A half-built database is never
    /// observed, because no classification code runs against one.
    Loading(Vec<RecordInit>),
    /// `iocInit` has run: the database is final and every link status is
    /// classified. A classification issued now runs immediately, which is what a
    /// runtime re-point (`special()` on a link field) needs. TERMINAL — nothing
    /// re-opens the load phase.
    Running,
}

/// [`PvDatabase::begin_load`] was called on a database whose `iocInit` has
/// already run — C's `getIocState() != iocVoid` (R19-63).
///
/// The `Display` text is C's `errSymMsg(S_dbLib_postInitRecRegister)` verbatim
/// (`dbStaticLib.h:269`), which is what `dbCreateRecord` prints:
///
/// ```text
/// epics> dbCreateRecord(pdbbase,"ai","NEWREC")
/// ERROR: 33554463 IOC already initialized - No new records can be added
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IocAlreadyInitialized;

impl std::fmt::Display for IocAlreadyInitialized {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("IOC already initialized - No new records can be added")
    }
}

impl std::error::Error for IocAlreadyInitialized {}

/// Which record kind a SELM link selection is being computed for.
/// The Specified/Mask base differs between record types in C, so the
/// shared selector must know the caller.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum SelmKind {
    /// `fanout` / `seq`: Specified index is `SELN + OFFS` (0-based over
    /// LNK0..LNKF / group 0..15); Mask is shifted by `SHFT`.
    /// Mirrors `fanoutRecord.c:106-141` and `seqRecord.c:147-178`.
    FanoutSeq,
    /// `dfanout`: Specified index is `SELN - 1` (1-based, `SELN==0`
    /// means "drive nothing", `SELN > OUT_ARG_MAX` is invalid); Mask
    /// has NO `SHFT` and `SELN==0` means "no output".
    /// Mirrors `dfanoutRecord.c:307-339`.
    Dfanout,
}

/// Result of resolving a SELM/SELN selection.
#[derive(Clone, Debug, Default)]
pub(crate) struct SelmResult {
    /// 0-based link indices to drive (into the LNK0../OUTA.. array).
    pub indices: Vec<usize>,
    /// `Some` when C would raise an alarm for an out-of-range
    /// `SELN`/`OFFS`/`SHFT`. C uses `recGblSetSevr(prec, SOFT_ALARM,
    /// INVALID_ALARM)` in every such path.
    pub alarm: Option<(u16, crate::server::record::AlarmSeverity)>,
}

/// Convert a link value to `epicsUInt16` with C `dbGetLink(.., DBR_USHORT,
/// ..)` semantics, for the fanout/dfanout/seq `SELL`→`SELN` read — so a
/// constant, DB, CA, or PVA link source all convert by the one rule C applies
/// through `dbFastGetConvertRoutine`.
///
/// # The source type decides the rule, because in C it decides the routine
///
/// `dbFastGetConvertRoutine` is a 2-D table indexed by *both* the source DBF
/// and the destination DBR (`dbConvert.c:1571-1638`): a `DBF_LONG` source
/// reaches `getLongUshort`, a `DBF_DOUBLE` source reaches `getDoubleUshort`.
/// They are different functions, and C gives them different semantics:
///
/// * **Integer source** — `(epicsUInt16)(epicsInt32)v`. Conversion of an
///   out-of-range *integer* to an unsigned type is **defined** in C
///   (C17 6.3.1.3p2: reduce modulo `USHRT_MAX + 1`). Every compiler and
///   every target agrees, so this is a real contract and the port keeps it:
///   `SELL` pointing at a `DBF_LONG` field holding `-1` gives `SELN = 65535`.
/// * **Float source** — `(epicsUInt16)d`. Conversion of an out-of-range
///   *float* is **undefined** (C17 6.3.1.4p1), so compiled C is not
///   single-valued: x86-64 wraps, aarch64 saturates. What the port does about
///   that is [`crate::types::c_cast`]'s call — the single owner of the policy —
///   and deliberately not restated here.
///
/// Both rules already live in [`EpicsValue::convert_to`], the single
/// value-coercion owner: it takes the integer view (`as_int_i64`) when the
/// source has one and falls back to `c_cast` only for a genuine float. So this
/// is a thin projection onto that owner, NOT a second conversion table.
///
/// The previous revision called `c_cast::f64_to_u16(value.to_f64())` directly,
/// bypassing the owner — which silently applied the float rule to integer
/// sources too, losing the one wrap C actually defines.
pub(crate) fn dbr_ushort_cast(value: &EpicsValue) -> u16 {
    match value.convert_to(crate::types::DbFieldType::UShort) {
        EpicsValue::UShort(v) => v,
        // A link that delivers an array converts element-wise; C's
        // `dbGetLink(.., &prec->seln, 0, 0)` requests ONE element, so SELN
        // takes the first (an empty array leaves it 0).
        EpicsValue::UShortArray(v) => v.first().copied().unwrap_or(0),
        // `convert_to(UShort)` returns no other variant.
        _ => 0,
    }
}

/// Select which link indices are active based on SELM/SELN, applying
/// the record-type-specific `OFFS`/`SHFT` bias.
///
/// SELM: 0 = All, 1 = Specified, 2 = Mask. `count` is the number of
/// link slots (16 for fanout/dfanout/seq).
///
/// `seln` is the native `DBF_USHORT` value: C declares `SELN` as
/// `epicsUInt16`, so every comparison below is unsigned, matching C's
/// selection arithmetic — never `-1`. What an out-of-range `SELL` converts
/// *to* is [`dbr_ushort_cast`]'s decision, not this function's.
///
/// C references:
/// * fanout — `fanoutRecord.c:106-141`
/// * dfanout — `dfanoutRecord.c:307-339`
/// * seq — `seqRecord.c:147-178`
pub(crate) fn select_link_indices_ex(
    kind: SelmKind,
    selm: i16,
    seln: u16,
    offs: i16,
    shft: i16,
    count: usize,
) -> SelmResult {
    use crate::server::recgbl::alarm_status::SOFT_ALARM;
    use crate::server::record::AlarmSeverity;

    let invalid = || SelmResult {
        indices: Vec::new(),
        alarm: Some((SOFT_ALARM, AlarmSeverity::Invalid)),
    };
    let ok = |indices: Vec<usize>| SelmResult {
        indices,
        alarm: None,
    };

    match selm {
        // All — every slot.
        0 => ok((0..count).collect()),
        // Specified.
        1 => match kind {
            SelmKind::FanoutSeq => {
                // C: `i = seln + offs;` with `seln` unsigned (epicsUInt16),
                // 0-based; `i<0 || i>=NLINKS` → INVALID. So `SELN=65535`
                // (from `SELL=-1`) yields `i>=NLINKS` → INVALID, never
                // drives link 0.
                let i = seln as i32 + offs as i32;
                if i < 0 || i >= count as i32 {
                    invalid()
                } else {
                    ok(vec![i as usize])
                }
            }
            SelmKind::Dfanout => {
                // C `dfanoutRecord.c:315-320`: `if (prec->seln > OUT_ARG_MAX)`
                // with `seln` unsigned → INVALID; `seln == 0` → no output;
                // otherwise drive `seln - 1`. OFFS is not a dfanout field.
                // `SELL=-1` → `SELN=65535` > count → INVALID (the signed
                // read used to see `-1`, take the `<= 0` branch, and drive
                // nothing with no alarm).
                let seln_i = seln as i32;
                if seln_i > count as i32 {
                    invalid()
                } else if seln_i == 0 {
                    ok(Vec::new())
                } else {
                    ok(vec![(seln_i - 1) as usize])
                }
            }
        },
        // Mask.
        2 => {
            let mask: u32 = match kind {
                SelmKind::FanoutSeq => {
                    // C: SHFT shift first, with `shft` range-checked to [-15,15].
                    if !(-15..=15).contains(&shft) {
                        return invalid();
                    }
                    let raw = seln as u32;
                    if shft >= 0 {
                        raw >> shft
                    } else {
                        raw << (-shft)
                    }
                }
                // dfanout Mask has no SHFT.
                SelmKind::Dfanout => seln as u32,
            };
            ok((0..count).filter(|i| mask & (1 << i) != 0).collect())
        }
        // Any other SELM value → C `default:` raises INVALID.
        _ => invalid(),
    }
}

impl PvDatabase {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(PvDatabaseInner {
                simple_pvs: RwLock::new(HashMap::new()),
                external_resolver: RwLock::new(None),
                search_resolver: RwLock::new(None),
                existence_gate: RwLock::new(None),
                link_sets: RwLock::new(link_set::LinkSetRegistry::new()),
                records: RwLock::new(HashMap::new()),
                scan_index: RwLock::new(HashMap::new()),
                load_order: RwLock::new(HashMap::new()),
                load_order_counter: std::sync::atomic::AtomicU64::new(0),
                cp_links: RwLock::new(HashMap::new()),
                external_cp_links: RwLock::new(HashMap::new()),
                aliases: RwLock::new(HashMap::new()),
                registration_mutex: tokio::sync::Mutex::new(()),
                init_phase: std::sync::Mutex::new(DbInitPhase::Unloaded),
                after_ioc_running: std::sync::Mutex::new(Vec::new()),
                scan_started: std::sync::atomic::AtomicBool::new(false),
                pini_done: std::sync::atomic::AtomicBool::new(false),
                pini_notify: tokio::sync::Notify::new(),
                record_locks: record_lock::RecordLockRegistry::default(),
                subroutine_registry: RwLock::new(HashMap::new()),
                breaktable_registry: RwLock::new(Arc::new(
                    crate::server::cvt_bpt::BreakTableRegistry::new(),
                )),
            }),
        }
    }

    /// Merge `tables` into the shared breakpoint-table registry (C `bptList`
    /// accumulation across `dbLoadDatabase`/`dbLoadRecords`) and return the new
    /// snapshot. Copy-on-write: a new merged registry replaces the old one.
    ///
    /// `add_breaktables` is the single registry-mutation owner, so it also
    /// restores the invariant *every record can resolve against the current
    /// registry* on mutation: the new snapshot is re-installed into every
    /// existing record. That covers a record created before its table was
    /// loaded (an inline record added before `dbLoadRecords`, or a merge-reload
    /// that repoints `LINR` to a table loaded in the same command) — neither
    /// of which goes back through `add_record`'s install. `install_*` is a
    /// no-op for non-ai/ao records and resets the cached table so the new
    /// registry wins. Returns the current snapshot unchanged when `tables` is
    /// empty (no mutation, so no re-install).
    pub async fn add_breaktables(
        &self,
        tables: Vec<crate::server::cvt_bpt::BrkTable>,
    ) -> Arc<crate::server::cvt_bpt::BreakTableRegistry> {
        // Hold the registration gate across the registry write AND the record
        // snapshot below so this mutation cannot interleave with `add_record`'s
        // [registry read -> records-map insert] — both are gated by the same
        // mutex. Without it a record created concurrently could read the
        // pre-mutation registry (miss the just-loaded table) while not yet
        // being in the records map for the re-install below, leaving a
        // table-not-found alarm until the next load / LINR put. `add_record`
        // holds this gate across its whole body (registry read + map insert),
        // so taking it here closes that TOCTOU window. No `add_breaktables`
        // caller already holds the gate, so this is reentrancy-safe.
        let _gate = self.inner.registration_mutex.lock().await;
        let snapshot = {
            let mut guard = self.inner.breaktable_registry.write().await;
            if tables.is_empty() {
                return guard.clone();
            }
            let mut next = (**guard).clone();
            for table in tables {
                next.insert(table);
            }
            let snapshot = Arc::new(next);
            *guard = snapshot.clone();
            snapshot
        };
        // Re-install into existing records. Snapshot the instance handles
        // under a brief read, then release the map lock BEFORE taking any
        // per-record write lock — collect-then-act, keeping the invariant
        // "never hold the records-map lock across a per-record lock" uniform
        // across the codebase (a7f5a74f). This is defensive: no current path
        // takes the per-record lock then the records-map lock, so there is no
        // confirmed cycle; uniform order forecloses one. Same idiom as
        // `all_record_names`. (The registry write lock was released above.)
        let instances: Vec<_> = self.inner.records.read().await.values().cloned().collect();
        for inst in instances {
            inst.write()
                .await
                .record
                .install_breaktable_registry(snapshot.clone());
        }
        snapshot
    }

    /// Install the by-name subroutine registry, retained for runtime
    /// re-resolution (aSub LFLG=READ / SUBL). Called once at iocInit with the
    /// IocApp/IocBuilder registry. See [`Self::find_subroutine_named`].
    pub async fn install_subroutine_registry(
        &self,
        registry: HashMap<String, Arc<crate::server::record::SubroutineFn>>,
    ) {
        *self.inner.subroutine_registry.write().await = registry;
    }

    /// Look up a registered subroutine by name. The processing path uses this
    /// to re-resolve an aSub's subroutine when SNAM changes (C `fetch_values`
    /// `registryFunctionFind`). `None` when the name is not registered, which
    /// the caller treats as C's `S_db_BadSub` (skip running the subroutine).
    pub(crate) async fn find_subroutine_named(
        &self,
        name: &str,
    ) -> Option<Arc<crate::server::record::SubroutineFn>> {
        self.inner
            .subroutine_registry
            .read()
            .await
            .get(name)
            .cloned()
    }

    /// Atomically claim the right to start the scan scheduler for this DB.
    /// Returns `true` on the first call, `false` on subsequent calls.
    /// Used by `ScanScheduler::run_with_hooks` to prevent duplicate scan tasks
    /// when multiple protocol servers (CA + PVA) both try to start scanning.
    pub fn try_claim_scan_start(&self) -> bool {
        self.inner
            .scan_started
            .compare_exchange(
                false,
                true,
                std::sync::atomic::Ordering::AcqRel,
                std::sync::atomic::Ordering::Acquire,
            )
            .is_ok()
    }

    /// Mark PINI processing complete. Wakes any non-owner scan schedulers
    /// that were waiting before running their hooks.
    pub fn mark_pini_done(&self) {
        self.inner
            .pini_done
            .store(true, std::sync::atomic::Ordering::Release);
        self.inner.pini_notify.notify_waiters();
    }

    /// Wait until the scan owner has completed PINI processing.
    /// Returns immediately if PINI has already completed.
    pub async fn wait_for_pini(&self) {
        if self
            .inner
            .pini_done
            .load(std::sync::atomic::Ordering::Acquire)
        {
            return;
        }
        // Register interest BEFORE re-checking the flag to avoid missing a
        // signal that arrives between the load and the await — `notify_waiters`
        // does not store a permit for late subscribers.
        let notified = self.inner.pini_notify.notified();
        if self
            .inner
            .pini_done
            .load(std::sync::atomic::Ordering::Acquire)
        {
            return;
        }
        notified.await;
    }

    /// Install an async resolver invoked when [`PvDatabase::has_name`]
    /// fails to find a name. Used by proxy/gateway implementations to
    /// lazily populate PVs on first search.
    pub async fn set_search_resolver(&self, resolver: SearchResolver) {
        *self.inner.search_resolver.write().await = Some(resolver);
    }

    /// Remove the previously installed search resolver, if any.
    pub async fn clear_search_resolver(&self) {
        *self.inner.search_resolver.write().await = None;
    }

    /// Install the per-request existence gate (see [`ExistenceGate`]).
    /// Replaces any previously installed gate. Used by the CA gateway so
    /// a cached shadow PV re-runs host/state admission per request.
    pub async fn set_existence_gate(&self, gate: ExistenceGate) {
        *self.inner.existence_gate.write().await = Some(gate);
    }

    /// Remove the previously installed existence gate, if any.
    pub async fn clear_existence_gate(&self) {
        *self.inner.existence_gate.write().await = None;
    }

    /// True when a cached simple PV named `name` must be treated as
    /// non-existent for `peer` because the installed [`ExistenceGate`]
    /// denied it. Always `false` when no gate is installed (a plain IOC)
    /// or when `name` does not resolve to a simple PV — records and
    /// aliases are never gateway-managed and bypass the gate.
    ///
    /// The single consultation point for the gate, shared by
    /// [`Self::find_entry_from`] and [`Self::has_name_from`] so the
    /// "cached simple PV ⇒ exists" short-circuit is closed uniformly on
    /// both the create and search paths.
    async fn simple_pv_gate_denies(&self, name: &str, peer: Option<std::net::SocketAddr>) -> bool {
        let gate = match self.inner.existence_gate.read().await.clone() {
            Some(g) => g,
            None => return false,
        };
        // Strip the channel-filter suffix exactly as the lookups do
        // (CA-FR-8) so the gate sees the same record-path key the
        // simple-PV map and the gateway cache are keyed on.
        let record_path = filters::split_channel_name(name).record_path;
        if !self
            .inner
            .simple_pvs
            .read()
            .await
            .contains_key(record_path.as_str())
        {
            return false;
        }
        !gate(record_path, peer).await
    }

    /// Set an external PV resolver for CA/PVA link resolution.
    /// The resolver is called synchronously from link reads.
    pub async fn set_external_resolver(&self, resolver: ExternalPvResolver) {
        *self.inner.external_resolver.write().await = Some(resolver);
    }

    /// Register a [`LinkSet`] under `scheme` (e.g. `"pva"` /
    /// `"ca"`). The lset is consulted for `ParsedLink::Pva` /
    /// `ParsedLink::Ca` link reads/writes before falling back to
    /// the legacy [`ExternalPvResolver`]. Subsequent calls for the
    /// same scheme replace the previous binding.
    pub async fn register_link_set(&self, scheme: &str, lset: link_set::DynLinkSet) {
        self.inner.link_sets.write().await.register(scheme, lset);
    }

    /// Look up the lset for `scheme`, if any.
    pub async fn link_set(&self, scheme: &str) -> Option<link_set::DynLinkSet> {
        self.inner.link_sets.read().await.get(scheme)
    }

    /// Snapshot of every registered scheme name. Stable order for
    /// `dbpvxr` dumps.
    pub async fn registered_link_schemes(&self) -> Vec<String> {
        let mut s = self.inner.link_sets.read().await.schemes();
        s.sort();
        s
    }

    /// Wait for the CA links to local records to report
    /// `is_connected() == true`. Mirrors `dbCa: iocInit wait for local CA
    /// links to connect` (epics-base PR #768/#856). The working set is
    /// exactly [`Self::external_link_targets`]: only the CA facility's
    /// local-target links — `pva://` links and non-local CA links connect
    /// in the background and are never waited on (pvxs parity).
    ///
    /// Polls every 100 ms. Returns:
    /// * `Ok(connected_count)` — the number of links that ended up
    ///   connected. May be smaller than the total when the timeout
    ///   expired before everyone was ready.
    /// * The total link count — i.e. the size of the working set
    ///   that was checked. `(connected, total)` lets the caller log
    ///   "M/N CA links connected".
    ///
    /// Pure no-op when no CA link set is registered, or when its
    /// `link_names()` has no local-target link yet (e.g. lazy-open lsets
    /// that haven't observed any record link — record processing creates
    /// the entries on first read, after iocInit returns).
    pub async fn wait_for_external_links(&self, timeout: std::time::Duration) -> (usize, usize) {
        // Collect (lset, name) pairs once. `link_names()` may grow
        // as record processing opens new links, but iocInit's wait
        // is bounded by the records loaded *before* Phase 3 — every
        // such link is already opened by the time wire_device_support
        // and setup_cp_links return.
        let targets = self.external_link_targets().await;
        let total = targets.len();
        if total == 0 {
            return (0, 0);
        }
        let deadline = tokio::time::Instant::now() + timeout;
        loop {
            let mut connected = 0usize;
            for (lset, name) in &targets {
                if lset.is_connected(name).await {
                    connected += 1;
                }
            }
            if connected == total {
                return (connected, total);
            }
            if tokio::time::Instant::now() >= deadline {
                return (connected, total);
            }
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }
    }

    /// Snapshot the `(lset, link_name)` pairs the iocInit external-link
    /// wait reasons over. Shared by [`Self::wait_for_external_links`] and
    /// [`Self::unconnected_external_links`] so both see the identical
    /// working set.
    ///
    /// C parity: the iocInit connection-wait is a property of the CA link
    /// facility (dbCa) alone. `dbCaRun` (dbCa.c:370-380) blocks on
    /// `initOutstanding`, the count of CA links flagged
    /// `DBCA_CALLBACK_INIT_WAIT` — set only for a CA link whose target is
    /// a LOCAL record (dbLink.c:128-130):
    ///   int isLocal = dbChannelTest(pvname) == 0;
    ///   dbCaAddLinkCallbackOpt(..., isLocal ? DBCA_CALLBACK_INIT_WAIT : 0)
    /// No other external facility waits: pvxs pvalink's `linkGlobal_t::init`
    /// (ioc/pvalink.cpp) only calls `chan->open()` per channel — it opens
    /// in the background and never blocks iocInit. So the wait targets
    /// exactly the CA link set's local-target links; a non-local CA link
    /// (e.g. areaDetector's `ShutterStatusEPICS_RBV.INP = "test CP MS"`
    /// placeholder) and every `pva://` link connect asynchronously and are
    /// never held by iocInit, like C.
    async fn external_link_targets(&self) -> Vec<(link_set::DynLinkSet, String)> {
        // Only the CA facility participates — look it up directly rather
        // than iterating every registered scheme. `has_name_no_resolve`
        // is the `dbChannelTest` twin (target is a local record).
        let Some(ca_lset) = ({
            let registry = self.inner.link_sets.read().await;
            registry.get("ca")
        }) else {
            return Vec::new();
        };
        let mut targets: Vec<(link_set::DynLinkSet, String)> = Vec::new();
        for n in ca_lset.link_names().await {
            if self.has_name_no_resolve(&n).await {
                targets.push((ca_lset.clone(), n));
            }
        }
        targets
    }

    /// Names of the waited-on CA links (local-target, per
    /// [`Self::external_link_targets`]) that are opened but not yet
    /// connected. iocInit calls this after
    /// [`Self::wait_for_external_links`] times out so the
    /// "M/N connected" diagnostic can name the `N-M` it proceeded
    /// without, instead of leaving the operator to run `dbcar`.
    /// `pva://` links are not in this set — they never block iocInit.
    pub async fn unconnected_external_links(&self) -> Vec<String> {
        let mut names = Vec::new();
        for (lset, name) in self.external_link_targets().await {
            if !lset.is_connected(&name).await {
                names.push(name);
            }
        }
        names
    }

    /// Enumerate every link-shaped field on `record_name`. Returns
    /// `(field_name, link_string, parsed)` tuples for fields whose
    /// raw value parses as a non-trivial link via
    /// [`crate::server::record::parse_link_v2`]. Used by `dbpvxr` to
    /// dump per-record link state without hardcoding the field-name
    /// list — works across record types as long as they expose link
    /// strings via [`Record::get_field`].
    ///
    /// Returns an empty Vec when the record doesn't exist.
    pub async fn record_link_fields(
        &self,
        record_name: &str,
    ) -> Vec<(String, String, crate::server::record::ParsedLink)> {
        let rec = match self.get_record(record_name).await {
            Some(r) => r,
            None => return Vec::new(),
        };
        let inst = rec.read().await;
        let mut out = Vec::new();
        // Each field is parsed for ITS OWN link-field type: C `dbPutFieldLink`
        // passes `pfldDes->field_type` to `dbParseLink` (`dbAccess.c:1094`),
        // which then masks the modifiers by that type (`dbStaticLib.c:2380-2391`).
        // `OUT` is `DBF_OUTLINK`, so its CP/CPP is discarded here rather than
        // reaching `setup_cp_links` — an `OUT` link must never be registered as
        // a CP holder.
        let push = |field: &str,
                    raw: &str,
                    ftype: crate::server::record::LinkFieldType,
                    out: &mut Vec<_>| {
            if raw.is_empty() {
                return;
            }
            let parsed = crate::server::record::parse_link_field(raw, ftype);
            if !matches!(parsed, crate::server::record::ParsedLink::None) {
                out.push((field.to_string(), raw.to_string(), parsed));
            }
        };
        use crate::server::record::LinkFieldType;
        // Canonical link-bearing fields stored on `CommonFields` as raw
        // String. These do NOT appear as `DbFieldType::String` entries in
        // `field_list()`: an `ai`'s `INP` / an `ao`'s `OUT` carry
        // `DBF_INLINK` / `DBF_OUTLINK` descriptors (and `INP`/`OUT` are
        // not in the record's static field table at all), so the previous
        // `field_list()` scan filtered by `String` silently dropped every
        // device-support link — the holder's pvalink monitor was never
        // opened. Enumerate the canonical storage directly so this method
        // is the single owner of "which fields on a record are links",
        // shared by `setup_cp_links` (CA CP/CPP) and the pvalink install
        // scan (PVA CP/CPP).
        push("INP", &inst.common.inp, LinkFieldType::In, &mut out);
        push("OUT", &inst.common.out, LinkFieldType::Out, &mut out);
        push("TSEL", &inst.common.tsel, LinkFieldType::In, &mut out);
        push("SDIS", &inst.common.sdis, LinkFieldType::In, &mut out);
        // Record-specific multi-input links (INPA..INPL for
        // calc/calcout/sel/sub) and the CP-capable input link fields
        // (DOL family, NVL, SELL, SGNL).
        let mut field_names: Vec<&str> = inst
            .record
            .multi_input_links()
            .iter()
            .map(|(lf, _vf)| *lf)
            .collect();
        field_names.extend_from_slice(crate::server::database::links::CP_INPUT_LINK_FIELDS);
        for field in field_names {
            if let Some(EpicsValue::String(s)) = inst.record.get_field(field) {
                push(field, &s.as_str_lossy(), LinkFieldType::In, &mut out);
            }
        }
        out
    }

    /// Resolve an external PV name. Dispatches through the
    /// `(scheme, name)` lset if one is registered; otherwise falls
    /// back to the legacy [`ExternalPvResolver`] closure. `name`
    /// may be the bare PV name (in which case `pva://` is assumed
    /// when an lset is registered for that scheme) or a fully
    /// scheme-prefixed string.
    pub(crate) async fn resolve_external_pv(&self, name: &str) -> Option<EpicsValue> {
        // Try lsets first. We accept both "scheme://body" and the
        // bare body (stored in ParsedLink::Pva/Ca after the
        // dispatch in record/link.rs).
        let (scheme, body) = if let Some(rest) = name.strip_prefix("pva://") {
            ("pva", rest)
        } else if let Some(rest) = name.strip_prefix("ca://") {
            ("ca", rest)
        } else {
            // No prefix — try every registered lset in turn. The
            // first one with a value for `name` wins. Schemes are
            // single-digit so this is cheap.
            let registry = self.inner.link_sets.read().await;
            let lsets: Vec<_> = registry
                .schemes()
                .iter()
                .filter_map(|s| registry.get(s))
                .collect();
            drop(registry);
            for lset in lsets {
                if let Some(v) = lset.get_value(name).await {
                    return Some(v);
                }
            }
            // Fall through to legacy resolver.
            let resolver = self.inner.external_resolver.read().await.clone();
            return match resolver {
                Some(r) => r(name).await,
                None => None,
            };
        };
        let lset = self.inner.link_sets.read().await.get(scheme);
        if let Some(lset) = lset {
            if let Some(v) = lset.get_value(body).await {
                return Some(v);
            }
        }
        let resolver = self.inner.external_resolver.read().await.clone();
        match resolver {
            Some(r) => r(name).await,
            None => None,
        }
    }

    /// Add a simple PV with an initial value.
    ///
    /// Returns `Err` when `name` is already registered as a simple PV,
    /// a record, or an alias — mirroring epics-base C IOC which treats
    /// duplicate `dbLoadRecords` names as a fatal error. Callers that
    /// want replace-on-overwrite semantics must first call
    /// `remove_simple_pv` / `remove_record` / `remove_alias`.
    ///
    /// Serialized through `registration_mutex` so the
    /// cross-namespace check is atomic with the insert and the lock
    /// order across all add_*/remove_* methods is identical (no
    /// cross-namespace deadlock).
    pub async fn add_pv(&self, name: &str, initial: EpicsValue) -> CaResult<()> {
        let _gate = self.inner.registration_mutex.lock().await;
        self.check_name_free(name).await?;
        let pv = Arc::new(ProcessVariable::new(name.to_string(), initial));
        self.inner
            .simple_pvs
            .write()
            .await
            .insert(name.to_string(), pv);
        Ok(())
    }

    /// Add a simple PV that already has a [`WriteHook`] installed.
    ///
    /// Equivalent to `add_pv` followed by `find_pv` + `set_write_hook`,
    /// but the PV is constructed with the hook in place so it is
    /// inserted into the `simple_pvs` map ATOMICALLY with the hook
    /// already attached. Closes a small race in proxy/gateway code
    /// where a downstream client could (in principle) `CREATE_CHAN` +
    /// `WRITE_NOTIFY` between the two awaits and hit the local
    /// `pv.set()` fallback path before the hook landed.
    ///
    /// Returns `Err` on duplicate name (see [`add_pv`]).
    pub async fn add_pv_with_hook(
        &self,
        name: &str,
        initial: EpicsValue,
        hook: crate::server::pv::WriteHook,
    ) -> CaResult<()> {
        self.add_pv_with_hooks(name, initial, hook, None).await
    }

    /// like [`Self::add_pv_with_hook`] but also installs an
    /// optional [`AccessHook`](crate::server::pv::AccessHook) so the CA
    /// gateway can route this shadow PV's read/write access-rights
    /// decision through its own ACF. Both hooks are attached before the
    /// PV is inserted into `simple_pvs`, so a downstream `CREATE_CHAN`
    /// cannot observe the PV without its access hook bound.
    pub async fn add_pv_with_hooks(
        &self,
        name: &str,
        initial: EpicsValue,
        write_hook: crate::server::pv::WriteHook,
        access_hook: Option<crate::server::pv::AccessHook>,
    ) -> CaResult<()> {
        self.add_pv_with_hooks_full(name, initial, write_hook, access_hook, None)
            .await
    }

    /// like [`Self::add_pv_with_hooks`] but also installs an optional
    /// [`ReadHook`](crate::server::pv::ReadHook) so a proxy (the CA
    /// gateway in no-cache mode) can serve each downstream GET from a
    /// fresh upstream fetch instead of the stored value. All three hooks
    /// are attached before the PV is inserted into `simple_pvs`, so a
    /// downstream `CREATE_CHAN` cannot observe the PV without its hooks
    /// bound — the read hook lands atomically with registration, closing
    /// the same race the write/access hooks already close. `read_hook:
    /// None` is identical to [`Self::add_pv_with_hooks`].
    pub async fn add_pv_with_hooks_full(
        &self,
        name: &str,
        initial: EpicsValue,
        write_hook: crate::server::pv::WriteHook,
        access_hook: Option<crate::server::pv::AccessHook>,
        read_hook: Option<crate::server::pv::ReadHook>,
    ) -> CaResult<()> {
        let _gate = self.inner.registration_mutex.lock().await;
        self.check_name_free(name).await?;
        let pv = Arc::new(ProcessVariable::new(name.to_string(), initial));
        pv.set_write_hook(write_hook);
        if let Some(access) = access_hook {
            pv.set_access_hook(access);
        }
        if let Some(read) = read_hook {
            pv.set_read_hook(read);
        }
        self.inner
            .simple_pvs
            .write()
            .await
            .insert(name.to_string(), pv);
        Ok(())
    }

    /// Remove a simple PV by name. Returns `Some(pv)` if a PV was
    /// removed. Used by the gateway sweep so an evicted upstream
    /// subscription doesn't leave a stale shadow PV (with a now-dead
    /// `WriteHook` capturing an aborted upstream channel).
    ///
    /// Also purges any aliases that pointed AT this name
    /// (otherwise a re-add of the same alias name would fail with
    /// "already registered as an alias" even though its target is
    /// gone).
    pub async fn remove_simple_pv(&self, name: &str) -> Option<Arc<ProcessVariable>> {
        let _gate = self.inner.registration_mutex.lock().await;
        // Simple PVs cannot be alias targets (aliases point at
        // records), but a stale alias whose name MATCHES this PV
        // would have been rejected at add_alias time. No alias
        // cleanup needed for simple-PV removal.
        self.inner.simple_pvs.write().await.remove(name)
    }

    /// Enter the LOAD phase: records are being created and the database is not
    /// yet the one C would classify links against. Called by every path that
    /// begins creating records for an IOC — an `IocBuilder` build, an iocsh
    /// `dbLoadRecords` / `dbCreateRecord`, `IocApp::run` — and idempotent within
    /// the phase, because an `st.cmd` issues several loads and they are all one
    /// `iocInit` (R18-92).
    ///
    /// # Refused once the IOC is running (R19-63)
    ///
    /// C admits no record creation after `iocInit`: `dbReadCOM`
    /// (`dbLexRoutines.c:236`) fails every `.db`/`.dbd` read with `-2` once
    /// `getIocState() != iocVoid`, and `dbCreateRecordCallFunc`
    /// (`dbStaticIocRegister.c:288`) fails with `S_dbLib_postInitRecRegister`.
    /// Asking to create records IS asking to enter the load phase, so the answer
    /// lives here and is a `Result` the caller cannot ignore — a creator that
    /// never asked cannot be written by accident, and one that asked cannot
    /// proceed on a refusal.
    ///
    /// The phase is left ONLY by [`Self::ioc_init`], and once left it is
    /// TERMINAL (R19-62): the queue is drained by exactly one `ioc_init`, so
    /// nothing can be pushed into it afterwards and stranded. A load that fails
    /// halfway leaves the phase open, which strands nothing: a queued
    /// classification blocks no caller, and it is dropped with the database.
    #[must_use = "C refuses a load after iocInit (dbReadCOM, dbLexRoutines.c:236); \
                  the refusal must be reported and no record created"]
    pub fn begin_load(&self) -> Result<(), IocAlreadyInitialized> {
        let mut phase = self.inner.init_phase.lock().unwrap();
        match *phase {
            // The only producer of `Loading`.
            DbInitPhase::Unloaded => {
                *phase = DbInitPhase::Loading(Vec::new());
                Ok(())
            }
            // An `st.cmd` issues several loads; they are all one `iocInit`.
            DbInitPhase::Loading(_) => Ok(()),
            // Post-`iocInit`: terminal. Refused, as C refuses it.
            DbInitPhase::Running => Err(IocAlreadyInitialized),
        }
    }

    /// Schedule a record's link-status classification — the port's
    /// `init_record` tail (C `checkLinks`).
    ///
    /// During the LOAD phase the future is QUEUED for [`Self::ioc_init`]; a
    /// half-built database cannot be classified against because the code that
    /// would do it has not been polled. Before any load, and once `iocInit` has
    /// run, it is spawned at once — which is what a runtime `special()` link
    /// re-point needs.
    pub(crate) fn schedule_record_init(
        &self,
        init: impl std::future::Future<Output = ()> + Send + 'static,
    ) {
        let mut phase = self.inner.init_phase.lock().unwrap();
        match &mut *phase {
            DbInitPhase::Loading(queued) => queued.push(Box::pin(init)),
            DbInitPhase::Unloaded | DbInitPhase::Running => {
                drop(phase);
                tokio::spawn(init);
            }
        }
    }

    /// The `iocInit` barrier: end the LOAD phase and run every classification
    /// owed, to completion.
    ///
    /// After this returns the database is complete and every link status is
    /// FINAL — C's guarantee, where `init_record` runs inside `iocInit` and a
    /// `dbgf REC.INAV` right after it reads the classified value (before it, C
    /// refuses `dbgf` outright). Idempotent: an `st.cmd` that spells `iocInit`
    /// out and the `IocApp` that runs one anyway are the same single boundary.
    pub async fn ioc_init(&self) {
        let owed = {
            let mut phase = self.inner.init_phase.lock().unwrap();
            match std::mem::replace(&mut *phase, DbInitPhase::Running) {
                DbInitPhase::Loading(queued) => queued,
                // An IOC that loaded nothing (programmatic / unit-test database)
                // still crosses the barrier: the phase becomes terminal.
                DbInitPhase::Unloaded => return,
                DbInitPhase::Running => return,
            }
        };
        // Sequential, in issue order: each classification is a short read of a
        // now-immutable record set, and C's `init_record` pass is a loop too.
        for init in owed {
            init.await;
        }
    }

    /// Add a record (accepts a boxed Record to avoid double-boxing).
    ///
    /// Returns `Err` when `name` collides with an existing record,
    /// simple PV, or alias. The C IOC's `dbLoadRecords` treats this as
    /// fatal; do not silently replace.
    ///
    /// The records-map insert AND scan-index insert run
    /// under the same `registration_mutex` hold, eliminating the
    /// TOCTOU window where `remove_record` could land between them
    /// and leave a phantom scan entry.
    pub async fn add_record(&self, name: &str, record: Box<dyn Record>) -> CaResult<()> {
        self.add_loaded_record(name, record, RecordLoad::default())
            .await
    }

    /// Add a record together with the field set its `.db` definition loaded
    /// into it — the creation sink for every `dbLoadRecords` path.
    ///
    /// C's `dbLoadRecords` writes a record's ENTIRE field set through
    /// `dbStaticLib` (including the `UDF = 0` that `dbPutString`
    /// (`dbStaticLib.c:2653-2661`) implies for any put to a field named
    /// `VAL`), and only afterwards does `iocInit::doInitRecord0`
    /// (`iocInit.c:508-536`) evaluate `if (udf && stat == UDF_ALARM) sevr =
    /// udfs`. The port used to add the record first and apply its loaded common
    /// fields afterwards, so the init passes ran against a PRE-LOAD field set:
    /// every record with a `field(VAL,…)` latched `SEVR = INVALID` at creation
    /// and the `UDF = 0` that arrived a moment later could not lower it again.
    /// A whole `.db` of setpoint defaults and sim constants came up red.
    ///
    /// Taking the loaded fields here is what makes C's ordering hold by
    /// construction: there is no window in which the init passes can observe a
    /// record whose `.db` fields have not landed, because the record is not
    /// reachable until they have. [`RecordInstance::run_init_passes`] is
    /// crate-private for the same reason — the sink is the only caller.
    pub async fn add_loaded_record(
        &self,
        name: &str,
        record: Box<dyn Record>,
        load: RecordLoad,
    ) -> CaResult<()> {
        let _gate = self.inner.registration_mutex.lock().await;
        self.check_name_free(name).await?;
        let mut instance = RecordInstance::new_boxed(name.to_string(), record);
        // Hand the record a cycle-free handle to its own database so it can
        // post out-of-band field updates / wire completion-driven re-entry
        // (asyn TRACE callback, sseq WAITn) without owning the database.
        // C records reach `dbCommon::pdba`/the IOC the same way at
        // `dbDefineRecord` init; the framework supplies the back-reference,
        // the record never constructs it. Defaulted no-op for records that
        // do not need it.
        instance
            .record
            .set_async_context(name.to_string(), self.async_handle());

        // Hand the record the current breakpoint-table registry snapshot so a
        // LINR>=3 ai/ao record can resolve its table lazily at convert time.
        // add_record is the single creation sink (IocBuilder, dbLoadRecords,
        // dbCreateRecord, inline records all funnel through here), so this one
        // install covers every creation path uniformly. The trait default is a
        // no-op for records that don't use it; skipped when no tables are
        // loaded so the common case pays no Arc clone. A record created before
        // its table is loaded is re-installed by `add_breaktables`.
        {
            let snapshot = self.inner.breaktable_registry.read().await.clone();
            if !snapshot.is_empty() {
                instance.record.install_breaktable_registry(snapshot);
            }
        }

        // The `.db` load, applied to the instance BEFORE the init passes below
        // — C's `dbLoadRecords` → `iocInit` ordering. The `.db` value coercion
        // (`put_common_field_db_load`) differs from a runtime `dbPut`'s: C's
        // loader converter has a wider menu bound (`dbStaticRun.c`).
        //
        // The scan-index entry is built from `instance.common.scan` further
        // down, i.e. from the POST-load field set, so a `field(SCAN,…)` needs
        // no index fix-up here — the record has not been published yet.
        for (field, value) in load.common_fields {
            if let Err(e) = instance.put_common_field_db_load(&field, value) {
                eprintln!("put_common_field({field}) failed for {name}: {e}");
            }
        }
        // `info(...)` tags land before `init_record`, so device support that
        // reads them at init sees the values.
        for (key, value) in &load.info_tags {
            instance.set_info(key, value);
        }

        // C's `iocInit` init passes, through their owner (the `doInitRecord0`
        // prologue — `pact = FALSE` plus the initial UDF severity — then
        // `init_record(0)`, `init_record(1)`, and the UDF tail). This sink is
        // the single site that runs them: a record built programmatically, by
        // iocsh `dbCreateRecord`, or from a `.db` is initialised the same way,
        // and — since the load above has already landed — always against its
        // FINAL field set.
        instance.run_init_passes(name);

        // The init-seed owner: every CONSTANT link the record declares
        // (`Record::constant_init_links`) is loaded into its value field ONCE,
        // here — a constant delivers NOTHING at process time
        // (`dbConstLink.c:219-225`). `add_record` is the creation sink every
        // path funnels through, so this covers a record built programmatically
        // as well as one loaded from a .db; `IocBuilder`/`dbLoadRecords` call
        // the owner again after `init_record(1)`, once the record's final
        // NELM/FTVL buffer exists for an array constant to land in. Seeding
        // twice is a no-op — both run before any client put.
        super::database::processing::seed_constant_links(&mut instance);

        let scan = instance.common.scan;
        let phas = instance.common.phas;
        self.inner
            .records
            .write()
            .await
            .insert(name.to_string(), Arc::new(RwLock::new(instance)));

        // Assign a monotonic load-order sequence — the scan-index
        // secondary sort key, so same-PHAS records keep load order.
        let seq = self
            .inner
            .load_order_counter
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        self.inner
            .load_order
            .write()
            .await
            .insert(name.to_string(), seq);

        if let Some(list) = scan.scan_list() {
            self.inner
                .scan_index
                .write()
                .await
                .entry(list)
                .or_default()
                .insert((phas, seq, name.to_string()));
        }
        Ok(())
    }

    /// Verify that `name` is not currently registered in any of the
    /// three namespaces. Caller MUST hold `registration_mutex` so the
    /// peek-then-insert sequence is atomic — without that, two tasks
    /// can both see the name as free and race the insert.
    async fn check_name_free(&self, name: &str) -> CaResult<()> {
        let kind = if self.inner.simple_pvs.read().await.contains_key(name) {
            Some("simple PV")
        } else if self.inner.records.read().await.contains_key(name) {
            Some("record")
        } else if self.inner.aliases.read().await.contains_key(name) {
            Some("alias")
        } else {
            None
        };
        if let Some(kind) = kind {
            return Err(CaError::DbParseError {
                line: 0,
                column: 0,
                message: format!("name '{name}' is already registered as a {kind}"),
            });
        }
        Ok(())
    }

    /// Remove a record by name. Returns `true` if a record was removed,
    /// `false` if no such name was registered. Mirrors epics-base PR
    /// #505 — deletion at database creation, exposed here as a public
    /// API so iocsh `dbDeleteRecord` and tests can drive it.
    ///
    /// The cleanup covers the three indices that `add_record` populates:
    /// the records map, the scan index, and CP-link source/target lists.
    /// Live subscribers on the removed record drop their `Sender` clone
    /// when the `RecordInstance` is dropped — they observe `Closed` on
    /// next recv, matching the existing dbEvent cancel flow.
    pub async fn remove_record(&self, name: &str) -> bool {
        let _gate = self.inner.registration_mutex.lock().await;
        // 1) Remove from main map; keep scan + phas for scan-index cleanup.
        let removed = self.inner.records.write().await.remove(name);
        let Some(rec_arc) = removed else {
            return false;
        };
        let scan = {
            let inst = rec_arc.read().await;
            inst.common.scan
        };

        // 2) Drop from scan index if it was scheduled. Match by record
        // name only — PHAS and load_order are not needed and may be
        // stale relative to the entry actually present.
        if let Some(list) = scan.scan_list() {
            let mut idx = self.inner.scan_index.write().await;
            if let Some(set) = idx.get_mut(&list) {
                set.retain(|(_, _, n)| n != name);
                if set.is_empty() {
                    idx.remove(&list);
                }
            }
        }

        // 2b) Drop the load-order entry.
        self.inner.load_order.write().await.remove(name);

        // 3) Drop from CP-link tables. Removed both as source (channel
        // change → trigger targets) and as target (other channels'
        // CP lists may still reference this name).
        let mut cp = self.inner.cp_links.write().await;
        cp.remove(name);
        for targets in cp.values_mut() {
            targets.retain(|t| t.record != name);
        }
        drop(cp);

        // 4) Purge aliases that pointed AT the
        // removed record. Otherwise `find_pv("ALT")` returns None
        // (target gone) but `add_pv("ALT", ...)` still fails with
        // "already registered as an alias" — orphan blocks reuse.
        let mut aliases = self.inner.aliases.write().await;
        aliases.retain(|_alias, target| target != name);

        true
    }

    /// Internal: synchronous lookup without invoking the search resolver.
    async fn find_entry_no_resolve(&self, name: &str) -> Option<PvEntry> {
        // a channel name may carry a `.{"arr":...}` filter
        // suffix. Strip it before lookup — the suffix is a per-channel
        // filter spec, not part of the PV identity. `split_channel_name`
        // is the single owner of "channel name → record_path" and is
        // idempotent on an already-stripped name. Without this a
        // filtered SimplePv (`SP.{"arr":...}`) never matches
        // `simple_pvs` (keyed by the bare PV name) and even a filtered
        // record fails when the JSON contains a `.` (e.g.
        // `{"dbnd":{"d":0.5}}`), because the bare `parse_pv_name` last-dot
        // split would tear the suffix apart instead of removing it.
        let record_path = filters::split_channel_name(name).record_path;
        let (base, _field) = parse_pv_name(&record_path);

        if let Some(pv) = self.inner.simple_pvs.read().await.get(record_path.as_str()) {
            return Some(PvEntry::Simple(pv.clone()));
        }
        if let Some(rec) = self.inner.records.read().await.get(base) {
            return Some(PvEntry::Record(rec.clone()));
        }
        // Alias resolve (epics-base PR #336): the alternate name maps
        // to a canonical record name. Look up the real record after
        // translating the base.
        if let Some(target) = self.inner.aliases.read().await.get(base).cloned() {
            if let Some(rec) = self.inner.records.read().await.get(&target) {
                return Some(PvEntry::Record(rec.clone()));
            }
        }
        None
    }

    /// Register an alias `alias` for an existing record `target`.
    /// Mirrors epics-base PR #336. Returns `Err(...)` when the target
    /// does not exist or the alias name is already in use anywhere
    /// in the database (records, simple PVs, or other aliases).
    ///
    /// Pre-fix the alias path checked only
    /// `records` and `aliases` — a simple-PV with the same name as
    /// the proposed alias was missed, leaving the database in a
    /// state where `find_pv(alias)` could resolve to either the
    /// simple PV or the alias-mapped record depending on lookup
    /// order. Now we run the same cross-namespace `check_name_free`
    /// guard the other add_* paths use.
    pub async fn add_alias(&self, alias: &str, target: &str) -> CaResult<()> {
        let _gate = self.inner.registration_mutex.lock().await;
        if !self.inner.records.read().await.contains_key(target) {
            return Err(CaError::ChannelNotFound(format!(
                "alias target '{target}' is not a registered record"
            )));
        }
        self.check_name_free(alias).await?;
        self.inner
            .aliases
            .write()
            .await
            .insert(alias.to_string(), target.to_string());
        Ok(())
    }

    /// Resolve an alias to its target record name, or `None` when the
    /// name is not an alias.
    pub async fn resolve_alias(&self, name: &str) -> Option<String> {
        self.inner.aliases.read().await.get(name).cloned()
    }

    /// Queue an iocsh command line for post-PINI execution.
    /// Mirrors epics-base PR #558 — `afterIocRunning <command>` lets
    /// the startup script schedule actions that run after iocInit
    /// completes (when the record set is fully wired up).
    pub fn queue_after_ioc_running(&self, line: impl Into<String>) {
        self.inner
            .after_ioc_running
            .lock()
            .unwrap()
            .push(line.into());
    }

    /// Drain the post-PINI iocsh command queue. Called by
    /// `IocApplication::run` after PINI processing.
    pub fn take_after_ioc_running(&self) -> Vec<String> {
        std::mem::take(&mut *self.inner.after_ioc_running.lock().unwrap())
    }

    /// Internal: synchronous existence check without resolver.
    async fn has_name_no_resolve(&self, name: &str) -> bool {
        // strip the channel-filter suffix before lookup so a
        // filtered channel (`SP.{"arr":...}` / `REC.{"dbnd":{"d":0.5}}`)
        // resolves to its underlying PV at UDP-search time. This is the
        // search-side twin of `find_entry_no_resolve`; without it a
        // filtered SimplePv never answers a SEARCH and the client never
        // reaches CREATE_CHAN. See that function for the full rationale.
        let record_path = filters::split_channel_name(name).record_path;
        let (base, _) = parse_pv_name(&record_path);
        if self
            .inner
            .simple_pvs
            .read()
            .await
            .contains_key(record_path.as_str())
        {
            return true;
        }
        if self.inner.records.read().await.contains_key(base) {
            return true;
        }
        // Alias entry exists and points to a live record
        // (epics-base PR #336).
        if let Some(target) = self.inner.aliases.read().await.get(base) {
            return self.inner.records.read().await.contains_key(target);
        }
        false
    }

    /// Look up an entry by name. Supports "record.FIELD" syntax.
    ///
    /// If the name is not found and a search resolver is installed,
    /// the resolver is invoked once. If the resolver returns true, the
    /// database is re-checked.
    pub async fn find_entry(&self, name: &str) -> Option<PvEntry> {
        self.find_entry_from(name, None).await
    }

    /// Like [`Self::find_entry`], but threads the downstream client's
    /// socket address into the search resolver. The CA TCP CREATE_CHANNEL
    /// handler passes the connection peer so the gateway can apply
    /// host-scoped `.pvlist` admission.
    pub async fn find_entry_from(
        &self,
        name: &str,
        peer: Option<std::net::SocketAddr>,
    ) -> Option<PvEntry> {
        if let Some(entry) = self.find_entry_no_resolve(name).await {
            // A cached simple PV must still pass the per-request
            // existence gate (CA gateway host/state admission). When the
            // gate denies it, answer does-not-exist for this requester
            // instead of returning the stale shadow entry — C ca-gateway
            // re-runs `gateAs::findEntry`/cache-state on every
            // `pvExistTest` (gateServer.cc:1516-1637). Records/aliases
            // bypass the gate (see `simple_pv_gate_denies`).
            if matches!(entry, PvEntry::Simple(_)) && self.simple_pv_gate_denies(name, peer).await {
                return None;
            }
            return Some(entry);
        }
        // Try the search resolver
        let resolver = self.inner.search_resolver.read().await.clone();
        if let Some(r) = resolver {
            if r(name.to_string(), peer).await {
                return self.find_entry_no_resolve(name).await;
            }
        }
        None
    }

    /// Check if a base name exists (for UDP search).
    ///
    /// If the name is not in the database and a search resolver is installed,
    /// the resolver is invoked. The resolver may populate the database
    /// (e.g., subscribe to an upstream IOC and add a placeholder PV) and
    /// return true; this method then re-checks.
    pub async fn has_name(&self, name: &str) -> bool {
        self.has_name_from(name, None).await
    }

    /// Like [`Self::has_name`], but threads the downstream client's
    /// socket address into the search resolver. The CA UDP search
    /// responder passes the datagram source address so the gateway can
    /// apply host-scoped `.pvlist` admission.
    pub async fn has_name_from(&self, name: &str, peer: Option<std::net::SocketAddr>) -> bool {
        if self.has_name_no_resolve(name).await {
            // Same per-request gate as `find_entry_from`: a cached simple
            // PV the gateway's host/state admission denies must answer
            // does-not-exist at search time. Records/aliases bypass.
            if self.simple_pv_gate_denies(name, peer).await {
                return false;
            }
            return true;
        }
        let resolver = self.inner.search_resolver.read().await.clone();
        if let Some(r) = resolver {
            if r(name.to_string(), peer).await {
                return self.has_name_no_resolve(name).await;
            }
        }
        false
    }

    /// Look up a simple PV by name (backward-compatible).
    pub async fn find_pv(&self, name: &str) -> Option<Arc<ProcessVariable>> {
        if let Some(pv) = self.inner.simple_pvs.read().await.get(name) {
            return Some(pv.clone());
        }
        None
    }

    /// Get a record Arc by name. Alias-aware (epics-base PR #336):
    /// when `name` is not a canonical record but matches a registered
    /// alias, the alias' target record is returned. Mirrors base
    /// `dbNameToAddr` behaviour, so dbpf/dbpr/dbgf, CA channel lookup,
    /// and DB-link target resolution all work transparently for
    /// aliases.
    ///
    /// Use [`Self::get_record_no_resolve`] when the caller already
    /// holds a canonical name and wants to suppress the alias path
    /// (e.g. to detect alias collisions during builder wiring).
    pub async fn get_record(&self, name: &str) -> Option<Arc<RwLock<RecordInstance>>> {
        if let Some(rec) = self.inner.records.read().await.get(name).cloned() {
            return Some(rec);
        }
        let target = self.inner.aliases.read().await.get(name).cloned()?;
        self.inner.records.read().await.get(&target).cloned()
    }

    /// Strict variant of [`Self::get_record`] — does NOT consult the
    /// alias table. Returns `Some` only when a canonical record with
    /// that exact name exists.
    pub async fn get_record_no_resolve(&self, name: &str) -> Option<Arc<RwLock<RecordInstance>>> {
        self.inner.records.read().await.get(name).cloned()
    }

    /// Every record name, in **database load order** — the single owner of
    /// whole-database iteration order.
    ///
    /// C parity: `dbFirstRecord`/`dbNextRecord` walk the record list of each
    /// record type in the order `dbReadDatabase` appended them, so every
    /// whole-database pass a C IOC makes — `initDevSup`, `initDatabase`,
    /// `initialProcess` (PINI), `dbl`/`dbgrep` dumps — visits records in load
    /// order. Device support is written against that contract: a dynamic device
    /// support whose record references another record (epics-modules/opcua's
    /// element records require their `opcuaItem` record to have bound first,
    /// linkParser.cpp:226-234) only boots if the referenced record was wired
    /// first, which the `.db` guarantees by declaring it first.
    ///
    /// The names live in a `HashMap`, so returning `keys()` made that order the
    /// hash order: neither load order nor even stable across runs of the same
    /// binary (`RandomState` reseeds per process). Booting the same database
    /// twice could wire records in two different orders — one boot succeeding
    /// and the next failing. Ordering here, at the one accessor every
    /// whole-database walk already goes through, makes every such pass
    /// deterministic and load-ordered at once.
    ///
    /// The order key is the existing per-record `load_order` sequence (the
    /// scan-index's secondary sort key), so this ordering and the scan lists'
    /// ordering are the same fact, not two. A record with no sequence — none
    /// exists; `add_record` is the only insertion path — would sort last by
    /// name rather than nondeterministically.
    pub async fn all_record_names(&self) -> Vec<String> {
        // Lock order records → load_order, matching `add_record`/`remove_record`.
        let records = self.inner.records.read().await;
        let load_order = self.inner.load_order.read().await;
        let mut names: Vec<String> = records.keys().cloned().collect();
        names.sort_by(|a, b| {
            let seq = |n: &String| load_order.get(n).copied().unwrap_or(u64::MAX);
            seq(a).cmp(&seq(b)).then_with(|| a.cmp(b))
        });
        names
    }

    /// Get all alias names registered against existing records.
    /// Mirrors the alias-half of base's `dbFirstRecord` iteration —
    /// `dbgrep` / `dbglob` / `dbsr` walk both record names and
    /// aliases when matching a glob.
    pub async fn all_alias_names(&self) -> Vec<String> {
        self.inner.aliases.read().await.keys().cloned().collect()
    }

    /// Return every alias that points at `canonical`. Sorted for
    /// stable output; empty when the record has no aliases. Used by
    /// `dbpr` to surface alias-form names so admins can see how
    /// clients may reach the record.
    pub async fn aliases_for_record(&self, canonical: &str) -> Vec<String> {
        let aliases = self.inner.aliases.read().await;
        let mut hits: Vec<String> = aliases
            .iter()
            .filter_map(|(alias, target)| {
                if target == canonical {
                    Some(alias.clone())
                } else {
                    None
                }
            })
            .collect();
        hits.sort();
        hits
    }

    /// Get all simple PV names.
    pub async fn all_simple_pv_names(&self) -> Vec<String> {
        self.inner.simple_pvs.read().await.keys().cloned().collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// C `recGblGetTimeStampSimm` (recGbl.c:310-343) maps TSE values
    /// to epicsTime sources via the constants in `epicsTime.h:102-104`.
    /// The Rust port previously misread TSE=-1 as "device-provided
    /// with BestTime fallback" and gated the BestTime call on a
    /// UNIX_EPOCH check. C calls `epicsTimeGetEvent(-1)`
    /// unconditionally; only TSE=-2 (epicsTimeEventDeviceTime) leaves
    /// `precord->time` untouched.
    ///
    /// Regression: a stale device write (any non-epoch SystemTime)
    /// suppressed every BestTime refresh thereafter.
    #[test]
    fn apply_timestamp_tse_minus_one_always_overwrites_with_best_time() {
        use crate::server::record::CommonFields;
        use std::time::{Duration, SystemTime};

        // Pre-populate `time` with a stale but non-epoch sentinel.
        let stale = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000_000);
        let mut common = CommonFields::default();
        common.tse = -1;
        common.time = stale;

        apply_timestamp(&mut common, false);

        // BestTime must have run unconditionally — `common.time` is
        // no longer the stale sentinel.
        assert_ne!(
            common.time, stale,
            "TSE=-1 must always overwrite via generalTime BestTime, \
             matching C epicsTimeGetEvent(-1) called unconditionally"
        );
    }

    /// C `epicsTimeEventDeviceTime = -2` (epicsTime.h:104). The C
    /// path does NOT call `epicsTimeGetEvent` for this TSE value;
    /// device support has already set `precord->time` before the
    /// recGbl call. The Rust port must leave `common.time` untouched.
    #[test]
    fn apply_timestamp_tse_minus_two_preserves_device_provided_time() {
        use crate::server::record::CommonFields;
        use std::time::{Duration, SystemTime};

        let device_time = SystemTime::UNIX_EPOCH + Duration::from_secs(2_000_000);
        let mut common = CommonFields::default();
        common.tse = -2;
        common.time = device_time;

        apply_timestamp(&mut common, false);

        assert_eq!(
            common.time, device_time,
            "TSE=-2 (epicsTimeEventDeviceTime) must preserve device-provided time"
        );
    }

    #[test]
    fn select_link_indices_fanout_all_specified_mask() {
        use crate::server::record::AlarmSeverity;
        // All — every slot.
        let r = select_link_indices_ex(SelmKind::FanoutSeq, 0, 0, 0, 0, 16);
        assert_eq!(r.indices, (0..16).collect::<Vec<_>>());
        assert!(r.alarm.is_none());

        // Specified, 0-based: SELN=0 selects LNK0 (C parity, fanout).
        let r = select_link_indices_ex(SelmKind::FanoutSeq, 1, 0, 0, 0, 16);
        assert_eq!(r.indices, vec![0]);
        // Specified with OFFS bias: SELN=2 + OFFS=3 → index 5.
        let r = select_link_indices_ex(SelmKind::FanoutSeq, 1, 2, 3, 0, 16);
        assert_eq!(r.indices, vec![5]);
        // Out-of-range Specified → INVALID alarm, no links.
        let r = select_link_indices_ex(SelmKind::FanoutSeq, 1, 20, 0, 0, 16);
        assert!(r.indices.is_empty());
        assert_eq!(r.alarm, Some((15, AlarmSeverity::Invalid)));
        // Negative resolved index (SELN + negative OFFS) → INVALID.
        let r = select_link_indices_ex(SelmKind::FanoutSeq, 1, 0, -1, 0, 16);
        assert_eq!(r.alarm, Some((15, AlarmSeverity::Invalid)));

        // Mask: SELN=0b101 → bits 0 and 2.
        let r = select_link_indices_ex(SelmKind::FanoutSeq, 2, 5, 0, 0, 16);
        assert_eq!(r.indices, vec![0, 2]);
        // Mask with SHFT: SELN=0b101 >> 1 = 0b10 → bit 1.
        let r = select_link_indices_ex(SelmKind::FanoutSeq, 2, 5, 0, 1, 16);
        assert_eq!(r.indices, vec![1]);
        // Mask with negative SHFT: SELN=0b101 << 1 = 0b1010 → bits 1,3.
        let r = select_link_indices_ex(SelmKind::FanoutSeq, 2, 5, 0, -1, 16);
        assert_eq!(r.indices, vec![1, 3]);
        // SHFT out of [-15,15] → INVALID.
        let r = select_link_indices_ex(SelmKind::FanoutSeq, 2, 5, 0, 16, 16);
        assert_eq!(r.alarm, Some((15, AlarmSeverity::Invalid)));

        // Unknown SELM → INVALID.
        let r = select_link_indices_ex(SelmKind::FanoutSeq, 9, 0, 0, 0, 16);
        assert_eq!(r.alarm, Some((15, AlarmSeverity::Invalid)));
    }

    #[test]
    fn select_link_indices_dfanout_specified_is_one_based() {
        use crate::server::record::AlarmSeverity;
        // dfanout Specified is 1-based: SELN=1 → OUTA (index 0).
        let r = select_link_indices_ex(SelmKind::Dfanout, 1, 1, 0, 0, 16);
        assert_eq!(r.indices, vec![0]);
        // SELN=2 → OUTB (index 1).
        let r = select_link_indices_ex(SelmKind::Dfanout, 1, 2, 0, 0, 16);
        assert_eq!(r.indices, vec![1]);
        // SELN=0 → drive nothing, NO alarm.
        let r = select_link_indices_ex(SelmKind::Dfanout, 1, 0, 0, 0, 16);
        assert!(r.indices.is_empty());
        assert!(r.alarm.is_none());
        // SELN > 16 → INVALID.
        let r = select_link_indices_ex(SelmKind::Dfanout, 1, 17, 0, 0, 16);
        assert_eq!(r.alarm, Some((15, AlarmSeverity::Invalid)));
        // dfanout Mask has no SHFT — SHFT arg ignored.
        let r = select_link_indices_ex(SelmKind::Dfanout, 2, 5, 0, 7, 16);
        assert_eq!(r.indices, vec![0, 2]);
    }

    /// `SELN` is unsigned, and the rule that makes it unsigned depends on the
    /// SOURCE type — because in C the source type picks the conversion routine.
    #[test]
    fn seln_cast_follows_the_source_type() {
        // Integer source -> `getLongUshort`, `(epicsUInt16)(epicsInt32)v`.
        // C DEFINES this (C17 6.3.1.3p2, modulo 2^16), so we reproduce it.
        assert_eq!(dbr_ushort_cast(&EpicsValue::Long(-1)), 65535);
        assert_eq!(dbr_ushort_cast(&EpicsValue::Long(65536)), 0);
        assert_eq!(dbr_ushort_cast(&EpicsValue::Short(-1)), 65535);
        assert_eq!(dbr_ushort_cast(&EpicsValue::Int64(-1)), 65535);
        assert_eq!(dbr_ushort_cast(&EpicsValue::Long(3)), 3);

        // Float source -> `getDoubleUshort`, `(epicsUInt16)d`. C leaves this
        // UNDEFINED (C17 6.3.1.4p1), and whatever `types::c_cast` decides to do
        // about that is a SEPARATE question from this one — the point here is
        // only that the float source takes the float rule and the integer
        // source does not.
        assert_eq!(
            dbr_ushort_cast(&EpicsValue::Double(-1.0)),
            crate::types::c_cast::f64_to_u16(-1.0)
        );
        assert_eq!(
            dbr_ushort_cast(&EpicsValue::Double(65536.0)),
            crate::types::c_cast::f64_to_u16(65536.0)
        );
        // In range: no policy in play, both rules truncate toward zero.
        assert_eq!(dbr_ushort_cast(&EpicsValue::Double(3.7)), 3);
    }

    /// Whatever produced it, a `SELN` of 65535 selects nothing under Specified
    /// (out of range -> INVALID) and everything under Mask.
    #[test]
    fn seln_at_the_unsigned_maximum_selects_by_selm() {
        use crate::server::record::AlarmSeverity;
        let seln_max = 65535u16;
        // fanout/seq Specified: C `i = (epicsUInt16)seln + offs` = 65535 →
        // out of range → INVALID. A signed read would clamp to 0 and wrongly
        // drive link 0.
        let r = select_link_indices_ex(SelmKind::FanoutSeq, 1, seln_max, 0, 0, 16);
        assert!(r.indices.is_empty());
        assert_eq!(r.alarm, Some((15, AlarmSeverity::Invalid)));
        // fanout/seq Mask: 65535 → all 16 low bits set → every link. A signed
        // read would produce an empty mask.
        let r = select_link_indices_ex(SelmKind::FanoutSeq, 2, seln_max, 0, 0, 16);
        assert_eq!(r.indices, (0..16).collect::<Vec<_>>());
        // dfanout Specified: 65535 > count → INVALID. A signed read would see
        // -1 ≤ 0 → drive nothing, with no alarm.
        let r = select_link_indices_ex(SelmKind::Dfanout, 1, seln_max, 0, 0, 16);
        assert!(r.indices.is_empty());
        assert_eq!(r.alarm, Some((15, AlarmSeverity::Invalid)));
    }

    /// Lset that flips to "connected" after a configurable delay.
    /// Drives the wait_for_external_links time-budget tests below.
    struct DelayedConnectLset {
        names: Vec<String>,
        connect_at: tokio::time::Instant,
    }

    #[async_trait::async_trait]
    impl link_set::LinkSet for DelayedConnectLset {
        async fn is_connected(&self, _: &str) -> bool {
            tokio::time::Instant::now() >= self.connect_at
        }
        async fn get_value(&self, _: &str) -> Option<EpicsValue> {
            None
        }
        async fn link_names(&self) -> Vec<String> {
            self.names.clone()
        }
    }

    #[tokio::test]
    async fn wait_for_external_links_returns_zero_zero_when_no_lsets() {
        let db = PvDatabase::new();
        let (c, t) = db
            .wait_for_external_links(std::time::Duration::from_millis(50))
            .await;
        assert_eq!((c, t), (0, 0));
    }

    #[tokio::test]
    async fn wait_for_external_links_connected_quickly() {
        let db = PvDatabase::new();
        // Local-target forced-CA links (dbChannelTest==0 → isLocal): these
        // get DBCA_CALLBACK_INIT_WAIT, so iocInit waits for them.
        db.add_pv("pv:A", EpicsValue::Long(0)).await.unwrap();
        db.add_pv("pv:B", EpicsValue::Long(0)).await.unwrap();
        let lset = Arc::new(DelayedConnectLset {
            names: vec!["pv:A".to_string(), "pv:B".to_string()],
            connect_at: tokio::time::Instant::now(),
        });
        // Registered under "ca": the iocInit wait is CA-facility only, so
        // the working set comes from the "ca" link set (these forced-CA
        // local-target links), never from a "pva" set.
        db.register_link_set("ca", lset).await;
        let (c, t) = db
            .wait_for_external_links(std::time::Duration::from_secs(1))
            .await;
        assert_eq!((c, t), (2, 2));
    }

    #[tokio::test]
    async fn wait_for_external_links_returns_partial_on_timeout() {
        let db = PvDatabase::new();
        // Local target so the link is in the init-wait set (dbLink.c:130);
        // connect-time well past the budget below, so the wait must return
        // (0, 1) instead of blocking.
        db.add_pv("slow:pv", EpicsValue::Long(0)).await.unwrap();
        let lset = Arc::new(DelayedConnectLset {
            names: vec!["slow:pv".to_string()],
            connect_at: tokio::time::Instant::now() + std::time::Duration::from_secs(60),
        });
        db.register_link_set("ca", lset).await;
        let started = tokio::time::Instant::now();
        let (c, t) = db
            .wait_for_external_links(std::time::Duration::from_millis(250))
            .await;
        let elapsed = started.elapsed();
        assert_eq!((c, t), (0, 1));
        assert!(
            elapsed >= std::time::Duration::from_millis(200),
            "wait must consume at least the configured budget, got {:?}",
            elapsed
        );
        assert!(
            elapsed < std::time::Duration::from_secs(2),
            "wait must not exceed the budget by much, got {:?}",
            elapsed
        );
    }

    /// C parity (dbLink.c:130): a link whose target is NOT a local record
    /// (`dbChannelTest != 0`) gets no DBCA_CALLBACK_INIT_WAIT, so iocInit
    /// must not block on it. An areaDetector `test CP MS` placeholder — a CP
    /// link to a PV that exists nowhere — must drop straight through, leaving
    /// the link to connect (or dangle) asynchronously and silently, like C.
    #[tokio::test]
    async fn wait_for_external_links_skips_nonlocal_targets() {
        let db = PvDatabase::new();
        // "test" has no local record and would never connect.
        let lset = Arc::new(DelayedConnectLset {
            names: vec!["test".to_string()],
            connect_at: tokio::time::Instant::now() + std::time::Duration::from_secs(60),
        });
        db.register_link_set("ca", lset).await;
        let started = tokio::time::Instant::now();
        let (c, t) = db
            .wait_for_external_links(std::time::Duration::from_secs(10))
            .await;
        // Non-local target is excluded from the wait set entirely, so the
        // call returns (0, 0) immediately rather than blocking the budget.
        assert_eq!((c, t), (0, 0));
        assert!(
            started.elapsed() < std::time::Duration::from_secs(1),
            "non-local link must not be waited on, got {:?}",
            started.elapsed()
        );
        // And it is reported as unconnected by neither path (silent, like C).
        assert!(db.unconnected_external_links().await.is_empty());
    }

    // epics-base PR #336 — alias parsing + lookup integration tests.

    #[tokio::test]
    async fn alias_resolves_through_find_entry() {
        let db = PvDatabase::new();
        db.add_record(
            "TARGET",
            Box::new(crate::server::records::ai::AiRecord::new(42.0)),
        )
        .await
        .unwrap();
        db.add_alias("ALIAS_NAME", "TARGET").await.unwrap();

        // find_entry on the alias must return the same record as
        // find_entry on the target.
        let via_alias = db.find_entry("ALIAS_NAME").await;
        let via_target = db.find_entry("TARGET").await;
        assert!(via_alias.is_some());
        assert!(via_target.is_some());
        // has_name flips true for the alias too.
        assert!(db.has_name("ALIAS_NAME").await);
        assert!(db.has_name("TARGET").await);
        assert!(!db.has_name("NOT:THERE").await);
    }

    #[tokio::test]
    async fn alias_target_must_exist() {
        let db = PvDatabase::new();
        let err = db.add_alias("DANGLING", "MISSING_TARGET").await;
        assert!(err.is_err(), "alias to missing target must be rejected");
    }

    #[tokio::test]
    async fn alias_collision_with_existing_record_rejected() {
        let db = PvDatabase::new();
        db.add_record(
            "EXISTING",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        db.add_record(
            "OTHER",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        let err = db.add_alias("EXISTING", "OTHER").await;
        assert!(
            err.is_err(),
            "alias name colliding with record must be rejected"
        );
    }

    #[tokio::test]
    async fn get_record_resolves_alias() {
        // Regression: get_record must transparently resolve
        // aliases so dbpf / dbgf / dbpr / CA put paths see the same
        // record whether the caller uses the canonical name or the
        // alias.
        let db = PvDatabase::new();
        db.add_record(
            "TARGET",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        db.add_alias("ALIAS", "TARGET").await.unwrap();

        let via_canonical = db.get_record("TARGET").await;
        let via_alias = db.get_record("ALIAS").await;
        assert!(via_canonical.is_some());
        assert!(via_alias.is_some(), "get_record must resolve alias");
        // Both calls return the same Arc (pointer equality).
        assert!(Arc::ptr_eq(&via_canonical.unwrap(), &via_alias.unwrap()));
    }

    /// `add_record` is the single creation sink: a record added AFTER its
    /// breakpoint table is loaded must receive the registry snapshot so a
    /// `LINR >= 3` conversion resolves — without any explicit per-call-site
    /// `install_breaktable_registry`. This covers the dbCreateRecord and
    /// inline-record creation paths that previously skipped the install.
    #[tokio::test]
    async fn add_record_installs_breaktable_registry_from_snapshot() {
        let db = PvDatabase::new();
        let ramp = crate::server::cvt_bpt::BrkTable::build(
            "ramp",
            &[(0.0, 0.0), (100.0, 10.0), (300.0, 30.0)],
        )
        .unwrap();
        db.add_breaktables(vec![ramp]).await;

        let mut rec = crate::server::records::ai::AiRecord::new(0.0);
        rec.put_field("LINR", EpicsValue::Short(15)).unwrap(); // ramp = first user-table index
        db.add_record("AI:BPT", Box::new(rec)).await.unwrap();

        let arc = db.get_record("AI:BPT").await.unwrap();
        let mut inst = arc.write().await;
        inst.record.put_field("RVAL", EpicsValue::Long(50)).unwrap();
        inst.record.process().unwrap();
        // raw 50 in [0,100] -> eng 5.0, proving the registry was installed by
        // add_record alone.
        assert_eq!(inst.record.get_field("VAL"), Some(EpicsValue::Double(5.0)));
    }

    /// `add_breaktables` re-installs the new snapshot into records that
    /// already exist, so a record created BEFORE its table was loaded (inline
    /// records added before dbLoadRecords; merge-reloads repointing LINR) can
    /// still resolve `LINR >= 3`. Without the re-install the record keeps an
    /// empty registry and never linearises.
    #[tokio::test]
    async fn add_breaktables_reinstalls_registry_into_existing_records() {
        let db = PvDatabase::new();
        // Record added while the registry is still empty: add_record installs
        // nothing (the inline-record / pre-load ordering case).
        let mut rec = crate::server::records::ai::AiRecord::new(0.0);
        rec.put_field("LINR", EpicsValue::Short(15)).unwrap(); // ramp = first user-table index
        db.add_record("AI:BPT", Box::new(rec)).await.unwrap();

        // Load the table afterwards — re-install must reach the existing record.
        let ramp = crate::server::cvt_bpt::BrkTable::build(
            "ramp",
            &[(0.0, 0.0), (100.0, 10.0), (300.0, 30.0)],
        )
        .unwrap();
        db.add_breaktables(vec![ramp]).await;

        let arc = db.get_record("AI:BPT").await.unwrap();
        let mut inst = arc.write().await;
        inst.record.put_field("RVAL", EpicsValue::Long(50)).unwrap();
        inst.record.process().unwrap();
        assert_eq!(inst.record.get_field("VAL"), Some(EpicsValue::Double(5.0)));
    }

    #[tokio::test]
    async fn get_record_no_resolve_skips_alias_table() {
        // Strict variant must NOT see aliases — keeps the canonical
        // distinction available for builder code paths.
        let db = PvDatabase::new();
        db.add_record(
            "TARGET",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        db.add_alias("ALIAS", "TARGET").await.unwrap();

        assert!(db.get_record_no_resolve("TARGET").await.is_some());
        assert!(
            db.get_record_no_resolve("ALIAS").await.is_none(),
            "get_record_no_resolve must not follow alias table"
        );
    }

    #[tokio::test]
    async fn register_cp_link_normalises_alias_to_canonical() {
        // Regression: CP link registration must store the
        // canonical record names. dispatch_cp_targets looks up by
        // canonical, so an alias-keyed entry is functionally dead.
        let db = PvDatabase::new();
        db.add_record(
            "SRC_REAL",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        db.add_record(
            "DST_REAL",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        db.add_alias("SRC_ALIAS", "SRC_REAL").await.unwrap();
        db.add_alias("DST_ALIAS", "DST_REAL").await.unwrap();

        // Register using the alias forms (CP edge: passive_only = false).
        db.register_cp_link("SRC_ALIAS", "DST_ALIAS", false).await;

        // Lookup must succeed via the canonical source name.
        let targets = db.get_cp_targets("SRC_REAL").await;
        assert_eq!(targets.len(), 1);
        assert_eq!(targets[0].record, "DST_REAL");
        assert!(!targets[0].passive_only);
        // Alias-keyed lookup must NOT have been registered.
        let alias_lookup = db.get_cp_targets("SRC_ALIAS").await;
        assert!(alias_lookup.is_empty());
    }

    #[tokio::test]
    async fn aliases_for_record_returns_sorted_targets_only() {
        let db = PvDatabase::new();
        db.add_record(
            "TARGET",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        db.add_record(
            "OTHER",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        db.add_alias("ZZ", "TARGET").await.unwrap();
        db.add_alias("AA", "TARGET").await.unwrap();
        db.add_alias("MM", "OTHER").await.unwrap();

        // Sorted, only TARGET's aliases.
        assert_eq!(
            db.aliases_for_record("TARGET").await,
            vec!["AA".to_string(), "ZZ".to_string()]
        );
        // OTHER's alone.
        assert_eq!(db.aliases_for_record("OTHER").await, vec!["MM".to_string()]);
        // Unknown record → empty, not None.
        assert!(db.aliases_for_record("MISSING").await.is_empty());
    }

    #[tokio::test]
    async fn all_alias_names_returns_registered_aliases() {
        let db = PvDatabase::new();
        db.add_record(
            "TARGET",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        db.add_alias("ALIAS_A", "TARGET").await.unwrap();
        db.add_alias("ALIAS_B", "TARGET").await.unwrap();

        let mut aliases = db.all_alias_names().await;
        aliases.sort();
        assert_eq!(aliases, vec!["ALIAS_A".to_string(), "ALIAS_B".to_string()]);
        // Canonical names are NOT returned here.
        assert!(!aliases.contains(&"TARGET".to_string()));
    }

    #[tokio::test]
    async fn complete_async_record_accepts_alias() {
        // Invariant audit: complete_async_record (the
        // entry point used by async device-support callbacks to
        // finish processing) must accept an alias name. Pre-fix it
        // walked `inner.records` directly and would
        // `ChannelNotFound` if the original name was an alias.
        let db = PvDatabase::new();
        db.add_record(
            "TARGET",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        db.add_alias("ALIAS", "TARGET").await.unwrap();

        // Use complete_async_record by alias — must not error.
        db.complete_async_record("ALIAS").await.unwrap();
        // And by canonical too — keeps existing behaviour.
        db.complete_async_record("TARGET").await.unwrap();
    }

    #[tokio::test]
    async fn process_record_accepts_alias() {
        // Regression: process_record must accept an alias
        // name. Pre-fix it walked `inner.records` directly.
        let db = PvDatabase::new();
        db.add_record(
            "TARGET",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        db.add_alias("ALIAS", "TARGET").await.unwrap();

        // Both should succeed and reach the same record.
        db.process_record("TARGET").await.unwrap();
        db.process_record("ALIAS").await.unwrap();

        // A bogus name still errors.
        assert!(db.process_record("MISSING").await.is_err());
    }

    #[tokio::test]
    async fn process_record_with_links_accepts_alias_and_avoids_cycle() {
        // Regression: process_record_with_links normalises
        // the alias so that (a) the records-map lookup hits and
        // (b) the cycle-detection set doesn't treat alias and
        // canonical as two distinct entries (which would let a
        // self-loop slip past the visited check).
        let db = PvDatabase::new();
        db.add_record(
            "TARGET",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        db.add_alias("ALIAS", "TARGET").await.unwrap();

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

        // visited should contain the *canonical* name only.
        assert!(
            visited.contains("TARGET"),
            "visited must record the canonical name: {visited:?}",
        );
        assert!(
            !visited.contains("ALIAS"),
            "visited must NOT record the alias form: {visited:?}",
        );
    }

    #[tokio::test]
    async fn alias_duplicate_rejected() {
        let db = PvDatabase::new();
        db.add_record(
            "TARGET",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();
        db.add_alias("ALIAS", "TARGET").await.unwrap();
        // Re-registering the same alias name (even to the same target)
        // must fail — base behaviour: aliases are inserted once.
        let err = db.add_alias("ALIAS", "TARGET").await;
        assert!(err.is_err(), "duplicate alias name must be rejected");
    }

    /// `add_pv`, `add_pv_with_hook`, and `add_record` must
    /// refuse to silently replace an existing registration. Mirrors
    /// epics-base C IOC which treats a duplicate `dbLoadRecords` name
    /// as a fatal load error.
    #[tokio::test]
    async fn add_pv_and_add_record_reject_duplicates_across_namespaces() {
        use crate::server::records::ai::AiRecord;

        let db = PvDatabase::new();
        db.add_pv("A", EpicsValue::Double(1.0)).await.unwrap();
        // Same name as simple_pv — every namespace must see it.
        assert!(db.add_pv("A", EpicsValue::Double(2.0)).await.is_err());
        let noop_hook: crate::server::pv::WriteHook =
            std::sync::Arc::new(|_v, _ctx| Box::pin(async { Ok(()) }));
        assert!(
            db.add_pv_with_hook("A", EpicsValue::Double(2.0), noop_hook)
                .await
                .is_err()
        );
        assert!(
            db.add_record("A", Box::new(AiRecord::new(0.0)))
                .await
                .is_err()
        );
        assert!(db.add_alias("A", "A").await.is_err());

        db.add_record("R", Box::new(AiRecord::new(0.0)))
            .await
            .unwrap();
        assert!(
            db.add_record("R", Box::new(AiRecord::new(1.0)))
                .await
                .is_err()
        );
        assert!(db.add_pv("R", EpicsValue::Double(0.0)).await.is_err());
        assert!(db.add_alias("R", "R").await.is_err());

        db.add_alias("AL", "R").await.unwrap();
        assert!(db.add_pv("AL", EpicsValue::Double(0.0)).await.is_err());
        assert!(
            db.add_record("AL", Box::new(AiRecord::new(0.0)))
                .await
                .is_err()
        );
    }

    /// Removing a record must purge aliases
    /// that pointed AT it. Otherwise the alias name stays
    /// "registered" forever and `add_pv` / `add_record` rejecting
    /// reuse causes a permanent name leak.
    #[tokio::test]
    async fn remove_record_purges_dangling_aliases() {
        use crate::server::records::ai::AiRecord;

        let db = PvDatabase::new();
        db.add_record("R", Box::new(AiRecord::new(0.0)))
            .await
            .unwrap();
        db.add_alias("ALT1", "R").await.unwrap();
        db.add_alias("ALT2", "R").await.unwrap();
        // An alias that points elsewhere must NOT be touched.
        db.add_record("OTHER", Box::new(AiRecord::new(0.0)))
            .await
            .unwrap();
        db.add_alias("KEEPER", "OTHER").await.unwrap();

        assert!(db.remove_record("R").await);

        // Both aliases pointing at R should be gone — `add_pv` of
        // those names succeeds again.
        db.add_pv("ALT1", EpicsValue::Double(0.0)).await.unwrap();
        db.add_pv("ALT2", EpicsValue::Double(0.0)).await.unwrap();
        // The unrelated alias must survive.
        assert_eq!(db.resolve_alias("KEEPER").await, Some("OTHER".to_string()));
    }

    /// `add_alias` must reject collisions with
    /// every namespace, including simple PVs (which the pre-fix
    /// code missed).
    #[tokio::test]
    async fn add_alias_rejects_simple_pv_collision() {
        use crate::server::records::ai::AiRecord;

        let db = PvDatabase::new();
        db.add_pv("PVX", EpicsValue::Double(0.0)).await.unwrap();
        db.add_record("TARGET", Box::new(AiRecord::new(0.0)))
            .await
            .unwrap();
        // alias name "PVX" collides with the simple PV — must fail.
        assert!(db.add_alias("PVX", "TARGET").await.is_err());
    }

    /// Concurrent `add_pv` and `add_record` with
    /// the same name must not deadlock and must serialize so that
    /// exactly one succeeds. Pre-fix the two methods grabbed
    /// different write locks first, opening a cross-lock-order
    /// deadlock window.
    #[tokio::test]
    async fn concurrent_add_pv_and_add_record_do_not_deadlock() {
        use crate::server::records::ai::AiRecord;

        let db = std::sync::Arc::new(PvDatabase::new());
        let db1 = db.clone();
        let db2 = db.clone();
        let h1 = tokio::spawn(async move { db1.add_pv("RACE", EpicsValue::Double(1.0)).await });
        let h2 =
            tokio::spawn(async move { db2.add_record("RACE", Box::new(AiRecord::new(0.0))).await });
        // Both complete within a reasonable bound — pre-fix this
        // could hang because T1 holds simple_pvs.write and waits
        // for records.read while T2 holds records.write and waits
        // for simple_pvs.read.
        let r1 = tokio::time::timeout(std::time::Duration::from_secs(2), h1)
            .await
            .expect("add_pv must not block on add_record");
        let r2 = tokio::time::timeout(std::time::Duration::from_secs(2), h2)
            .await
            .expect("add_record must not block on add_pv");
        let r1 = r1.unwrap();
        let r2 = r2.unwrap();
        // Exactly one of the two wins; the other reports
        // "already registered".
        assert!(
            (r1.is_ok() && r2.is_err()) || (r1.is_err() && r2.is_ok()),
            "exactly one of the racing inserts must succeed: r1={r1:?} r2={r2:?}",
        );
    }

    #[tokio::test]
    async fn existence_gate_blocks_cached_simple_pv_per_request() {
        // A cached simple PV must re-pass the installed existence gate on
        // both the search (`has_name_from`) and create (`find_entry_from`)
        // paths. Records bypass the gate. With no gate the short-circuit
        // is unchanged (plain-IOC behaviour).
        use std::net::SocketAddr;

        let db = PvDatabase::new();
        db.add_pv("SHADOW:x", EpicsValue::Double(1.0))
            .await
            .unwrap();
        db.add_record(
            "REC",
            Box::new(crate::server::records::ai::AiRecord::new(0.0)),
        )
        .await
        .unwrap();

        let denied: SocketAddr = "127.0.0.1:5064".parse().unwrap();
        let allowed: SocketAddr = "192.0.2.5:5064".parse().unwrap();

        // No gate installed: the cached simple PV resolves unconditionally.
        assert!(db.has_name_from("SHADOW:x", Some(denied)).await);
        assert!(db.find_entry_from("SHADOW:x", Some(denied)).await.is_some());

        // Gate denies the simple PV only for `denied` (the gateway's
        // host-scoped `.pvlist` admission has exactly this shape).
        let gate: ExistenceGate = Arc::new(move |name, peer| {
            Box::pin(async move { !(name == "SHADOW:x" && peer == Some(denied)) })
        });
        db.set_existence_gate(gate).await;

        // Denied peer: does-not-exist on both paths despite the PV being
        // cached in `simple_pvs`.
        assert!(!db.has_name_from("SHADOW:x", Some(denied)).await);
        assert!(db.find_entry_from("SHADOW:x", Some(denied)).await.is_none());

        // Allowed peer: still resolves.
        assert!(db.has_name_from("SHADOW:x", Some(allowed)).await);
        assert!(
            db.find_entry_from("SHADOW:x", Some(allowed))
                .await
                .is_some()
        );

        // Records are never gateway-managed — the gate must not gate them
        // even for the denied peer.
        assert!(db.has_name_from("REC", Some(denied)).await);
        assert!(db.find_entry_from("REC", Some(denied)).await.is_some());
    }

    /// `record_link_fields` must surface a record's device-support `INP`
    /// link. An `ai`'s `INP` is a `DBF_INLINK` field stored in
    /// `common.inp` — it is not a `DbFieldType::String` entry in
    /// `field_list()` — so the earlier `field_list()` scan filtered by
    /// `String` silently dropped it. The pvalink install scan walks this
    /// method, so a Passive `ai` carrying a CP/CPP pvalink `INP` never had
    /// its monitor opened at iocInit. Enumerating the canonical
    /// `common.inp` storage fixes it; C `dbpvar`/`dbcar` likewise dump
    /// every link field including device-support INP/OUT.
    #[tokio::test]
    async fn record_link_fields_surfaces_device_support_inp() {
        use crate::server::record::ParsedLink;
        use crate::server::records::ai::AiRecord;

        let db = PvDatabase::new();
        db.add_record("AI", Box::new(AiRecord::new(0.0)))
            .await
            .unwrap();
        // Device-support INP lives in `common.inp` (DBF_INLINK), the
        // exact storage a `field_list()` String scan cannot reach.
        {
            let rec = db.get_record("AI").await.unwrap();
            rec.write().await.common.inp = "pva://mini:current?proc=CP".to_string();
        }

        let links = db.record_link_fields("AI").await;
        let inp = links
            .iter()
            .find(|(f, _, _)| f == "INP")
            .unwrap_or_else(|| panic!("INP link must be surfaced, got {links:?}"));
        assert_eq!(inp.1, "pva://mini:current?proc=CP");
        assert!(
            matches!(inp.2, ParsedLink::Pva(_)),
            "a pva:// INP must parse to ParsedLink::Pva, got {:?}",
            inp.2
        );
    }
}