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
use {
    crate::{
        accounts_index::{
            AccountMapEntry, AccountMapEntryInner, AccountMapEntryMeta, DiskIndexValue, IndexValue,
            PreAllocatedAccountMapEntry, RefCount, SlotList, UpsertReclaim, ZeroLamport,
        },
        bucket_map_holder::{Age, AtomicAge, BucketMapHolder},
        bucket_map_holder_stats::BucketMapHolderStats,
        waitable_condvar::WaitableCondvar,
    },
    rand::{thread_rng, Rng},
    solana_bucket_map::bucket_api::BucketApi,
    solana_measure::measure::Measure,
    solana_sdk::{clock::Slot, pubkey::Pubkey},
    std::{
        collections::{hash_map::Entry, HashMap, HashSet},
        fmt::Debug,
        ops::{Bound, RangeBounds, RangeInclusive},
        sync::{
            atomic::{AtomicBool, AtomicU64, Ordering},
            Arc, Mutex, RwLock, RwLockWriteGuard,
        },
    },
};
type K = Pubkey;
type CacheRangesHeld = RwLock<Vec<RangeInclusive<Pubkey>>>;

type InMemMap<T> = HashMap<Pubkey, AccountMapEntry<T>>;

#[derive(Debug, Default)]
pub struct StartupStats {
    pub copy_data_us: AtomicU64,
}

#[derive(Debug)]
pub struct PossibleEvictions<T: IndexValue> {
    /// vec per age in the future, up to size 'ages_to_stay_in_cache'
    possible_evictions: Vec<FlushScanResult<T>>,
    /// next index to use into 'possible_evictions'
    /// if 'index' >= 'possible_evictions.len()', then there are no available entries
    index: usize,
}

impl<T: IndexValue> PossibleEvictions<T> {
    fn new(max_ages: Age) -> Self {
        Self {
            possible_evictions: (0..max_ages).map(|_| FlushScanResult::default()).collect(),
            index: max_ages as usize, // initially no data
        }
    }

    /// remove the possible evictions. This is required because we need ownership of the Arc strong counts to transfer to caller so entries can be removed from the accounts index
    fn get_possible_evictions(&mut self) -> Option<FlushScanResult<T>> {
        self.possible_evictions.get_mut(self.index).map(|result| {
            self.index += 1;
            // remove the list from 'possible_evictions'
            std::mem::take(result)
        })
    }

    /// clear existing data and prepare to add 'entries' more ages of data
    fn reset(&mut self, entries: Age) {
        self.possible_evictions.iter_mut().for_each(|entry| {
            entry.evictions_random.clear();
            entry.evictions_age_possible.clear();
        });
        let entries = entries as usize;
        assert!(
            entries <= self.possible_evictions.len(),
            "entries: {}, len: {}",
            entries,
            self.possible_evictions.len()
        );
        self.index = self.possible_evictions.len() - entries;
    }

    /// insert 'entry' at 'relative_age' in the future into 'possible_evictions'
    fn insert(&mut self, relative_age: Age, key: Pubkey, entry: AccountMapEntry<T>, random: bool) {
        let index = self.index + (relative_age as usize);
        let list = &mut self.possible_evictions[index];
        if random {
            &mut list.evictions_random
        } else {
            &mut list.evictions_age_possible
        }
        .push((key, entry));
    }
}

// one instance of this represents one bin of the accounts index.
pub struct InMemAccountsIndex<T: IndexValue, U: DiskIndexValue + From<T> + Into<T>> {
    last_age_flushed: AtomicAge,

    // backing store
    map_internal: RwLock<InMemMap<T>>,
    storage: Arc<BucketMapHolder<T, U>>,
    bin: usize,

    bucket: Option<Arc<BucketApi<(Slot, U)>>>,

    // pubkey ranges that this bin must hold in the cache while the range is present in this vec
    pub cache_ranges_held: CacheRangesHeld,
    // incremented each time stop_evictions is changed
    stop_evictions_changes: AtomicU64,
    // true while ranges are being manipulated. Used to keep an async flush from removing things while a range is being held.
    stop_evictions: AtomicU64,
    // set to true while this bin is being actively flushed
    flushing_active: AtomicBool,

    /// info to streamline initial index generation
    startup_info: StartupInfo<T, U>,

    /// possible evictions for next few slots coming up
    possible_evictions: RwLock<PossibleEvictions<T>>,

    /// how many more ages to skip before this bucket is flushed (as opposed to being skipped).
    /// When this reaches 0, this bucket is flushed.
    remaining_ages_to_skip_flushing: AtomicAge,

    /// an individual bucket will evict its entries and write to disk every 1/NUM_AGES_TO_DISTRIBUTE_FLUSHES ages
    /// Higher numbers mean we flush less buckets/s
    /// Lower numbers mean we flush more buckets/s
    num_ages_to_distribute_flushes: Age,

    /// stats related to starting up
    pub(crate) startup_stats: Arc<StartupStats>,
}

impl<T: IndexValue, U: DiskIndexValue + From<T> + Into<T>> Debug for InMemAccountsIndex<T, U> {
    fn fmt(&self, _f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Ok(())
    }
}

pub enum InsertNewEntryResults {
    DidNotExist,
    ExistedNewEntryZeroLamports,
    ExistedNewEntryNonZeroLamports,
}

#[derive(Default, Debug)]
struct StartupInfoDuplicates<T: IndexValue> {
    /// entries that were found to have duplicate index entries.
    /// When all entries have been inserted, these can be resolved and held in memory.
    duplicates: Vec<(Slot, Pubkey, T)>,
    /// pubkeys that were already added to disk and later found to be duplicates,
    duplicates_put_on_disk: HashSet<(Slot, Pubkey)>,
}

#[derive(Default, Debug)]
struct StartupInfo<T: IndexValue, U: DiskIndexValue + From<T> + Into<T>> {
    /// entries to add next time we are flushing to disk
    insert: Mutex<Vec<(Pubkey, (Slot, U))>>,
    /// pubkeys with more than 1 entry
    duplicates: Mutex<StartupInfoDuplicates<T>>,
}

#[derive(Default, Debug)]
/// result from scanning in-mem index during flush
struct FlushScanResult<T> {
    /// pubkeys whose age indicates they may be evicted now, pending further checks.
    evictions_age_possible: Vec<(Pubkey, AccountMapEntry<T>)>,
    /// pubkeys chosen to evict based on random eviction
    evictions_random: Vec<(Pubkey, AccountMapEntry<T>)>,
}

impl<T: IndexValue, U: DiskIndexValue + From<T> + Into<T>> InMemAccountsIndex<T, U> {
    pub fn new(storage: &Arc<BucketMapHolder<T, U>>, bin: usize) -> Self {
        let num_ages_to_distribute_flushes = Age::MAX - storage.ages_to_stay_in_cache;
        Self {
            map_internal: RwLock::default(),
            storage: Arc::clone(storage),
            bin,
            bucket: storage
                .disk
                .as_ref()
                .map(|disk| disk.get_bucket_from_index(bin))
                .map(Arc::clone),
            cache_ranges_held: CacheRangesHeld::default(),
            stop_evictions_changes: AtomicU64::default(),
            stop_evictions: AtomicU64::default(),
            flushing_active: AtomicBool::default(),
            // initialize this to max, to make it clear we have not flushed at age 0, the starting age
            last_age_flushed: AtomicAge::new(Age::MAX),
            startup_info: StartupInfo::default(),
            possible_evictions: RwLock::new(PossibleEvictions::new(1)),
            // Spread out the scanning across all ages within the window.
            // This causes us to scan 1/N of the bins each 'Age'
            remaining_ages_to_skip_flushing: AtomicAge::new(
                thread_rng().gen_range(0..num_ages_to_distribute_flushes),
            ),
            num_ages_to_distribute_flushes,
            startup_stats: Arc::clone(&storage.startup_stats),
        }
    }

    /// true if this bucket needs to call flush for the current age
    /// we need to scan each bucket once per value of age
    fn get_should_age(&self, age: Age) -> bool {
        let last_age_flushed = self.last_age_flushed();
        last_age_flushed != age
    }

    /// called after flush scans this bucket at the current age
    fn set_has_aged(&self, age: Age, can_advance_age: bool) {
        self.last_age_flushed.store(age, Ordering::Release);
        self.storage.bucket_flushed_at_current_age(can_advance_age);
    }

    fn last_age_flushed(&self) -> Age {
        self.last_age_flushed.load(Ordering::Acquire)
    }

    /// Release entire in-mem hashmap to free all memory associated with it.
    /// Idea is that during startup we needed a larger map than we need during runtime.
    /// When using disk-buckets, in-mem index grows over time with dynamic use and then shrinks, in theory back to 0.
    pub fn shrink_to_fit(&self) {
        // shrink_to_fit could be quite expensive on large map sizes, which 'no disk buckets' could produce, so avoid shrinking in case we end up here
        if self.storage.is_disk_index_enabled() {
            self.map_internal.write().unwrap().shrink_to_fit();
        }
    }

    pub fn items<R>(&self, range: &R) -> Vec<(K, AccountMapEntry<T>)>
    where
        R: RangeBounds<Pubkey> + std::fmt::Debug,
    {
        let m = Measure::start("items");
        self.hold_range_in_memory(range, true);
        let map = self.map_internal.read().unwrap();
        let mut result = Vec::with_capacity(map.len());
        map.iter().for_each(|(k, v)| {
            if range.contains(k) {
                result.push((*k, Arc::clone(v)));
            }
        });
        drop(map);
        self.hold_range_in_memory(range, false);
        Self::update_stat(&self.stats().items, 1);
        Self::update_time_stat(&self.stats().items_us, m);
        result
    }

    // only called in debug code paths
    pub fn keys(&self) -> Vec<Pubkey> {
        Self::update_stat(&self.stats().keys, 1);
        // easiest implementation is to load everything from disk into cache and return the keys
        let evictions_guard = EvictionsGuard::lock(self);
        self.put_range_in_cache(&None::<&RangeInclusive<Pubkey>>, &evictions_guard);
        let keys = self.map_internal.read().unwrap().keys().cloned().collect();
        keys
    }

    fn load_from_disk(&self, pubkey: &Pubkey) -> Option<(SlotList<U>, RefCount)> {
        self.bucket.as_ref().and_then(|disk| {
            let m = Measure::start("load_disk_found_count");
            let entry_disk = disk.read_value(pubkey);
            match &entry_disk {
                Some(_) => {
                    Self::update_time_stat(&self.stats().load_disk_found_us, m);
                    Self::update_stat(&self.stats().load_disk_found_count, 1);
                }
                None => {
                    Self::update_time_stat(&self.stats().load_disk_missing_us, m);
                    Self::update_stat(&self.stats().load_disk_missing_count, 1);
                }
            }
            entry_disk
        })
    }

    /// lookup 'pubkey' in disk map.
    /// If it is found, convert it to a cache entry and return the cache entry.
    /// Cache entries from this function will always not be dirty.
    fn load_account_entry_from_disk(&self, pubkey: &Pubkey) -> Option<AccountMapEntry<T>> {
        let entry_disk = self.load_from_disk(pubkey)?; // returns None if not on disk
        let entry_cache = self.disk_to_cache_entry(entry_disk.0, entry_disk.1);
        debug_assert!(!entry_cache.dirty());
        Some(entry_cache)
    }

    /// lookup 'pubkey' by only looking in memory. Does not look on disk.
    /// callback is called whether pubkey is found or not
    fn get_only_in_mem<RT>(
        &self,
        pubkey: &K,
        update_age: bool,
        callback: impl for<'a> FnOnce(Option<&'a AccountMapEntry<T>>) -> RT,
    ) -> RT {
        let mut found = true;
        let mut m = Measure::start("get");
        let result = {
            let map = self.map_internal.read().unwrap();
            let result = map.get(pubkey);
            m.stop();

            callback(if let Some(entry) = result {
                if update_age {
                    self.set_age_to_future(entry, false);
                }
                Some(entry)
            } else {
                drop(map);
                found = false;
                None
            })
        };

        let stats = self.stats();
        let (count, time) = if found {
            (&stats.gets_from_mem, &stats.get_mem_us)
        } else {
            (&stats.gets_missing, &stats.get_missing_us)
        };
        Self::update_stat(time, m.as_us());
        Self::update_stat(count, 1);

        result
    }

    /// lookup 'pubkey' in index (in mem or on disk)
    pub fn get(&self, pubkey: &K) -> Option<AccountMapEntry<T>> {
        self.get_internal(pubkey, |entry| (true, entry.map(Arc::clone)))
    }

    /// set age of 'entry' to the future
    /// if 'is_cached', age will be set farther
    fn set_age_to_future(&self, entry: &AccountMapEntry<T>, is_cached: bool) {
        entry.set_age(self.storage.future_age_to_flush(is_cached));
    }

    /// lookup 'pubkey' in index (in_mem or disk).
    /// call 'callback' whether found or not
    pub fn get_internal<RT>(
        &self,
        pubkey: &K,
        // return true if item should be added to in_mem cache
        callback: impl for<'a> FnOnce(Option<&AccountMapEntry<T>>) -> (bool, RT),
    ) -> RT {
        self.get_only_in_mem(pubkey, true, |entry| {
            if let Some(entry) = entry {
                callback(Some(entry)).1
            } else {
                // not in cache, look on disk
                let stats = self.stats();
                let disk_entry = self.load_account_entry_from_disk(pubkey);
                if disk_entry.is_none() {
                    return callback(None).1;
                }
                let disk_entry = disk_entry.unwrap();
                let mut map = self.map_internal.write().unwrap();
                let entry = map.entry(*pubkey);
                match entry {
                    Entry::Occupied(occupied) => callback(Some(occupied.get())).1,
                    Entry::Vacant(vacant) => {
                        debug_assert!(!disk_entry.dirty());
                        let (add_to_cache, rt) = callback(Some(&disk_entry));
                        // We are holding a write lock to the in-memory map.
                        // This pubkey is not in the in-memory map.
                        // If the entry is now dirty, then it must be put in the cache or the modifications will be lost.
                        if add_to_cache || disk_entry.dirty() {
                            stats.inc_mem_count(self.bin);
                            vacant.insert(disk_entry);
                        }
                        rt
                    }
                }
            }
        })
    }

    fn remove_if_slot_list_empty_value(&self, is_empty: bool) -> bool {
        if is_empty {
            self.stats().inc_delete();
            true
        } else {
            false
        }
    }

    fn delete_disk_key(&self, pubkey: &Pubkey) {
        if let Some(disk) = self.bucket.as_ref() {
            disk.delete_key(pubkey)
        }
    }

    /// return false if the entry is in the index (disk or memory) and has a slot list len > 0
    /// return true in all other cases, including if the entry is NOT in the index at all
    fn remove_if_slot_list_empty_entry(&self, entry: Entry<K, AccountMapEntry<T>>) -> bool {
        match entry {
            Entry::Occupied(occupied) => {
                let result = self.remove_if_slot_list_empty_value(
                    occupied.get().slot_list.read().unwrap().is_empty(),
                );
                if result {
                    // note there is a potential race here that has existed.
                    // if someone else holds the arc,
                    //  then they think the item is still in the index and can make modifications.
                    // We have to have a write lock to the map here, which means nobody else can get
                    //  the arc, but someone may already have retrieved a clone of it.
                    // account index in_mem flushing is one such possibility
                    self.delete_disk_key(occupied.key());
                    self.stats().dec_mem_count(self.bin);
                    occupied.remove();
                }
                result
            }
            Entry::Vacant(vacant) => {
                // not in cache, look on disk
                let entry_disk = self.load_from_disk(vacant.key());
                match entry_disk {
                    Some(entry_disk) => {
                        // on disk
                        if self.remove_if_slot_list_empty_value(entry_disk.0.is_empty()) {
                            // not in cache, but on disk, so just delete from disk
                            self.delete_disk_key(vacant.key());
                            true
                        } else {
                            // could insert into cache here, but not required for correctness and value is unclear
                            false
                        }
                    }
                    None => true, // not in cache or on disk, but slot list is 'empty' and entry is not in index, so return true
                }
            }
        }
    }

    // If the slot list for pubkey exists in the index and is empty, remove the index entry for pubkey and return true.
    // Return false otherwise.
    pub fn remove_if_slot_list_empty(&self, pubkey: Pubkey) -> bool {
        let mut m = Measure::start("entry");
        let mut map = self.map_internal.write().unwrap();
        let entry = map.entry(pubkey);
        m.stop();
        let found = matches!(entry, Entry::Occupied(_));
        let result = self.remove_if_slot_list_empty_entry(entry);
        drop(map);

        self.update_entry_stats(m, found);
        result
    }

    pub fn slot_list_mut<RT>(
        &self,
        pubkey: &Pubkey,
        user: impl for<'a> FnOnce(&mut RwLockWriteGuard<'a, SlotList<T>>) -> RT,
    ) -> Option<RT> {
        self.get_internal(pubkey, |entry| {
            (
                true,
                entry.map(|entry| {
                    let result = user(&mut entry.slot_list.write().unwrap());
                    entry.set_dirty(true);
                    result
                }),
            )
        })
    }

    /// update 'entry' with 'new_value'
    fn update_slot_list_entry(
        &self,
        entry: &AccountMapEntry<T>,
        new_value: PreAllocatedAccountMapEntry<T>,
        other_slot: Option<Slot>,
        reclaims: &mut SlotList<T>,
        reclaim: UpsertReclaim,
    ) {
        let new_value: (Slot, T) = new_value.into();
        let mut upsert_cached = new_value.1.is_cached();
        if Self::lock_and_update_slot_list(entry, new_value, other_slot, reclaims, reclaim) > 1 {
            // if slot list > 1, then we are going to hold this entry in memory until it gets set back to 1
            upsert_cached = true;
        }
        self.set_age_to_future(entry, upsert_cached);
    }

    pub fn upsert(
        &self,
        pubkey: &Pubkey,
        new_value: PreAllocatedAccountMapEntry<T>,
        other_slot: Option<Slot>,
        reclaims: &mut SlotList<T>,
        reclaim: UpsertReclaim,
    ) {
        let mut updated_in_mem = true;
        // try to get it just from memory first using only a read lock
        self.get_only_in_mem(pubkey, false, |entry| {
            if let Some(entry) = entry {
                self.update_slot_list_entry(entry, new_value, other_slot, reclaims, reclaim);
            } else {
                let mut m = Measure::start("entry");
                let mut map = self.map_internal.write().unwrap();
                let entry = map.entry(*pubkey);
                m.stop();
                let found = matches!(entry, Entry::Occupied(_));
                match entry {
                    Entry::Occupied(mut occupied) => {
                        let current = occupied.get_mut();
                        self.update_slot_list_entry(
                            current, new_value, other_slot, reclaims, reclaim,
                        );
                    }
                    Entry::Vacant(vacant) => {
                        // not in cache, look on disk
                        updated_in_mem = false;

                        // go to in-mem cache first
                        let disk_entry = self.load_account_entry_from_disk(vacant.key());
                        let new_value = if let Some(disk_entry) = disk_entry {
                            // on disk, so merge new_value with what was on disk
                            self.update_slot_list_entry(
                                &disk_entry,
                                new_value,
                                other_slot,
                                reclaims,
                                reclaim,
                            );
                            disk_entry
                        } else {
                            // not on disk, so insert new thing
                            self.stats().inc_insert();
                            new_value.into_account_map_entry(&self.storage)
                        };
                        assert!(new_value.dirty());
                        vacant.insert(new_value);
                        self.stats().inc_mem_count(self.bin);
                    }
                };

                drop(map);
                self.update_entry_stats(m, found);
            };
        });
        if updated_in_mem {
            Self::update_stat(&self.stats().updates_in_mem, 1);
        }
    }

    fn update_entry_stats(&self, stopped_measure: Measure, found: bool) {
        let stats = self.stats();
        let (count, time) = if found {
            (&stats.entries_from_mem, &stats.entry_mem_us)
        } else {
            (&stats.entries_missing, &stats.entry_missing_us)
        };
        Self::update_stat(time, stopped_measure.as_us());
        Self::update_stat(count, 1);
    }

    /// Try to update an item in the slot list the given `slot` If an item for the slot
    /// already exists in the list, remove the older item, add it to `reclaims`, and insert
    /// the new item.
    /// if 'other_slot' is some, then also remove any entries in the slot list that are at 'other_slot'
    /// return resulting len of slot list
    pub fn lock_and_update_slot_list(
        current: &AccountMapEntryInner<T>,
        new_value: (Slot, T),
        other_slot: Option<Slot>,
        reclaims: &mut SlotList<T>,
        reclaim: UpsertReclaim,
    ) -> usize {
        let mut slot_list = current.slot_list.write().unwrap();
        let (slot, new_entry) = new_value;
        let addref = Self::update_slot_list(
            &mut slot_list,
            slot,
            new_entry,
            other_slot,
            reclaims,
            reclaim,
        );
        if addref {
            current.addref();
        }
        current.set_dirty(true);
        slot_list.len()
    }

    /// modifies slot_list
    /// any entry at 'slot' or slot 'other_slot' is replaced with 'account_info'.
    /// or, 'account_info' is appended to the slot list if the slot did not exist previously.
    /// returns true if caller should addref
    /// conditions when caller should addref:
    ///   'account_info' does NOT represent a cached storage (the slot is being flushed from the cache)
    /// AND
    ///   previous slot_list entry AT 'slot' did not exist (this is the first time this account was modified in this "slot"), or was previously cached (the storage is now being flushed from the cache)
    /// Note that even if entry DID exist at 'other_slot', the above conditions apply.
    fn update_slot_list(
        slot_list: &mut SlotList<T>,
        slot: Slot,
        account_info: T,
        mut other_slot: Option<Slot>,
        reclaims: &mut SlotList<T>,
        reclaim: UpsertReclaim,
    ) -> bool {
        let mut addref = !account_info.is_cached();

        if other_slot == Some(slot) {
            other_slot = None; // redundant info, so ignore
        }

        // There may be 0..=2 dirty accounts found (one at 'slot' and one at 'other_slot')
        // that are already in the slot list.  Since the first one found will be swapped with the
        // new account, if a second one is found, we cannot swap again. Instead, just remove it.
        let mut found_slot = false;
        let mut found_other_slot = false;
        (0..slot_list.len())
            .rev() // rev since we delete from the list in some cases
            .for_each(|slot_list_index| {
                let (cur_slot, cur_account_info) = &slot_list[slot_list_index];
                let matched_slot = *cur_slot == slot;
                if matched_slot || Some(*cur_slot) == other_slot {
                    // make sure neither 'slot' nor 'other_slot' are in the slot list more than once
                    let matched_other_slot = !matched_slot;
                    assert!(
                        !(found_slot && matched_slot || matched_other_slot && found_other_slot),
                        "{slot_list:?}, slot: {slot}, other_slot: {other_slot:?}"
                    );

                    let is_cur_account_cached = cur_account_info.is_cached();

                    let reclaim_item = if !(found_slot || found_other_slot) {
                        // first time we found an entry in 'slot' or 'other_slot', so replace it in-place.
                        // this may be the only instance we find
                        std::mem::replace(&mut slot_list[slot_list_index], (slot, account_info))
                    } else {
                        // already replaced one entry, so this one has to be removed
                        slot_list.remove(slot_list_index)
                    };
                    match reclaim {
                        UpsertReclaim::PopulateReclaims => {
                            reclaims.push(reclaim_item);
                        }
                        UpsertReclaim::PreviousSlotEntryWasCached => {
                            assert!(is_cur_account_cached);
                        }
                        UpsertReclaim::IgnoreReclaims => {
                            // do nothing. nothing to assert. nothing to return in reclaims
                        }
                    }

                    if matched_slot {
                        found_slot = true;
                    } else {
                        found_other_slot = true;
                    }
                    if !is_cur_account_cached {
                        // current info at 'slot' is NOT cached, so we should NOT addref. This slot already has a ref count for this pubkey.
                        addref = false;
                    }
                }
            });
        if !found_slot && !found_other_slot {
            // if we make it here, we did not find the slot in the list
            slot_list.push((slot, account_info));
        }
        addref
    }

    // convert from raw data on disk to AccountMapEntry, set to age in future
    fn disk_to_cache_entry(
        &self,
        slot_list: SlotList<U>,
        ref_count: RefCount,
    ) -> AccountMapEntry<T> {
        Arc::new(AccountMapEntryInner::new(
            slot_list
                .into_iter()
                .map(|(slot, info)| (slot, info.into()))
                .collect(),
            ref_count,
            AccountMapEntryMeta::new_clean(&self.storage),
        ))
    }

    pub fn len_for_stats(&self) -> usize {
        self.stats().count_in_bucket(self.bin)
    }

    /// Queue up these insertions for when the flush thread is dealing with this bin.
    /// This is very fast and requires no lookups or disk access.
    pub fn startup_insert_only(&self, items: impl Iterator<Item = (Pubkey, (Slot, T))>) {
        assert!(self.storage.get_startup());
        assert!(self.bucket.is_some());

        let mut insert = self.startup_info.insert.lock().unwrap();
        let m = Measure::start("copy");
        items
            .into_iter()
            .for_each(|(k, (slot, v))| insert.push((k, (slot, v.into()))));
        self.startup_stats
            .copy_data_us
            .fetch_add(m.end_as_us(), Ordering::Relaxed);
    }

    pub fn insert_new_entry_if_missing_with_lock(
        &self,
        pubkey: Pubkey,
        new_entry: PreAllocatedAccountMapEntry<T>,
    ) -> InsertNewEntryResults {
        let mut m = Measure::start("entry");
        let mut map = self.map_internal.write().unwrap();
        let entry = map.entry(pubkey);
        m.stop();
        let new_entry_zero_lamports = new_entry.is_zero_lamport();
        let (found_in_mem, already_existed) = match entry {
            Entry::Occupied(occupied) => {
                // in cache, so merge into cache
                let (slot, account_info) = new_entry.into();
                InMemAccountsIndex::<T, U>::lock_and_update_slot_list(
                    occupied.get(),
                    (slot, account_info),
                    None, // should be None because we don't expect a different slot # during index generation
                    &mut Vec::default(),
                    UpsertReclaim::PopulateReclaims, // this should be ignore?
                );
                (
                    true, /* found in mem */
                    true, /* already existed */
                )
            }
            Entry::Vacant(vacant) => {
                // not in cache, look on disk
                let disk_entry = self.load_account_entry_from_disk(vacant.key());
                self.stats().inc_mem_count(self.bin);
                if let Some(disk_entry) = disk_entry {
                    let (slot, account_info) = new_entry.into();
                    InMemAccountsIndex::<T, U>::lock_and_update_slot_list(
                        &disk_entry,
                        (slot, account_info),
                        // None because we are inserting the first element in the slot list for this pubkey.
                        // There can be no 'other' slot in the list.
                        None,
                        &mut Vec::default(),
                        UpsertReclaim::PopulateReclaims,
                    );
                    vacant.insert(disk_entry);
                    (
                        false, /* found in mem */
                        true,  /* already existed */
                    )
                } else {
                    // not on disk, so insert new thing and we're done
                    let new_entry: AccountMapEntry<T> =
                        new_entry.into_account_map_entry(&self.storage);
                    assert!(new_entry.dirty());
                    vacant.insert(new_entry);
                    (false, false)
                }
            }
        };
        drop(map);
        self.update_entry_stats(m, found_in_mem);
        let stats = self.stats();
        if !already_existed {
            stats.inc_insert();
        } else {
            Self::update_stat(&stats.updates_in_mem, 1);
        }
        if !already_existed {
            InsertNewEntryResults::DidNotExist
        } else if new_entry_zero_lamports {
            InsertNewEntryResults::ExistedNewEntryZeroLamports
        } else {
            InsertNewEntryResults::ExistedNewEntryNonZeroLamports
        }
    }

    /// Look at the currently held ranges. If 'range' is already included in what is
    ///  being held, then add 'range' to the currently held list AND return true
    /// If 'range' is NOT already included in what is being held, then return false
    ///  withOUT adding 'range' to the list of what is currently held
    fn add_hold_range_in_memory_if_already_held<R>(
        &self,
        range: &R,
        evictions_guard: &EvictionsGuard,
    ) -> bool
    where
        R: RangeBounds<Pubkey>,
    {
        let start_holding = true;
        let only_add_if_already_held = true;
        self.just_set_hold_range_in_memory_internal(
            range,
            start_holding,
            only_add_if_already_held,
            evictions_guard,
        )
    }

    fn just_set_hold_range_in_memory<R>(
        &self,
        range: &R,
        start_holding: bool,
        evictions_guard: &EvictionsGuard,
    ) where
        R: RangeBounds<Pubkey>,
    {
        let only_add_if_already_held = false;
        let _ = self.just_set_hold_range_in_memory_internal(
            range,
            start_holding,
            only_add_if_already_held,
            evictions_guard,
        );
    }

    /// if 'start_holding', then caller wants to add 'range' to the list of ranges being held
    /// if !'start_holding', then caller wants to remove 'range' to the list
    /// if 'only_add_if_already_held', caller intends to only add 'range' to the list if the range is already held
    /// returns true iff start_holding=true and the range we're asked to hold was already being held
    fn just_set_hold_range_in_memory_internal<R>(
        &self,
        range: &R,
        start_holding: bool,
        only_add_if_already_held: bool,
        _evictions_guard: &EvictionsGuard,
    ) -> bool
    where
        R: RangeBounds<Pubkey>,
    {
        assert!(!only_add_if_already_held || start_holding);
        let start = match range.start_bound() {
            Bound::Included(bound) | Bound::Excluded(bound) => *bound,
            Bound::Unbounded => Pubkey::from([0; 32]),
        };

        let end = match range.end_bound() {
            Bound::Included(bound) | Bound::Excluded(bound) => *bound,
            Bound::Unbounded => Pubkey::from([0xff; 32]),
        };

        // this becomes inclusive - that is ok - we are just roughly holding a range of items.
        // inclusive is bigger than exclusive so we may hold 1 extra item worst case
        let inclusive_range = start..=end;
        let mut ranges = self.cache_ranges_held.write().unwrap();
        let mut already_held = false;
        if start_holding {
            if only_add_if_already_held {
                for r in ranges.iter() {
                    if r.contains(&start) && r.contains(&end) {
                        already_held = true;
                        break;
                    }
                }
            }
            if already_held || !only_add_if_already_held {
                ranges.push(inclusive_range);
            }
        } else {
            // find the matching range and delete it since we don't want to hold it anymore
            // search backwards, assuming LIFO ordering
            for (i, r) in ranges.iter().enumerate().rev() {
                if let (Bound::Included(start_found), Bound::Included(end_found)) =
                    (r.start_bound(), r.end_bound())
                {
                    if start_found == &start && end_found == &end {
                        // found a match. There may be dups, that's ok, we expect another call to remove the dup.
                        ranges.remove(i);
                        break;
                    }
                }
            }
        }
        already_held
    }

    /// if 'start_holding'=true, then:
    ///  at the end of this function, cache_ranges_held will be updated to contain 'range'
    ///  and all pubkeys in that range will be in the in-mem cache
    /// if 'start_holding'=false, then:
    ///  'range' will be removed from cache_ranges_held
    ///  and all pubkeys will be eligible for being removed from in-mem cache in the bg if no other range is holding them
    /// Any in-process flush will be aborted when it gets to evicting items from in-mem.
    pub fn hold_range_in_memory<R>(&self, range: &R, start_holding: bool)
    where
        R: RangeBounds<Pubkey> + Debug,
    {
        let evictions_guard = EvictionsGuard::lock(self);

        if !start_holding || !self.add_hold_range_in_memory_if_already_held(range, &evictions_guard)
        {
            if start_holding {
                // put everything in the cache and it will be held there
                self.put_range_in_cache(&Some(range), &evictions_guard);
            }
            // do this AFTER items have been put in cache - that way anyone who finds this range can know that the items are already in the cache
            self.just_set_hold_range_in_memory(range, start_holding, &evictions_guard);
        }
    }

    fn put_range_in_cache<R>(&self, range: &Option<&R>, _evictions_guard: &EvictionsGuard)
    where
        R: RangeBounds<Pubkey>,
    {
        assert!(self.get_stop_evictions()); // caller should be controlling the lifetime of how long this needs to be present
        let m = Measure::start("range");

        let mut added_to_mem = 0;
        // load from disk
        if let Some(disk) = self.bucket.as_ref() {
            let mut map = self.map_internal.write().unwrap();
            let items = disk.items_in_range(range); // map's lock has to be held while we are getting items from disk
            let future_age = self.storage.future_age_to_flush(false);
            for item in items {
                let entry = map.entry(item.pubkey);
                match entry {
                    Entry::Occupied(occupied) => {
                        // item already in cache, bump age to future. This helps the current age flush to succeed.
                        occupied.get().set_age(future_age);
                    }
                    Entry::Vacant(vacant) => {
                        vacant.insert(self.disk_to_cache_entry(item.slot_list, item.ref_count));
                        added_to_mem += 1;
                    }
                }
            }
        }
        self.stats().add_mem_count(self.bin, added_to_mem);

        Self::update_time_stat(&self.stats().get_range_us, m);
    }

    /// returns true if there are active requests to stop evictions
    fn get_stop_evictions(&self) -> bool {
        self.stop_evictions.load(Ordering::Acquire) > 0
    }

    /// return count of calls to 'start_stop_evictions', indicating changes could have been made to eviction strategy
    fn get_stop_evictions_changes(&self) -> u64 {
        self.stop_evictions_changes.load(Ordering::Acquire)
    }

    pub fn flush(&self, can_advance_age: bool) {
        if let Some(flush_guard) = FlushGuard::lock(&self.flushing_active) {
            self.flush_internal(&flush_guard, can_advance_age)
        }
    }

    /// returns true if a dice roll indicates this call should result in a random eviction.
    /// This causes non-determinism in cache contents per validator.
    fn random_chance_of_eviction() -> bool {
        // random eviction
        const N: usize = 1000;
        // 1/N chance of eviction
        thread_rng().gen_range(0..N) == 0
    }

    /// assumes 1 entry in the slot list. Ignores overhead of the HashMap and such
    fn approx_size_of_one_entry() -> usize {
        std::mem::size_of::<T>()
            + std::mem::size_of::<Pubkey>()
            + std::mem::size_of::<AccountMapEntry<T>>()
    }

    fn should_evict_based_on_age(
        current_age: Age,
        entry: &AccountMapEntry<T>,
        startup: bool,
        ages_flushing_now: Age,
    ) -> bool {
        startup || current_age.wrapping_sub(entry.age()) <= ages_flushing_now
    }

    /// return true if 'entry' should be evicted from the in-mem index
    fn should_evict_from_mem<'a>(
        &self,
        current_age: Age,
        entry: &'a AccountMapEntry<T>,
        startup: bool,
        update_stats: bool,
        exceeds_budget: bool,
        ages_flushing_now: Age,
    ) -> (bool, Option<std::sync::RwLockReadGuard<'a, SlotList<T>>>) {
        // this could be tunable dynamically based on memory pressure
        // we could look at more ages or we could throw out more items we are choosing to keep in the cache
        if Self::should_evict_based_on_age(current_age, entry, startup, ages_flushing_now) {
            if exceeds_budget {
                // if we are already holding too many items in-mem, then we need to be more aggressive at kicking things out
                (true, None)
            } else if entry.ref_count() != 1 {
                Self::update_stat(&self.stats().held_in_mem.ref_count, 1);
                (false, None)
            } else {
                // only read the slot list if we are planning to throw the item out
                let slot_list = entry.slot_list.read().unwrap();
                if slot_list.len() != 1 {
                    if update_stats {
                        Self::update_stat(&self.stats().held_in_mem.slot_list_len, 1);
                    }
                    (false, None) // keep 0 and > 1 slot lists in mem. They will be cleaned or shrunk soon.
                } else {
                    // keep items with slot lists that contained cached items
                    let evict = !slot_list.iter().any(|(_, info)| info.is_cached());
                    if !evict && update_stats {
                        Self::update_stat(&self.stats().held_in_mem.slot_list_cached, 1);
                    }
                    (evict, if evict { Some(slot_list) } else { None })
                }
            }
        } else {
            (false, None)
        }
    }

    /// fill in `possible_evictions` from `iter` by checking age
    fn gather_possible_evictions<'a>(
        iter: impl Iterator<Item = (&'a Pubkey, &'a Arc<AccountMapEntryInner<T>>)>,
        possible_evictions: &mut PossibleEvictions<T>,
        startup: bool,
        current_age: Age,
        ages_flushing_now: Age,
        can_randomly_flush: bool,
    ) {
        for (k, v) in iter {
            let mut random = false;
            if !startup && current_age.wrapping_sub(v.age()) > ages_flushing_now {
                if !can_randomly_flush || !Self::random_chance_of_eviction() {
                    // not planning to evict this item from memory within 'ages_flushing_now' ages
                    continue;
                }
                random = true;
            }

            possible_evictions.insert(0, *k, Arc::clone(v), random);
        }
    }

    /// scan loop
    /// holds read lock
    /// identifies items which are potential candidates to evict
    fn flush_scan(
        &self,
        current_age: Age,
        startup: bool,
        _flush_guard: &FlushGuard,
        ages_flushing_now: Age,
    ) -> FlushScanResult<T> {
        let mut possible_evictions = self.possible_evictions.write().unwrap();
        possible_evictions.reset(1);
        let m;
        {
            let map = self.map_internal.read().unwrap();
            m = Measure::start("flush_scan"); // we don't care about lock time in this metric - bg threads can wait
            Self::gather_possible_evictions(
                map.iter(),
                &mut possible_evictions,
                startup,
                current_age,
                ages_flushing_now,
                true,
            );
        }
        Self::update_time_stat(&self.stats().flush_scan_us, m);

        possible_evictions.get_possible_evictions().unwrap()
    }

    fn write_startup_info_to_disk(&self) {
        let insert = std::mem::take(&mut *self.startup_info.insert.lock().unwrap());
        if insert.is_empty() {
            // nothing to insert for this bin
            return;
        }

        // during startup, nothing should be in the in-mem map
        let map_internal = self.map_internal.read().unwrap();
        assert!(
            map_internal.is_empty(),
            "len: {}, first: {:?}",
            map_internal.len(),
            map_internal.iter().take(1).collect::<Vec<_>>()
        );
        drop(map_internal);

        // this fn should only be called from a single thread, so holding the lock is fine
        let mut duplicates = self.startup_info.duplicates.lock().unwrap();

        // merge all items into the disk index now
        let disk = self.bucket.as_ref().unwrap();
        let mut count = insert.len() as u64;
        for (i, duplicate_entry) in disk.batch_insert_non_duplicates(&insert) {
            let (k, entry) = &insert[i];
            duplicates.duplicates.push((entry.0, *k, entry.1.into()));
            // accurately account for there being a duplicate for the first entry that was previously added to the disk index.
            // That entry could not have known yet that it was a duplicate.
            // It is important to capture each slot with a duplicate because of slot limits applied to clean.
            duplicates
                .duplicates_put_on_disk
                .insert((duplicate_entry.0, *k));
            count -= 1;
        }

        self.stats().inc_insert_count(count);
    }

    /// pull out all duplicate pubkeys from 'startup_info'
    /// duplicate pubkeys have a slot list with len > 1
    /// These were collected for this bin when we did batch inserts in the bg flush threads.
    /// Insert these into the in-mem index, then return the duplicate (Slot, Pubkey)
    pub fn populate_and_retrieve_duplicate_keys_from_startup(&self) -> Vec<(Slot, Pubkey)> {
        // in order to return accurate and complete duplicates, we must have nothing left remaining to insert
        assert!(self.startup_info.insert.lock().unwrap().is_empty());

        let mut duplicate_items = self.startup_info.duplicates.lock().unwrap();
        let duplicates = std::mem::take(&mut duplicate_items.duplicates);
        let duplicates_put_on_disk = std::mem::take(&mut duplicate_items.duplicates_put_on_disk);
        drop(duplicate_items);

        duplicates_put_on_disk
            .into_iter()
            .chain(duplicates.into_iter().map(|(slot, key, info)| {
                let entry = PreAllocatedAccountMapEntry::new(slot, info, &self.storage, true);
                self.insert_new_entry_if_missing_with_lock(key, entry);
                (slot, key)
            }))
            .collect()
    }

    /// synchronize the in-mem index with the disk index
    fn flush_internal(&self, flush_guard: &FlushGuard, can_advance_age: bool) {
        let current_age = self.storage.current_age();
        let iterate_for_age = self.get_should_age(current_age);
        let startup = self.storage.get_startup();
        if !iterate_for_age && !startup {
            // no need to age, so no need to flush this bucket
            // but, at startup we want to evict from buckets as fast as possible if any items exist
            return;
        }

        if startup {
            self.write_startup_info_to_disk();
        }

        let ages_flushing_now = if iterate_for_age && !startup {
            let old_value = self
                .remaining_ages_to_skip_flushing
                .fetch_sub(1, Ordering::AcqRel);
            if old_value == 0 {
                self.remaining_ages_to_skip_flushing
                    .store(self.num_ages_to_distribute_flushes, Ordering::Release);
            } else {
                // skipping iteration of the buckets at the current age, but mark the bucket as having aged
                assert_eq!(current_age, self.storage.current_age());
                self.set_has_aged(current_age, can_advance_age);
                return;
            }
            self.num_ages_to_distribute_flushes
        } else {
            // just 1 age to flush. 0 means age == age
            0
        };

        Self::update_stat(&self.stats().buckets_scanned, 1);

        // scan in-mem map for items that we may evict
        let FlushScanResult {
            mut evictions_age_possible,
            mut evictions_random,
        } = self.flush_scan(current_age, startup, flush_guard, ages_flushing_now);

        // write to disk outside in-mem map read lock
        {
            let mut evictions_age = Vec::with_capacity(evictions_age_possible.len());
            if !evictions_age_possible.is_empty() || !evictions_random.is_empty() {
                let disk = self.bucket.as_ref().unwrap();
                let mut flush_entries_updated_on_disk = 0;
                let exceeds_budget = self.get_exceeds_budget();
                let mut flush_should_evict_us = 0;
                // we don't care about lock time in this metric - bg threads can wait
                let m = Measure::start("flush_update");

                // consider whether to write to disk for all the items we may evict, whether evicting due to age or random
                for (is_random, check_for_eviction_and_dirty) in [
                    (false, &mut evictions_age_possible),
                    (true, &mut evictions_random),
                ] {
                    for (k, v) in check_for_eviction_and_dirty.drain(..) {
                        let mut slot_list = None;
                        if !is_random {
                            let mut mse = Measure::start("flush_should_evict");
                            let (evict_for_age, slot_list_temp) = self.should_evict_from_mem(
                                current_age,
                                &v,
                                startup,
                                true,
                                exceeds_budget,
                                ages_flushing_now,
                            );
                            slot_list = slot_list_temp;
                            mse.stop();
                            flush_should_evict_us += mse.as_us();
                            if evict_for_age {
                                evictions_age.push(k);
                            } else {
                                // not evicting, so don't write, even if dirty
                                continue;
                            }
                        } else if v.ref_count() != 1 {
                            continue;
                        }
                        if is_random && v.dirty() {
                            // Don't randomly evict dirty entries. Evicting dirty entries results in us writing entries with many slot list elements for example, unnecessarily.
                            // So, only randomly evict entries that lru would say don't throw away and were just read (or were dirty and written, but could not be evicted).
                            continue;
                        }

                        // if we are evicting it, then we need to update disk if we're dirty
                        if v.clear_dirty() {
                            // step 1: clear the dirty flag
                            // step 2: perform the update on disk based on the fields in the entry
                            // If a parallel operation dirties the item again - even while this flush is occurring,
                            //  the last thing the writer will do, after updating contents, is set_dirty(true)
                            //  That prevents dropping an item from cache before disk is updated to latest in mem.
                            // It is possible that the item in the cache is marked as dirty while these updates are happening. That is ok.
                            //  The dirty will be picked up and the item will be prevented from being evicted.

                            // may have to loop if disk has to grow and we have to retry the write
                            loop {
                                let disk_resize = {
                                    let slot_list = slot_list
                                        .take()
                                        .unwrap_or_else(|| v.slot_list.read().unwrap());
                                    disk.try_write(
                                        &k,
                                        (
                                            &slot_list
                                                .iter()
                                                .map(|(slot, info)| (*slot, (*info).into()))
                                                .collect::<Vec<_>>(),
                                            v.ref_count(),
                                        ),
                                    )
                                };
                                match disk_resize {
                                    Ok(_) => {
                                        // successfully written to disk
                                        flush_entries_updated_on_disk += 1;
                                        break;
                                    }
                                    Err(err) => {
                                        // disk needs to resize. This item did not get written. Resize and try again.
                                        let m = Measure::start("flush_grow");
                                        disk.grow(err);
                                        Self::update_time_stat(&self.stats().flush_grow_us, m);
                                    }
                                }
                            }
                        }
                    }
                }
                Self::update_time_stat(&self.stats().flush_update_us, m);
                Self::update_stat(&self.stats().flush_should_evict_us, flush_should_evict_us);
                Self::update_stat(
                    &self.stats().flush_entries_updated_on_disk,
                    flush_entries_updated_on_disk,
                );
                // remove the 'v'
                let evictions_random = evictions_random
                    .into_iter()
                    .map(|(k, _v)| k)
                    .collect::<Vec<_>>();

                let m = Measure::start("flush_evict");
                self.evict_from_cache(
                    evictions_age,
                    current_age,
                    startup,
                    false,
                    ages_flushing_now,
                );
                self.evict_from_cache(
                    evictions_random,
                    current_age,
                    startup,
                    true,
                    ages_flushing_now,
                );
                Self::update_time_stat(&self.stats().flush_evict_us, m);
            }

            if iterate_for_age {
                // completed iteration of the buckets at the current age
                assert_eq!(current_age, self.storage.current_age());
                self.set_has_aged(current_age, can_advance_age);
            }
        }
    }

    /// calculate the estimated size of the in-mem index
    /// return whether the size exceeds the specified budget
    fn get_exceeds_budget(&self) -> bool {
        let in_mem_count = self.stats().count_in_mem.load(Ordering::Relaxed);
        let limit = self.storage.mem_budget_mb;
        let estimate_mem = in_mem_count * Self::approx_size_of_one_entry();
        let exceeds_budget = limit
            .map(|limit| estimate_mem >= limit * 1024 * 1024)
            .unwrap_or_default();
        self.stats()
            .estimate_mem
            .store(estimate_mem as u64, Ordering::Relaxed);
        exceeds_budget
    }

    /// for each key in 'keys', look up in map, set age to the future
    fn move_ages_to_future(&self, next_age: Age, current_age: Age, keys: &[Pubkey]) {
        let map = self.map_internal.read().unwrap();
        keys.iter().for_each(|key| {
            if let Some(entry) = map.get(key) {
                entry.try_exchange_age(next_age, current_age);
            }
        });
    }

    // evict keys in 'evictions' from in-mem cache, likely due to age
    fn evict_from_cache(
        &self,
        mut evictions: Vec<Pubkey>,
        current_age: Age,
        startup: bool,
        randomly_evicted: bool,
        ages_flushing_now: Age,
    ) {
        if evictions.is_empty() {
            return;
        }

        let stop_evictions_changes_at_start = self.get_stop_evictions_changes();
        let next_age_on_failure = self.storage.future_age_to_flush(false);
        if self.get_stop_evictions() {
            // ranges were changed
            self.move_ages_to_future(next_age_on_failure, current_age, &evictions);
            return;
        }

        let mut failed = 0;

        // skip any keys that are held in memory because of ranges being held
        let ranges = self.cache_ranges_held.read().unwrap().clone();
        if !ranges.is_empty() {
            let mut move_age = Vec::default();
            evictions.retain(|k| {
                if ranges.iter().any(|range| range.contains(k)) {
                    // this item is held in mem by range, so don't evict
                    move_age.push(*k);
                    false
                } else {
                    true
                }
            });
            if !move_age.is_empty() {
                failed += move_age.len();
                self.move_ages_to_future(next_age_on_failure, current_age, &move_age);
            }
        }

        let mut evicted = 0;
        // chunk these so we don't hold the write lock too long
        for evictions in evictions.chunks(50) {
            let mut map = self.map_internal.write().unwrap();
            for k in evictions {
                if let Entry::Occupied(occupied) = map.entry(*k) {
                    let v = occupied.get();
                    if Arc::strong_count(v) > 1 {
                        // someone is holding the value arc's ref count and could modify it, so do not evict
                        failed += 1;
                        v.try_exchange_age(next_age_on_failure, current_age);
                        continue;
                    }

                    if v.dirty()
                        || (!randomly_evicted
                            && !Self::should_evict_based_on_age(
                                current_age,
                                v,
                                startup,
                                ages_flushing_now,
                            ))
                    {
                        // marked dirty or bumped in age after we looked above
                        // these evictions will be handled in later passes (at later ages)
                        // but, at startup, everything is ready to age out if it isn't dirty
                        failed += 1;
                        continue;
                    }

                    if stop_evictions_changes_at_start != self.get_stop_evictions_changes() {
                        // ranges were changed
                        failed += 1;
                        v.try_exchange_age(next_age_on_failure, current_age);
                        continue;
                    }

                    // all conditions for eviction succeeded, so really evict item from in-mem cache
                    evicted += 1;
                    occupied.remove();
                }
            }
            if map.is_empty() {
                map.shrink_to_fit();
            }
        }
        self.stats().sub_mem_count(self.bin, evicted);
        Self::update_stat(&self.stats().flush_entries_evicted_from_mem, evicted as u64);
        Self::update_stat(&self.stats().failed_to_evict, failed as u64);
    }

    pub fn stats(&self) -> &BucketMapHolderStats {
        &self.storage.stats
    }

    fn update_stat(stat: &AtomicU64, value: u64) {
        if value != 0 {
            stat.fetch_add(value, Ordering::Relaxed);
        }
    }

    pub fn update_time_stat(stat: &AtomicU64, mut m: Measure) {
        m.stop();
        let value = m.as_us();
        Self::update_stat(stat, value);
    }
}

/// An RAII implementation of a scoped lock for the `flushing_active` atomic flag in
/// `InMemAccountsIndex`.  When this structure is dropped (falls out of scope), the flag will be
/// cleared (set to false).
///
/// After successfully locking (calling `FlushGuard::lock()`), pass a reference to the `FlashGuard`
/// instance to any function/code that requires the `flushing_active` flag has been set (to true).
#[derive(Debug)]
struct FlushGuard<'a> {
    flushing: &'a AtomicBool,
}

impl<'a> FlushGuard<'a> {
    /// Set the `flushing` atomic flag to true.  If the flag was already true, then return `None`
    /// (so as to not clear the flag erroneously).  Otherwise return `Some(FlushGuard)`.
    #[must_use = "if unused, the `flushing` flag will immediately clear"]
    fn lock(flushing: &'a AtomicBool) -> Option<Self> {
        let already_flushing = flushing.swap(true, Ordering::AcqRel);
        // Eager evaluation here would result in dropping Self and clearing flushing flag
        #[allow(clippy::unnecessary_lazy_evaluations)]
        (!already_flushing).then(|| Self { flushing })
    }
}

impl Drop for FlushGuard<'_> {
    fn drop(&mut self) {
        self.flushing.store(false, Ordering::Release);
    }
}

/// Disable (and safely enable) the background flusher from evicting entries from the in-mem
/// accounts index.  When disabled, no entries may be evicted.  When enabled, only eligible entries
/// may be evicted (i.e. those not in a held range).
///
/// An RAII implementation of a scoped lock for the `stop_evictions` atomic flag/counter in
/// `InMemAccountsIndex`.  When this structure is dropped (falls out of scope), the counter will
/// decrement and conditionally notify its storage.
///
/// After successfully locking (calling `EvictionsGuard::lock()`), pass a reference to the
/// `EvictionsGuard` instance to any function/code that requires `stop_evictions` to be
/// incremented/decremented correctly.
#[derive(Debug)]
struct EvictionsGuard<'a> {
    /// The number of active callers disabling evictions
    stop_evictions: &'a AtomicU64,
    /// The number of times that evictions have been disabled or enabled
    num_state_changes: &'a AtomicU64,
    /// Who will be notified after the evictions are re-enabled
    storage_notifier: &'a WaitableCondvar,
}

impl<'a> EvictionsGuard<'a> {
    #[must_use = "if unused, this evictions lock will be immediately unlocked"]
    fn lock<T: IndexValue, U: DiskIndexValue + From<T> + Into<T>>(
        in_mem_accounts_index: &'a InMemAccountsIndex<T, U>,
    ) -> Self {
        Self::lock_with(
            &in_mem_accounts_index.stop_evictions,
            &in_mem_accounts_index.stop_evictions_changes,
            &in_mem_accounts_index.storage.wait_dirty_or_aged,
        )
    }

    #[must_use = "if unused, this evictions lock will be immediately unlocked"]
    fn lock_with(
        stop_evictions: &'a AtomicU64,
        num_state_changes: &'a AtomicU64,
        storage_notifier: &'a WaitableCondvar,
    ) -> Self {
        num_state_changes.fetch_add(1, Ordering::Release);
        stop_evictions.fetch_add(1, Ordering::Release);

        Self {
            stop_evictions,
            num_state_changes,
            storage_notifier,
        }
    }
}

impl Drop for EvictionsGuard<'_> {
    fn drop(&mut self) {
        let previous_value = self.stop_evictions.fetch_sub(1, Ordering::AcqRel);
        debug_assert!(previous_value > 0);

        let should_notify = previous_value == 1;
        if should_notify {
            // stop_evictions went to 0, so this bucket could now be ready to be aged
            self.storage_notifier.notify_one();
        }

        self.num_state_changes.fetch_add(1, Ordering::Release);
    }
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::accounts_index::{AccountsIndexConfig, IndexLimitMb, BINS_FOR_TESTING},
        assert_matches::assert_matches,
        itertools::Itertools,
    };

    fn new_for_test<T: IndexValue>() -> InMemAccountsIndex<T, T> {
        let holder = Arc::new(BucketMapHolder::new(
            BINS_FOR_TESTING,
            &Some(AccountsIndexConfig::default()),
            1,
        ));
        let bin = 0;
        InMemAccountsIndex::new(&holder, bin)
    }

    fn new_disk_buckets_for_test<T: IndexValue>() -> InMemAccountsIndex<T, T> {
        let holder = Arc::new(BucketMapHolder::new(
            BINS_FOR_TESTING,
            &Some(AccountsIndexConfig {
                index_limit_mb: IndexLimitMb::Limit(1),
                ..AccountsIndexConfig::default()
            }),
            1,
        ));
        let bin = 0;
        let bucket = InMemAccountsIndex::new(&holder, bin);
        assert!(bucket.storage.is_disk_index_enabled());
        bucket
    }

    #[test]
    fn test_should_evict_from_mem_ref_count() {
        for ref_count in [0, 1, 2] {
            let bucket = new_for_test::<u64>();
            let startup = false;
            let current_age = 0;
            let one_element_slot_list = vec![(0, 0)];
            let one_element_slot_list_entry = Arc::new(AccountMapEntryInner::new(
                one_element_slot_list,
                ref_count,
                AccountMapEntryMeta::default(),
            ));

            // exceeded budget
            assert_eq!(
                bucket
                    .should_evict_from_mem(
                        current_age,
                        &one_element_slot_list_entry,
                        startup,
                        false,
                        false,
                        1,
                    )
                    .0,
                ref_count == 1
            );
        }
    }

    #[test]
    fn test_gather_possible_evictions() {
        solana_logger::setup();
        let startup = false;
        let ref_count = 1;
        let pks = (0..=255)
            .map(|i| Pubkey::from([i as u8; 32]))
            .collect::<Vec<_>>();
        let accounts = (0..=255)
            .map(|age| {
                let one_element_slot_list = vec![(0, 0)];
                let one_element_slot_list_entry = Arc::new(AccountMapEntryInner::new(
                    one_element_slot_list,
                    ref_count,
                    AccountMapEntryMeta::default(),
                ));
                one_element_slot_list_entry.set_age(age);
                one_element_slot_list_entry
            })
            .collect::<Vec<_>>();
        let both = pks.iter().zip(accounts.iter()).collect::<Vec<_>>();

        for current_age in 0..=255 {
            for ages_flushing_now in 0..=255 {
                let mut possible_evictions = PossibleEvictions::new(1);
                possible_evictions.reset(1);
                InMemAccountsIndex::<u64, u64>::gather_possible_evictions(
                    both.iter().cloned(),
                    &mut possible_evictions,
                    startup,
                    current_age,
                    ages_flushing_now,
                    false, // true=can_randomly_flush
                );
                let evictions = possible_evictions.possible_evictions.pop().unwrap();
                assert_eq!(
                    evictions.evictions_age_possible.len(),
                    1 + ages_flushing_now as usize
                );
                evictions.evictions_age_possible.iter().for_each(|(_k, v)| {
                    assert!(
                        InMemAccountsIndex::<u64, u64>::should_evict_based_on_age(
                            current_age,
                            v,
                            startup,
                            ages_flushing_now,
                        ),
                        "current_age: {}, age: {}, ages_flushing_now: {}",
                        current_age,
                        v.age(),
                        ages_flushing_now
                    );
                });
            }
        }
    }

    #[test]
    fn test_should_evict_from_mem() {
        solana_logger::setup();
        let bucket = new_for_test::<u64>();
        let mut startup = false;
        let mut current_age = 0;
        let ref_count = 1;
        let one_element_slot_list = vec![(0, 0)];
        let one_element_slot_list_entry = Arc::new(AccountMapEntryInner::new(
            one_element_slot_list,
            ref_count,
            AccountMapEntryMeta::default(),
        ));

        // exceeded budget
        assert!(
            bucket
                .should_evict_from_mem(
                    current_age,
                    &Arc::new(AccountMapEntryInner::new(
                        vec![],
                        ref_count,
                        AccountMapEntryMeta::default()
                    )),
                    startup,
                    false,
                    true,
                    0,
                )
                .0
        );
        // empty slot list
        assert!(
            !bucket
                .should_evict_from_mem(
                    current_age,
                    &Arc::new(AccountMapEntryInner::new(
                        vec![],
                        ref_count,
                        AccountMapEntryMeta::default()
                    )),
                    startup,
                    false,
                    false,
                    0,
                )
                .0
        );
        // 1 element slot list
        assert!(
            bucket
                .should_evict_from_mem(
                    current_age,
                    &one_element_slot_list_entry,
                    startup,
                    false,
                    false,
                    0,
                )
                .0
        );
        // 2 element slot list
        assert!(
            !bucket
                .should_evict_from_mem(
                    current_age,
                    &Arc::new(AccountMapEntryInner::new(
                        vec![(0, 0), (1, 1)],
                        ref_count,
                        AccountMapEntryMeta::default()
                    )),
                    startup,
                    false,
                    false,
                    0,
                )
                .0
        );

        {
            let bucket = new_for_test::<f64>();
            // 1 element slot list with a CACHED item - f64 acts like cached
            assert!(
                !bucket
                    .should_evict_from_mem(
                        current_age,
                        &Arc::new(AccountMapEntryInner::new(
                            vec![(0, 0.0)],
                            ref_count,
                            AccountMapEntryMeta::default()
                        )),
                        startup,
                        false,
                        false,
                        0,
                    )
                    .0
            );
        }

        // 1 element slot list, age is now
        assert!(
            bucket
                .should_evict_from_mem(
                    current_age,
                    &one_element_slot_list_entry,
                    startup,
                    false,
                    false,
                    0,
                )
                .0
        );

        // 1 element slot list, but not current age
        current_age = 1;
        assert!(
            !bucket
                .should_evict_from_mem(
                    current_age,
                    &one_element_slot_list_entry,
                    startup,
                    false,
                    false,
                    0,
                )
                .0
        );

        // 1 element slot list, but at startup and age not current
        startup = true;
        assert!(
            bucket
                .should_evict_from_mem(
                    current_age,
                    &one_element_slot_list_entry,
                    startup,
                    false,
                    false,
                    0,
                )
                .0
        );
    }

    #[test]
    fn test_hold_range_in_memory() {
        let bucket = new_disk_buckets_for_test::<u64>();
        // 0x81 is just some other range
        let all = Pubkey::from([0; 32])..=Pubkey::from([0xff; 32]);
        let ranges = [
            all.clone(),
            Pubkey::from([0x81; 32])..=Pubkey::from([0xff; 32]),
        ];
        for range in ranges.clone() {
            assert!(bucket.cache_ranges_held.read().unwrap().is_empty());
            bucket.hold_range_in_memory(&range, true);
            assert_eq!(
                bucket.cache_ranges_held.read().unwrap().to_vec(),
                vec![range.clone()]
            );
            {
                let evictions_guard = EvictionsGuard::lock(&bucket);
                assert!(bucket.add_hold_range_in_memory_if_already_held(&range, &evictions_guard));
                bucket.hold_range_in_memory(&range, false);
            }
            bucket.hold_range_in_memory(&range, false);
            assert!(bucket.cache_ranges_held.read().unwrap().is_empty());
            bucket.hold_range_in_memory(&range, true);
            assert_eq!(
                bucket.cache_ranges_held.read().unwrap().to_vec(),
                vec![range.clone()]
            );
            bucket.hold_range_in_memory(&range, true);
            assert_eq!(
                bucket.cache_ranges_held.read().unwrap().to_vec(),
                vec![range.clone(), range.clone()]
            );
            bucket.hold_range_in_memory(&ranges[0], true);
            assert_eq!(
                bucket.cache_ranges_held.read().unwrap().to_vec(),
                vec![range.clone(), range.clone(), ranges[0].clone()]
            );
            bucket.hold_range_in_memory(&range, false);
            assert_eq!(
                bucket.cache_ranges_held.read().unwrap().to_vec(),
                vec![range.clone(), ranges[0].clone()]
            );
            bucket.hold_range_in_memory(&range, false);
            assert_eq!(
                bucket.cache_ranges_held.read().unwrap().to_vec(),
                vec![ranges[0].clone()]
            );
            bucket.hold_range_in_memory(&ranges[0].clone(), false);
            assert!(bucket.cache_ranges_held.read().unwrap().is_empty());

            // hold all in mem first
            assert!(bucket.cache_ranges_held.read().unwrap().is_empty());
            bucket.hold_range_in_memory(&all, true);

            let evictions_guard = EvictionsGuard::lock(&bucket);
            assert!(bucket.add_hold_range_in_memory_if_already_held(&range, &evictions_guard));
            bucket.hold_range_in_memory(&range, false);
            bucket.hold_range_in_memory(&all, false);
        }
    }

    #[test]
    fn test_age() {
        solana_logger::setup();
        let test = new_for_test::<u64>();
        assert!(test.get_should_age(test.storage.current_age()));
        assert_eq!(test.storage.count_buckets_flushed(), 0);
        test.set_has_aged(0, true);
        assert!(!test.get_should_age(test.storage.current_age()));
        assert_eq!(test.storage.count_buckets_flushed(), 1);
        // simulate rest of buckets aging
        for _ in 1..BINS_FOR_TESTING {
            assert!(!test.storage.all_buckets_flushed_at_current_age());
            test.storage.bucket_flushed_at_current_age(true);
        }
        assert!(test.storage.all_buckets_flushed_at_current_age());
        // advance age
        test.storage.increment_age();
        assert_eq!(test.storage.current_age(), 1);
        assert!(!test.storage.all_buckets_flushed_at_current_age());
        assert!(test.get_should_age(test.storage.current_age()));
        assert_eq!(test.storage.count_buckets_flushed(), 0);
    }

    #[test]
    fn test_update_slot_list_other() {
        solana_logger::setup();
        let reclaim = UpsertReclaim::PopulateReclaims;
        let new_slot = 0;
        let info = 1;
        let other_value = info + 1;
        let at_new_slot = (new_slot, info);
        let unique_other_slot = new_slot + 1;
        for other_slot in [Some(new_slot), Some(unique_other_slot), None] {
            let mut reclaims = Vec::default();
            let mut slot_list = Vec::default();
            // upserting into empty slot_list, so always addref
            assert!(
                InMemAccountsIndex::<u64, u64>::update_slot_list(
                    &mut slot_list,
                    new_slot,
                    info,
                    other_slot,
                    &mut reclaims,
                    reclaim
                ),
                "other_slot: {other_slot:?}"
            );
            assert_eq!(slot_list, vec![at_new_slot]);
            assert!(reclaims.is_empty());
        }

        // replace other
        let mut slot_list = vec![(unique_other_slot, other_value)];
        let expected_reclaims = slot_list.clone();
        let other_slot = Some(unique_other_slot);
        let mut reclaims = Vec::default();
        assert!(
            // upserting into slot_list that does NOT contain an entry at 'new_slot'
            // but, it DOES contain an entry at other_slot, so we do NOT add-ref. The assumption is that 'other_slot' is going away
            // and that the previously held add-ref is now used by 'new_slot'
            !InMemAccountsIndex::<u64, u64>::update_slot_list(
                &mut slot_list,
                new_slot,
                info,
                other_slot,
                &mut reclaims,
                reclaim
            ),
            "other_slot: {other_slot:?}"
        );
        assert_eq!(slot_list, vec![at_new_slot]);
        assert_eq!(reclaims, expected_reclaims);

        // replace other and new_slot
        let mut slot_list = vec![(unique_other_slot, other_value), (new_slot, other_value)];
        let expected_reclaims = slot_list.clone();
        let other_slot = Some(unique_other_slot);
        // upserting into slot_list that already contain an entry at 'new-slot', so do NOT addref
        let mut reclaims = Vec::default();
        assert!(
            !InMemAccountsIndex::<u64, u64>::update_slot_list(
                &mut slot_list,
                new_slot,
                info,
                other_slot,
                &mut reclaims,
                reclaim
            ),
            "other_slot: {other_slot:?}"
        );
        assert_eq!(slot_list, vec![at_new_slot]);
        assert_eq!(
            reclaims,
            expected_reclaims.into_iter().rev().collect::<Vec<_>>()
        );

        // nothing will exist at this slot
        let missing_other_slot = unique_other_slot + 1;
        let ignored_slot = 10; // bigger than is used elsewhere in the test
        let ignored_value = info + 10;

        let mut possible_initial_slot_list_contents;
        // build a list of possible contents in the slot_list prior to calling 'update_slot_list'
        {
            // up to 3 ignored slot account_info (ignored means not 'new_slot', not 'other_slot', but different slot #s which could exist in the slot_list initially)
            possible_initial_slot_list_contents = (0..3)
                .map(|i| (ignored_slot + i, ignored_value + i))
                .collect::<Vec<_>>();
            // account_info that already exists in the slot_list AT 'new_slot'
            possible_initial_slot_list_contents.push(at_new_slot);
            // account_info that already exists in the slot_list AT 'other_slot'
            possible_initial_slot_list_contents.push((unique_other_slot, other_value));
        }

        /*
         * loop over all possible permutations of 'possible_initial_slot_list_contents'
         * some examples:
         * []
         * [other]
         * [other, new_slot]
         * [new_slot, other]
         * [dummy0, new_slot, dummy1, other] (and all permutation of this order)
         * [other, dummy1, new_slot] (and all permutation of this order)
         * ...
         * [dummy0, new_slot, dummy1, other_slot, dummy2] (and all permutation of this order)
         */
        let mut attempts = 0;
        // loop over each initial size of 'slot_list'
        for initial_slot_list_len in 0..=possible_initial_slot_list_contents.len() {
            // loop over every permutation of possible_initial_slot_list_contents within a list of len 'initial_slot_list_len'
            for content_source_indexes in
                (0..possible_initial_slot_list_contents.len()).permutations(initial_slot_list_len)
            {
                // loop over each possible parameter for 'other_slot'
                for other_slot in [
                    Some(new_slot),
                    Some(unique_other_slot),
                    Some(missing_other_slot),
                    None,
                ] {
                    attempts += 1;
                    // initialize slot_list prior to call to 'InMemAccountsIndex::update_slot_list'
                    // by inserting each possible entry at each possible position
                    let mut slot_list = content_source_indexes
                        .iter()
                        .map(|i| possible_initial_slot_list_contents[*i])
                        .collect::<Vec<_>>();
                    let mut expected = slot_list.clone();
                    let original = slot_list.clone();
                    let mut reclaims = Vec::default();

                    let result = InMemAccountsIndex::<u64, u64>::update_slot_list(
                        &mut slot_list,
                        new_slot,
                        info,
                        other_slot,
                        &mut reclaims,
                        reclaim,
                    );

                    // calculate expected results
                    let mut expected_reclaims = Vec::default();
                    // addref iff the slot_list did NOT previously contain an entry at 'new_slot' and it also did not contain an entry at 'other_slot'
                    let expected_result = !expected
                        .iter()
                        .any(|(slot, _info)| slot == &new_slot || Some(*slot) == other_slot);
                    {
                        // this is the logical equivalent of 'InMemAccountsIndex::update_slot_list', but slower (and ignoring addref)
                        expected.retain(|(slot, info)| {
                            let retain = slot != &new_slot && Some(*slot) != other_slot;
                            if !retain {
                                expected_reclaims.push((*slot, *info));
                            }
                            retain
                        });
                        expected.push((new_slot, info));
                    }
                    assert_eq!(
                        expected_result, result,
                        "return value different. other: {other_slot:?}, {expected:?}, {slot_list:?}, original: {original:?}"
                    );
                    // sort for easy comparison
                    expected_reclaims.sort_unstable();
                    reclaims.sort_unstable();
                    assert_eq!(
                        expected_reclaims, reclaims,
                        "reclaims different. other: {other_slot:?}, {expected:?}, {slot_list:?}, original: {original:?}"
                    );
                    // sort for easy comparison
                    slot_list.sort_unstable();
                    expected.sort_unstable();
                    assert_eq!(
                        slot_list, expected,
                        "slot_list different. other: {other_slot:?}, {expected:?}, {slot_list:?}, original: {original:?}"
                    );
                }
            }
        }
        assert_eq!(attempts, 1304); // complicated permutations, so make sure we ran the right #
    }

    #[test]
    fn test_flush_guard() {
        let flushing_active = AtomicBool::new(false);

        {
            let flush_guard = FlushGuard::lock(&flushing_active);
            assert!(flush_guard.is_some());
            assert!(flushing_active.load(Ordering::Acquire));

            {
                // Trying to lock the FlushGuard again will not succeed.
                let flush_guard2 = FlushGuard::lock(&flushing_active);
                assert!(flush_guard2.is_none());
            }

            // The `flushing_active` flag will remain true, even after `flush_guard2` goes out of
            // scope (and is dropped).  This ensures `lock()` and `drop()` work harmoniously.
            assert!(flushing_active.load(Ordering::Acquire));
        }

        // After the FlushGuard is dropped, the flag will be cleared.
        assert!(!flushing_active.load(Ordering::Acquire));
    }

    #[test]
    fn test_remove_if_slot_list_empty_entry() {
        let key = solana_sdk::pubkey::new_rand();
        let unknown_key = solana_sdk::pubkey::new_rand();

        let test = new_for_test::<u64>();

        let mut map = test.map_internal.write().unwrap();

        {
            // item is NOT in index at all, still return true from remove_if_slot_list_empty_entry
            // make sure not initially in index
            let entry = map.entry(unknown_key);
            assert_matches!(entry, Entry::Vacant(_));
            let entry = map.entry(unknown_key);
            assert!(test.remove_if_slot_list_empty_entry(entry));
            // make sure still not in index
            let entry = map.entry(unknown_key);
            assert_matches!(entry, Entry::Vacant(_));
        }

        {
            // add an entry with an empty slot list
            let val = Arc::new(AccountMapEntryInner::<u64>::default());
            map.insert(key, val);
            let entry = map.entry(key);
            assert_matches!(entry, Entry::Occupied(_));
            // should have removed it since it had an empty slot list
            assert!(test.remove_if_slot_list_empty_entry(entry));
            let entry = map.entry(key);
            assert_matches!(entry, Entry::Vacant(_));
            // return true - item is not in index at all now
            assert!(test.remove_if_slot_list_empty_entry(entry));
        }

        {
            // add an entry with a NON empty slot list - it will NOT get removed
            let val = Arc::new(AccountMapEntryInner::<u64>::default());
            val.slot_list.write().unwrap().push((1, 1));
            map.insert(key, val);
            // does NOT remove it since it has a non-empty slot list
            let entry = map.entry(key);
            assert!(!test.remove_if_slot_list_empty_entry(entry));
            let entry = map.entry(key);
            assert_matches!(entry, Entry::Occupied(_));
        }
    }

    #[test]
    fn test_lock_and_update_slot_list() {
        let test = AccountMapEntryInner::<u64>::default();
        let info = 65;
        let mut reclaims = Vec::default();
        // first upsert, should increase
        let len = InMemAccountsIndex::<u64, u64>::lock_and_update_slot_list(
            &test,
            (1, info),
            None,
            &mut reclaims,
            UpsertReclaim::IgnoreReclaims,
        );
        assert_eq!(test.slot_list.read().unwrap().len(), len);
        assert_eq!(len, 1);
        // update to different slot, should increase
        let len = InMemAccountsIndex::<u64, u64>::lock_and_update_slot_list(
            &test,
            (2, info),
            None,
            &mut reclaims,
            UpsertReclaim::IgnoreReclaims,
        );
        assert_eq!(test.slot_list.read().unwrap().len(), len);
        assert_eq!(len, 2);
        // update to same slot, should not increase
        let len = InMemAccountsIndex::<u64, u64>::lock_and_update_slot_list(
            &test,
            (2, info),
            None,
            &mut reclaims,
            UpsertReclaim::IgnoreReclaims,
        );
        assert_eq!(test.slot_list.read().unwrap().len(), len);
        assert_eq!(len, 2);
    }
}