1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545
//! ARCache - A concurrently readable adaptive replacement cache.
//!
//! An ARCache is used in place of a `RwLock<LruCache>` or `Mutex<LruCache>`.
//! This structure is transactional, meaning that readers have guaranteed
//! point-in-time views of the cache and their items, while allowing writers
//! to proceed with inclusions and cache state management in parallel.
//!
//! This means that unlike a `RwLock` which can have many readers OR one writer
//! this cache is capable of many readers, over multiple data generations AND
//! writers that are serialised. This formally means that this is an ACID
//! compliant Cache.
mod ll;
use self::ll::{LLNode, LLWeight, LL};
// use self::traits::ArcWeight;
use crate::cowcell::{CowCell, CowCellReadTxn};
use crate::hashmap::*;
// use crossbeam::channel::{bounded, Receiver, Sender};
use crossbeam::queue::ArrayQueue;
use parking_lot::{Mutex, RwLock};
use std::collections::HashMap as Map;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::borrow::Borrow;
use std::cell::UnsafeCell;
use std::convert::TryFrom;
use std::fmt::Debug;
use std::hash::Hash;
use std::mem;
use std::ops::Deref;
use std::ops::DerefMut;
use std::time::Instant;
// const READ_THREAD_MIN: usize = 8;
const READ_THREAD_RATIO: usize = 16;
/// Statistics related to the Arc
#[derive(Clone, Debug, PartialEq)]
pub struct CacheStats {
/// The number of hits during all read operations on the primary cache.
pub reader_hits: usize,
/// The number of hits during all read operations on the thread local caches.
pub reader_tlocal_hits: usize,
/// The number of inclusions through read operations.
pub reader_includes: usize,
/// The number of hits during all write operations.
pub write_hits: usize,
/// The number of inclusions or changes through write operations.
pub write_inc_or_mod: usize,
/// The maximum number of items in the shared cache.
pub shared_max: usize,
/// The number of items in the frequent set
pub freq: usize,
/// The number of items in the recent set
pub recent: usize,
/// The number of items evicted from the frequent set
pub freq_evicts: usize,
/// The number of items evicted from the recent set
pub recent_evicts: usize,
/// The current cache weight between recent and frequent.
pub p_weight: usize,
/// The number of keys seen through the cache's lifetime.
pub all_seen_keys: usize,
}
enum ThreadCacheItem<V> {
Present(V, bool, usize),
Removed(bool),
}
enum CacheEvent<K, V> {
Hit {
t: Instant,
k_hash: u64,
is_tlocal: bool,
},
Include {
t: Instant,
k: K,
v: V,
txid: u64,
size: usize,
},
}
#[derive(Hash, Ord, PartialOrd, Eq, PartialEq, Clone, Debug)]
struct CacheItemInner<K>
where
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
{
k: K,
txid: u64,
size: usize,
}
impl<K> LLWeight for CacheItemInner<K>
where
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
{
#[inline]
fn ll_weight(&self) -> usize {
self.size
}
}
#[derive(Clone, Debug)]
enum CacheItem<K, V>
where
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
{
Freq(*mut LLNode<CacheItemInner<K>>, V),
Rec(*mut LLNode<CacheItemInner<K>>, V),
GhostFreq(*mut LLNode<CacheItemInner<K>>),
GhostRec(*mut LLNode<CacheItemInner<K>>),
Haunted(*mut LLNode<CacheItemInner<K>>),
}
unsafe impl<
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
> Send for CacheItem<K, V>
{
}
unsafe impl<
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
> Sync for CacheItem<K, V>
{
}
#[cfg(test)]
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum CacheState {
Freq,
Rec,
GhostFreq,
GhostRec,
Haunted,
None,
}
#[cfg(test)]
#[derive(Debug, PartialEq)]
pub(crate) struct CStat {
max: usize,
cache: usize,
tlocal: usize,
freq: usize,
rec: usize,
ghost_freq: usize,
ghost_rec: usize,
haunted: usize,
p: usize,
}
struct ArcInner<K, V>
where
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
{
/// Weight of items between the two caches.
p: usize,
freq: LL<CacheItemInner<K>>,
rec: LL<CacheItemInner<K>>,
ghost_freq: LL<CacheItemInner<K>>,
ghost_rec: LL<CacheItemInner<K>>,
haunted: LL<CacheItemInner<K>>,
// rx: Receiver<CacheEvent<K, V>>,
queue: Arc<ArrayQueue<CacheEvent<K, V>>>,
min_txid: u64,
}
struct ArcShared<K, V>
where
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
{
// Max number of elements to cache.
max: usize,
// Max number of elements for a reader per thread.
read_max: usize,
// channels for readers.
// tx: Sender<CacheEvent<K, V>>,
queue: Arc<ArrayQueue<CacheEvent<K, V>>>,
/// The number of items that are present in the cache before we start to process
/// the arc sets/lists.
watermark: usize,
}
/// A concurrently readable adaptive replacement cache. Operations are performed on the
/// cache via read and write operations.
pub struct ARCache<K, V>
where
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
{
// Use a unified tree, allows simpler movement of items between the
// cache types.
cache: HashMap<K, CacheItem<K, V>>,
// This is normally only ever taken in "read" mode, so it's effectively
// an uncontended barrier.
shared: RwLock<ArcShared<K, V>>,
// These are only taken during a quiesce
inner: Mutex<ArcInner<K, V>>,
stats: CowCell<CacheStats>,
above_watermark: AtomicBool,
}
unsafe impl<
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
> Send for ARCache<K, V>
{
}
unsafe impl<
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
> Sync for ARCache<K, V>
{
}
#[derive(Debug, Clone)]
struct ReadCacheItem<K, V>
where
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
{
k: K,
v: V,
size: usize,
}
impl<K, V> LLWeight for ReadCacheItem<K, V>
where
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
{
#[inline]
fn ll_weight(&self) -> usize {
self.size
}
}
struct ReadCache<K, V>
where
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
{
// cache of our missed items to send forward.
// On drop we drain this to the channel
set: Map<K, *mut LLNode<ReadCacheItem<K, V>>>,
read_size: usize,
tlru: LL<ReadCacheItem<K, V>>,
}
/// An active read transaction over the cache. The data is this cache is guaranteed to be
/// valid at the point in time the read is created. You may include items during a cache
/// miss via the "insert" function.
pub struct ARCacheReadTxn<'a, K, V>
where
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
{
caller: &'a ARCache<K, V>,
// ro_txn to cache
cache: HashMapReadTxn<'a, K, CacheItem<K, V>>,
tlocal: Option<ReadCache<K, V>>,
// tx channel to send forward events.
// tx: Sender<CacheEvent<K, V>>,
queue: Arc<ArrayQueue<CacheEvent<K, V>>>,
above_watermark: bool,
}
unsafe impl<
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
> Send for ARCacheReadTxn<'_, K, V>
{
}
unsafe impl<
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
> Sync for ARCacheReadTxn<'_, K, V>
{
}
/// An active write transaction over the cache. The data in this cache is isolated
/// from readers, and may be rolled-back if an error occurs. Changes only become
/// globally visible once you call "commit". Items may be added to the cache on
/// a miss via "insert", and you can explicitly remove items by calling "remove".
pub struct ARCacheWriteTxn<'a, K, V>
where
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
{
caller: &'a ARCache<K, V>,
// wr_txn to cache
cache: HashMapWriteTxn<'a, K, CacheItem<K, V>>,
// Cache of missed items (w_ dirty/clean)
// On COMMIT we drain this to the main cache
tlocal: Map<K, ThreadCacheItem<V>>,
hit: UnsafeCell<Vec<u64>>,
clear: UnsafeCell<bool>,
above_watermark: bool,
}
/*
pub struct ArcReadSnapshot<K, V> {
// How to communicate back to the caller the loads we did?
tlocal: &mut Map<K, ThreadCacheItem<K, V>>,
}
*/
impl<
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
> CacheItem<K, V>
{
fn to_vref(&self) -> Option<&V> {
match &self {
CacheItem::Freq(_, v) | CacheItem::Rec(_, v) => Some(&v),
_ => None,
}
}
#[cfg(test)]
fn to_state(&self) -> CacheState {
match &self {
CacheItem::Freq(_, _v) => CacheState::Freq,
CacheItem::Rec(_, _v) => CacheState::Rec,
CacheItem::GhostFreq(_) => CacheState::GhostFreq,
CacheItem::GhostRec(_) => CacheState::GhostRec,
CacheItem::Haunted(_) => CacheState::Haunted,
}
}
}
macro_rules! drain_ll_to_ghost {
(
$cache:expr,
$ll:expr,
$gf:expr,
$gr:expr,
$txid:expr
) => {{
while $ll.len() > 0 {
let n = $ll.pop();
debug_assert!(!n.is_null());
unsafe {
// Set the item's evict txid.
(*n).as_mut().txid = $txid;
}
let mut r = $cache.get_mut(unsafe { &(*n).as_mut().k });
match r {
Some(ref mut ci) => {
let mut next_state = match &ci {
CacheItem::Freq(n, _) => {
$gf.append_n(*n);
CacheItem::GhostFreq(*n)
}
CacheItem::Rec(n, _) => {
$gr.append_n(*n);
CacheItem::GhostRec(*n)
}
_ => {
// Impossible state!
unreachable!();
}
};
// Now change the state.
mem::swap(*ci, &mut next_state);
}
None => {
// Impossible state!
unreachable!();
}
}
} // end while
}};
}
macro_rules! evict_to_len {
(
$cache:expr,
$ll:expr,
$to_ll:expr,
$size:expr,
$txid:expr
) => {{
debug_assert!($ll.len() >= $size);
while $ll.len() > $size {
let n = $ll.pop();
debug_assert!(!n.is_null());
let mut r = $cache.get_mut(unsafe { &(*n).as_mut().k });
unsafe {
// Set the item's evict txid.
(*n).as_mut().txid = $txid;
}
match r {
Some(ref mut ci) => {
let mut next_state = match &ci {
CacheItem::Freq(llp, _v) => {
debug_assert!(*llp == n);
// No need to extract, already popped!
// $ll.extract(*llp);
$to_ll.append_n(*llp);
CacheItem::GhostFreq(*llp)
}
CacheItem::Rec(llp, _v) => {
debug_assert!(*llp == n);
// No need to extract, already popped!
// $ll.extract(*llp);
$to_ll.append_n(*llp);
CacheItem::GhostRec(*llp)
}
_ => {
// Impossible state!
unreachable!();
}
};
// Now change the state.
mem::swap(*ci, &mut next_state);
}
None => {
// Impossible state!
unreachable!();
}
}
}
}};
}
macro_rules! evict_to_haunted_len {
(
$cache:expr,
$ll:expr,
$to_ll:expr,
$size:expr,
$txid:expr
) => {{
debug_assert!($ll.len() >= $size);
while $ll.len() > $size {
let n = $ll.pop();
debug_assert!(!n.is_null());
$to_ll.append_n(n);
let mut r = $cache.get_mut(unsafe { &(*n).as_mut().k });
unsafe {
// Set the item's evict txid.
(*n).as_mut().txid = $txid;
}
match r {
Some(ref mut ci) => {
// Now change the state.
let mut next_state = CacheItem::Haunted(n);
mem::swap(*ci, &mut next_state);
}
None => {
// Impossible state!
unreachable!();
}
};
}
}};
}
impl<
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
> ARCache<K, V>
{
/// Create a new ARCache, that derives it's size based on your expected workload.
///
/// The values are total number of items you want to have in memory, the number
/// of read threads you expect concurrently, the expected average number of cache
/// misses per read operation, and the expected average number of writes or write
/// cache misses per operation. The following formula is assumed:
///
/// `max + (threads * (max/16))`
/// ` + (threads * avg number of misses per op)`
/// ` + avg number of writes per transaction`
///
/// The cache may still exceed your provided total, and inaccurate tuning numbers
/// will yield a situation where you may use too-little ram, or too much. This could
/// be to your read misses exceeding your expected amount causing the queues to have
/// more items in them at a time, or your writes are larger than expected.
///
/// If you set ex_ro_miss to zero, no read thread local cache will be configured, but
/// space will still be reserved for channel communication.
pub fn new(
total: usize,
threads: usize,
ex_ro_miss: usize,
ex_rw_miss: usize,
read_cache: bool,
) -> Self {
let total = isize::try_from(total).unwrap();
let threads = isize::try_from(threads).unwrap();
let ro_miss = isize::try_from(ex_ro_miss).unwrap();
let wr_miss = isize::try_from(ex_rw_miss).unwrap();
let ratio = isize::try_from(READ_THREAD_RATIO).unwrap();
// I'd like to thank wolfram alpha ... for this magic.
let max = -((ratio * ((ro_miss * threads) + wr_miss - total)) / (ratio + threads));
let read_max = if read_cache { max / ratio } else { 0 };
let max = usize::try_from(max).unwrap();
let read_max = usize::try_from(read_max).unwrap();
Self::new_size(max, read_max)
}
/// Create a new ARCache, with a capacity of `max` main cache items and `read_max`
/// Note that due to the way the cache operates, the number of items can and
/// will exceed `max` on a regular basis, so you should consider using `new`
/// and specifying your expected workload parameters to have a better derived
/// cache size.
pub fn new_size(max: usize, read_max: usize) -> Self {
// Based on max, what should our watermark be?
let watermark = if max < 128 { 0 } else { (max / 20) * 16 };
Self::new_size_watermark(max, read_max, watermark)
}
/// See [new_size] for more information. This allows manual configuration of the data
/// tracking watermark. To disable this, set to 0. Watermark must be less than max.
pub fn new_size_watermark(max: usize, read_max: usize, watermark: usize) -> Self {
assert!(max > 0);
assert!(watermark <= max);
// for now we set the back pressure to 10% of max.
let chan_size = max / 10;
let chan_size = if chan_size < 16 { 16 } else { chan_size };
// let (tx, rx) = bounded(chan_size);
let queue = Arc::new(ArrayQueue::new(chan_size));
let shared = RwLock::new(ArcShared {
max,
read_max,
// tx,
queue: queue.clone(),
watermark,
});
let inner = Mutex::new(ArcInner {
p: 0,
freq: LL::new(),
rec: LL::new(),
ghost_freq: LL::new(),
ghost_rec: LL::new(),
haunted: LL::new(),
// rx,
queue,
min_txid: 0,
});
let stats = CowCell::new(CacheStats {
reader_hits: 0,
reader_tlocal_hits: 0,
reader_includes: 0,
write_hits: 0,
write_inc_or_mod: 0,
shared_max: 0,
freq: 0,
recent: 0,
freq_evicts: 0,
recent_evicts: 0,
p_weight: 0,
all_seen_keys: 0,
});
ARCache {
cache: HashMap::new(),
shared,
inner,
stats,
above_watermark: AtomicBool::new(true),
}
}
/// Begin a read operation on the cache. This reader has a thread-local cache for items
/// that are localled included via `insert`, and can communicate back to the main cache
/// to safely include items.
pub fn read(&self) -> ARCacheReadTxn<K, V> {
let rshared = self.shared.read();
let tlocal = if rshared.read_max > 0 {
Some(ReadCache {
set: Map::new(),
read_size: rshared.read_max,
tlru: LL::new(),
})
} else {
None
};
let above_watermark = self.above_watermark.load(Ordering::Relaxed);
ARCacheReadTxn {
caller: &self,
cache: self.cache.read(),
tlocal,
// tx: rshared.tx.clone(),
queue: rshared.queue.clone(),
above_watermark,
}
}
/// Begin a write operation on the cache. This writer has a thread-local store
/// for all items that have been included or dirtied in the transactions, items
/// may be removed from this cache (ie deleted, invalidated).
pub fn write(&self) -> ARCacheWriteTxn<K, V> {
let above_watermark = self.above_watermark.load(Ordering::Relaxed);
ARCacheWriteTxn {
caller: &self,
cache: self.cache.write(),
tlocal: Map::new(),
hit: UnsafeCell::new(Vec::new()),
clear: UnsafeCell::new(false),
above_watermark,
}
}
/// View the statistics for this cache. These values are a snapshot of a point in
/// time and may not be accurate at "this exact moment".
pub fn view_stats(&self) -> CowCellReadTxn<CacheStats> {
self.stats.read()
}
fn try_write(&self) -> Option<ARCacheWriteTxn<K, V>> {
self.cache.try_write().map(|cache| {
let above_watermark = self.above_watermark.load(Ordering::Relaxed);
ARCacheWriteTxn {
caller: &self,
cache,
tlocal: Map::new(),
hit: UnsafeCell::new(Vec::new()),
clear: UnsafeCell::new(false),
above_watermark,
}
})
}
fn try_quiesce(&self) {
if let Some(wr_txn) = self.try_write() {
wr_txn.commit()
};
}
fn calc_p_freq(ghost_rec_len: usize, ghost_freq_len: usize, p: &mut usize) {
let delta = if ghost_rec_len > ghost_freq_len {
ghost_rec_len / ghost_freq_len
} else {
1
};
if delta < *p {
*p -= delta
} else {
*p = 0
}
}
fn calc_p_rec(cap: usize, ghost_rec_len: usize, ghost_freq_len: usize, p: &mut usize) {
let delta = if ghost_freq_len > ghost_rec_len {
ghost_freq_len / ghost_rec_len
} else {
1
};
if delta <= cap - *p {
*p += delta
} else {
*p = cap
}
}
fn drain_tlocal_inc<'a>(
&'a self,
cache: &mut HashMapWriteTxn<'a, K, CacheItem<K, V>>,
inner: &mut ArcInner<K, V>,
shared: &ArcShared<K, V>,
// stats: &mut CacheStats,
tlocal: Map<K, ThreadCacheItem<V>>,
commit_txid: u64,
) {
// drain tlocal into the main cache.
tlocal.into_iter().for_each(|(k, tcio)| {
let r = cache.get_mut(&k);
match (r, tcio) {
(None, ThreadCacheItem::Present(tci, clean, size)) => {
assert!(clean);
let llp = inner.rec.append_k(CacheItemInner {
k: k.clone(),
txid: commit_txid,
size,
});
cache.insert(k, CacheItem::Rec(llp, tci));
}
(None, ThreadCacheItem::Removed(clean)) => {
assert!(clean);
// Mark this as haunted
let llp = inner.haunted.append_k(CacheItemInner {
k: k.clone(),
txid: commit_txid,
size: 1,
});
cache.insert(k, CacheItem::Haunted(llp));
}
(Some(ref mut ci), ThreadCacheItem::Removed(clean)) => {
assert!(clean);
// From whatever set we were in, pop and move to haunted.
let mut next_state = match ci {
CacheItem::Freq(llp, _v) => {
// println!("tlocal {:?} Freq -> Freq", k);
inner.freq.extract(*llp);
unsafe { (**llp).as_mut().txid = commit_txid };
inner.haunted.append_n(*llp);
CacheItem::Haunted(*llp)
}
CacheItem::Rec(llp, _v) => {
// println!("tlocal {:?} Rec -> Freq", k);
// Remove the node and put it into freq.
inner.rec.extract(*llp);
unsafe { (**llp).as_mut().txid = commit_txid };
inner.haunted.append_n(*llp);
CacheItem::Haunted(*llp)
}
CacheItem::GhostFreq(llp) => {
// println!("tlocal {:?} GhostFreq -> Freq", k);
inner.ghost_freq.extract(*llp);
unsafe { (**llp).as_mut().txid = commit_txid };
inner.haunted.append_n(*llp);
CacheItem::Haunted(*llp)
}
CacheItem::GhostRec(llp) => {
// println!("tlocal {:?} GhostRec -> Rec", k);
inner.ghost_rec.extract(*llp);
unsafe { (**llp).as_mut().txid = commit_txid };
inner.haunted.append_n(*llp);
CacheItem::Haunted(*llp)
}
CacheItem::Haunted(llp) => {
// println!("tlocal {:?} Haunted -> Rec", k);
unsafe { (**llp).as_mut().txid = commit_txid };
CacheItem::Haunted(*llp)
}
};
// Now change the state.
mem::swap(*ci, &mut next_state);
}
// TODO: https://github.com/rust-lang/rust/issues/68354 will stabilise
// in 1.44 so we can prevent a need for a clone.
(Some(ref mut ci), ThreadCacheItem::Present(ref tci, clean, size)) => {
assert!(clean);
// * as we include each item, what state was it in before?
// It's in the cache - what action must we take?
let mut next_state = match ci {
CacheItem::Freq(llp, _v) => {
// println!("tlocal {:?} Freq -> Freq", k);
inner.freq.extract(*llp);
unsafe { (**llp).as_mut().txid = commit_txid };
unsafe { (**llp).as_mut().size = size };
// Move the list item to it's head.
inner.freq.append_n(*llp);
// Update v.
CacheItem::Freq(*llp, (*tci).clone())
}
CacheItem::Rec(llp, _v) => {
// println!("tlocal {:?} Rec -> Freq", k);
// Remove the node and put it into freq.
inner.rec.extract(*llp);
unsafe { (**llp).as_mut().txid = commit_txid };
unsafe { (**llp).as_mut().size = size };
inner.freq.append_n(*llp);
CacheItem::Freq(*llp, (*tci).clone())
}
CacheItem::GhostFreq(llp) => {
// println!("tlocal {:?} GhostFreq -> Freq", k);
// Ajdust p
Self::calc_p_freq(
inner.ghost_rec.len(),
inner.ghost_freq.len(),
&mut inner.p,
);
inner.ghost_freq.extract(*llp);
unsafe { (**llp).as_mut().txid = commit_txid };
unsafe { (**llp).as_mut().size = size };
inner.freq.append_n(*llp);
CacheItem::Freq(*llp, (*tci).clone())
}
CacheItem::GhostRec(llp) => {
// println!("tlocal {:?} GhostRec -> Rec", k);
// Ajdust p
Self::calc_p_rec(
shared.max,
inner.ghost_rec.len(),
inner.ghost_freq.len(),
&mut inner.p,
);
inner.ghost_rec.extract(*llp);
unsafe { (**llp).as_mut().txid = commit_txid };
unsafe { (**llp).as_mut().size = size };
inner.rec.append_n(*llp);
CacheItem::Rec(*llp, (*tci).clone())
}
CacheItem::Haunted(llp) => {
// println!("tlocal {:?} Haunted -> Rec", k);
inner.haunted.extract(*llp);
unsafe { (**llp).as_mut().txid = commit_txid };
unsafe { (**llp).as_mut().size = size };
inner.rec.append_n(*llp);
CacheItem::Rec(*llp, (*tci).clone())
}
};
// Now change the state.
mem::swap(*ci, &mut next_state);
}
}
});
}
fn drain_rx<'a>(
&'a self,
cache: &mut HashMapWriteTxn<'a, K, CacheItem<K, V>>,
inner: &mut ArcInner<K, V>,
shared: &ArcShared<K, V>,
stats: &mut CacheStats,
commit_ts: Instant,
) {
// * for each item
// while let Ok(ce) = inner.rx.try_recv() {
while let Some(ce) = inner.queue.pop() {
let t = match ce {
// Update if it was hit.
CacheEvent::Hit {
t,
k_hash,
is_tlocal,
} => {
if is_tlocal {
stats.reader_tlocal_hits += 1;
} else {
stats.reader_hits += 1;
}
if let Some(ref mut ci_slots) = unsafe { cache.get_slot_mut(k_hash) } {
for ref mut ci in ci_slots.iter_mut() {
let mut next_state = match &ci.v {
CacheItem::Freq(llp, v) => {
// println!("rxhit {:?} Freq -> Freq", k);
inner.freq.touch(*llp);
CacheItem::Freq(*llp, v.clone())
}
CacheItem::Rec(llp, v) => {
// println!("rxhit {:?} Rec -> Freq", k);
inner.rec.extract(*llp);
inner.freq.append_n(*llp);
CacheItem::Freq(*llp, v.clone())
}
// While we can't add this from nothing, we can
// at least keep it in the ghost sets.
CacheItem::GhostFreq(llp) => {
// println!("rxhit {:?} GhostFreq -> GhostFreq", k);
inner.ghost_freq.touch(*llp);
CacheItem::GhostFreq(*llp)
}
CacheItem::GhostRec(llp) => {
// println!("rxhit {:?} GhostRec -> GhostRec", k);
inner.ghost_rec.touch(*llp);
CacheItem::GhostRec(*llp)
}
CacheItem::Haunted(llp) => {
// println!("rxhit {:?} Haunted -> Haunted", k);
// We can't do anything about this ...
CacheItem::Haunted(*llp)
}
};
mem::swap(&mut (*ci).v, &mut next_state);
} // for each item in the bucket.
}
// Do nothing, it must have been evicted.
t
}
// Update if it was inc
CacheEvent::Include {
t,
k,
v: iv,
txid,
size,
} => {
stats.reader_includes += 1;
let mut r = cache.get_mut(&k);
match r {
Some(ref mut ci) => {
let mut next_state = match &ci {
CacheItem::Freq(llp, _v) => {
if unsafe { (**llp).as_ref().txid >= txid }
|| inner.min_txid > txid
{
// println!("rxinc {:?} Freq -> Freq (touch only)", k);
// Our cache already has a newer value, keep it.
inner.freq.touch(*llp);
None
} else {
// println!("rxinc {:?} Freq -> Freq (update)", k);
// The value is newer, update.
inner.freq.extract(*llp);
unsafe { (**llp).as_mut().txid = txid };
unsafe { (**llp).as_mut().size = size };
inner.freq.append_n(*llp);
Some(CacheItem::Freq(*llp, iv))
}
}
CacheItem::Rec(llp, v) => {
inner.rec.extract(*llp);
if unsafe { (**llp).as_ref().txid >= txid }
|| inner.min_txid > txid
{
// println!("rxinc {:?} Rec -> Freq (touch only)", k);
inner.freq.append_n(*llp);
Some(CacheItem::Freq(*llp, v.clone()))
} else {
// println!("rxinc {:?} Rec -> Freq (update)", k);
unsafe { (**llp).as_mut().txid = txid };
unsafe { (**llp).as_mut().size = size };
inner.freq.append_n(*llp);
Some(CacheItem::Freq(*llp, iv))
}
}
CacheItem::GhostFreq(llp) => {
// Adjust p
Self::calc_p_freq(
inner.ghost_rec.len(),
inner.ghost_freq.len(),
&mut inner.p,
);
if unsafe { (**llp).as_ref().txid > txid }
|| inner.min_txid > txid
{
// println!("rxinc {:?} GhostFreq -> GhostFreq", k);
// The cache version is newer, this is just a hit.
inner.ghost_freq.touch(*llp);
None
} else {
// This item is newer, so we can include it.
// println!("rxinc {:?} GhostFreq -> Rec", k);
inner.ghost_freq.extract(*llp);
unsafe { (**llp).as_mut().txid = txid };
unsafe { (**llp).as_mut().size = size };
inner.freq.append_n(*llp);
Some(CacheItem::Freq(*llp, iv))
}
}
CacheItem::GhostRec(llp) => {
// Adjust p
Self::calc_p_rec(
shared.max,
inner.ghost_rec.len(),
inner.ghost_freq.len(),
&mut inner.p,
);
if unsafe { (**llp).as_ref().txid > txid }
|| inner.min_txid > txid
{
// println!("rxinc {:?} GhostRec -> GhostRec", k);
inner.ghost_rec.touch(*llp);
None
} else {
// println!("rxinc {:?} GhostRec -> Rec", k);
inner.ghost_rec.extract(*llp);
unsafe { (**llp).as_mut().txid = txid };
unsafe { (**llp).as_mut().size = size };
inner.rec.append_n(*llp);
Some(CacheItem::Rec(*llp, iv))
}
}
CacheItem::Haunted(llp) => {
if unsafe { (**llp).as_ref().txid > txid }
|| inner.min_txid > txid
{
// println!("rxinc {:?} Haunted -> Haunted", k);
None
} else {
// println!("rxinc {:?} Haunted -> Rec", k);
inner.haunted.extract(*llp);
unsafe { (**llp).as_mut().txid = txid };
unsafe { (**llp).as_mut().size = size };
inner.rec.append_n(*llp);
Some(CacheItem::Rec(*llp, iv))
}
}
};
if let Some(ref mut next_state) = next_state {
mem::swap(*ci, next_state);
}
}
None => {
// It's not present - include it!
// println!("rxinc {:?} None -> Rec", k);
if txid >= inner.min_txid {
let llp = inner.rec.append_k(CacheItemInner {
k: k.clone(),
txid,
size,
});
cache.insert(k, CacheItem::Rec(llp, iv));
}
}
};
t
}
};
// Stop processing the queue, we are up to "now".
if t >= commit_ts {
break;
}
}
}
fn drain_tlocal_hits<'a>(
&'a self,
cache: &mut HashMapWriteTxn<'a, K, CacheItem<K, V>>,
inner: &mut ArcInner<K, V>,
// shared: &ArcShared<K, V>,
// stats: &mut CacheStats,
commit_txid: u64,
hit: Vec<u64>,
) {
hit.into_iter().for_each(|k_hash| {
// * everything hit must be in main cache now, so bring these
// all to the relevant item heads.
// * Why do this last? Because the write is the "latest" we want all the fresh
// written items in the cache over the "read" hits, it gives us some aprox
// of time ordering, but not perfect.
// Find the item in the cache.
// * based on it's type, promote it in the correct list, or move it.
// How does this prevent incorrect promotion from rec to freq? txid?
// println!("Checking Hit ... {:?}", k);
let mut r = unsafe { cache.get_slot_mut(k_hash) };
match r {
Some(ref mut ci_slots) => {
for ref mut ci in ci_slots.iter_mut() {
// This differs from above - we skip if we don't touch anything
// that was added in this txn. This is to prevent double touching
// anything that was included in a write.
let mut next_state = match &ci.v {
CacheItem::Freq(llp, v) => {
if unsafe { (**llp).as_ref().txid != commit_txid } {
// println!("hit {:?} Freq -> Freq", k);
inner.freq.touch(*llp);
Some(CacheItem::Freq(*llp, v.clone()))
} else {
None
}
}
CacheItem::Rec(llp, v) => {
if unsafe { (**llp).as_ref().txid != commit_txid } {
// println!("hit {:?} Rec -> Freq", k);
inner.rec.extract(*llp);
inner.freq.append_n(*llp);
Some(CacheItem::Freq(*llp, v.clone()))
} else {
None
}
}
_ => {
// Ignore hits on items that may have been cleared.
None
}
};
// Now change the state.
if let Some(ref mut next_state) = next_state {
mem::swap(&mut (*ci).v, next_state);
}
} // for each ci in slots
}
None => {
// Impossible state!
unreachable!();
}
}
});
}
#[allow(clippy::cognitive_complexity)]
fn evict<'a>(
&'a self,
cache: &mut HashMapWriteTxn<'a, K, CacheItem<K, V>>,
inner: &mut ArcInner<K, V>,
shared: &ArcShared<K, V>,
stats: &mut CacheStats,
commit_txid: u64,
) {
debug_assert!(inner.p <= shared.max);
// Convince the compiler copying is okay.
let p = inner.p;
stats.p_weight = p;
if inner.rec.len() + inner.freq.len() > shared.max {
// println!("Checking cache evict");
/*
println!(
"from -> rec {:?}, freq {:?}",
inner.rec.len(),
inner.freq.len()
);
*/
let delta = (inner.rec.len() + inner.freq.len()) - shared.max;
// We have overflowed by delta. As we are not "evicting as we go" we have to work out
// what we should have evicted up to now.
//
// keep removing from rec until == p OR delta == 0, and if delta remains, then remove from freq.
let rec_to_len = if inner.p == 0 {
// println!("p == 0 => {:?}", inner.rec.len());
debug_assert!(delta <= inner.rec.len());
// We are fully weight to freq, so only remove in rec.
inner.rec.len() - delta
} else if inner.rec.len() > inner.p {
// There is a partial weighting, how much do we need to move?
let rec_delta = inner.rec.len() - inner.p;
if rec_delta > delta {
/*
println!(
"p ({:?}) <= rec ({:?}), rec_delta ({:?}) > delta ({:?})",
inner.p,
inner.rec.len(),
rec_delta,
delta
);
*/
// We will have removed enough through delta alone in rec.
inner.rec.len() - delta
} else {
/*
println!(
"p ({:?}) <= rec ({:?}), rec_delta ({:?}) <= delta ({:?})",
inner.p,
inner.rec.len(),
rec_delta,
delta
);
*/
// Remove the full delta, and excess will be removed from freq.
inner.rec.len() - rec_delta
}
} else {
// rec is already below p, therefore we must need to remove in freq, and
// we need to consider how much is in rec.
// println!("p ({:?}) > rec ({:?})", inner.p, inner.rec.len());
inner.rec.len()
};
// Now we can get the expected sizes;
debug_assert!(shared.max >= rec_to_len);
let freq_to_len = shared.max - rec_to_len;
// println!("move to -> rec {:?}, freq {:?}", rec_to_len, freq_to_len);
debug_assert!(freq_to_len + rec_to_len <= shared.max);
stats.freq_evicts += inner.freq.len() - freq_to_len;
stats.recent_evicts += inner.rec.len() - rec_to_len;
evict_to_len!(
cache,
inner.rec,
&mut inner.ghost_rec,
rec_to_len,
commit_txid
);
evict_to_len!(
cache,
inner.freq,
&mut inner.ghost_freq,
freq_to_len,
commit_txid
);
// Finally, do an evict of the ghost sets if they are too long - these are weighted
// inverse to the above sets. Note the freq to len in ghost rec, and rec to len in
// ghost freq!
if inner.ghost_rec.len() > (shared.max - p) {
evict_to_haunted_len!(
cache,
inner.ghost_rec,
&mut inner.haunted,
freq_to_len,
commit_txid
);
}
if inner.ghost_freq.len() > p {
evict_to_haunted_len!(
cache,
inner.ghost_freq,
&mut inner.haunted,
rec_to_len,
commit_txid
);
}
}
}
#[allow(clippy::unnecessary_mut_passed)]
fn commit<'a>(
&'a self,
mut cache: HashMapWriteTxn<'a, K, CacheItem<K, V>>,
tlocal: Map<K, ThreadCacheItem<V>>,
hit: Vec<u64>,
clear: bool,
init_above_watermark: bool,
) {
// What is the time?
let commit_ts = Instant::now();
let commit_txid = cache.get_txid();
// Copy p + init cache sizes for adjustment.
let mut inner = self.inner.lock();
let shared = self.shared.read();
let mut stat_guard = self.stats.write();
let stats = stat_guard.get_mut();
// Did we request to be cleared? If so, we move everything to a ghost set
// that was live.
//
// we also set the min_txid watermark which prevents any inclusion of
// any item that existed before this point in time.
if clear {
// Set the watermark of this txn.
inner.min_txid = commit_txid;
// Indicate that we evicted all to ghost/freq
stats.freq_evicts += inner.freq.len();
stats.recent_evicts += inner.rec.len();
// Move everything active into ghost sets.
drain_ll_to_ghost!(
&mut cache,
inner.freq,
inner.ghost_freq,
inner.ghost_rec,
commit_txid
);
drain_ll_to_ghost!(
&mut cache,
inner.rec,
inner.ghost_freq,
inner.ghost_rec,
commit_txid
);
}
// Why is it okay to drain the rx/tlocal and create the cache in a temporary
// oversize? Because these values in the queue/tlocal are already in memory
// and we are moving them to the cache, we are not actually using any more
// memory (well, not significantly more). By adding everything, then evicting
// we also get better and more accurate hit patterns over the cache based on what
// was used. This gives us an advantage over other cache types - we can see
// patterns based on temporal usage that other caches can't, at the expense that
// it may take some moments for that cache pattern to sync to the main thread.
stats.write_inc_or_mod += tlocal.len();
self.drain_tlocal_inc(
&mut cache,
inner.deref_mut(),
shared.deref(),
tlocal,
commit_txid,
);
// drain rx until empty or time >= time.
self.drain_rx(
&mut cache,
inner.deref_mut(),
shared.deref(),
stats,
commit_ts,
);
stats.write_hits += hit.len();
// drain the tlocal hits into the main cache.
self.drain_tlocal_hits(&mut cache, inner.deref_mut(), commit_txid, hit);
// now clean the space for each of the primary caches, evicting into the ghost sets.
// * It's possible that both caches are now over-sized if rx was empty
// but wr inc many items.
// * p has possibly changed width, causing a balance shift
// * and ghost items have been included changing ghost list sizes.
// so we need to do a clean up/balance of all the list lengths.
self.evict(
&mut cache,
inner.deref_mut(),
shared.deref(),
stats,
commit_txid,
);
stats.shared_max = shared.max;
stats.freq = inner.freq.len();
stats.recent = inner.rec.len();
stats.all_seen_keys = cache.len();
// Indicate if we are at/above watermark, so that read/writers begin to indicate their
// hit events so we can start to setup/order our arc sets correctly.
//
// If we drop below this again, they'll go back to just insert/remove content only mode.
if init_above_watermark {
if (inner.freq.len() + inner.rec.len()) < shared.watermark {
self.above_watermark.store(false, Ordering::Relaxed);
}
} else {
if (inner.freq.len() + inner.rec.len()) >= shared.watermark {
self.above_watermark.store(true, Ordering::Relaxed);
}
}
// Commit the stats
stat_guard.commit();
// commit on the wr txn.
cache.commit();
// done!
// eprintln!("quiesce took - {:?}", commit_ts.elapsed());
}
}
impl<
'a,
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
> ARCacheWriteTxn<'a, K, V>
{
/// Commit the changes of this writer, making them globally visible. This causes
/// all items written to this thread's local store to become visible in the main
/// cache.
///
/// To rollback (abort) and operation, just do not call commit (consider std::mem::drop
/// on the write transaction)
pub fn commit(self) {
self.caller.commit(
self.cache,
self.tlocal,
self.hit.into_inner(),
self.clear.into_inner(),
self.above_watermark,
)
}
/// Clear all items of the cache. This operation does not take effect until you commit.
/// After calling "clear", you may then include new items which will be stored thread
/// locally until you commit.
pub fn clear(&mut self) {
// Mark that we have been requested to clear the cache.
unsafe {
let clear_ptr = self.clear.get();
*clear_ptr = true;
}
// Dump the hit log.
unsafe {
let hit_ptr = self.hit.get();
(*hit_ptr).clear();
}
// Dump the thread local state.
self.tlocal.clear();
// From this point any get will miss on the main cache.
// Inserts are accepted.
}
/// Attempt to retieve a k-v pair from the cache. If it is present in the main cache OR
/// the thread local cache, a `Some` is returned, else you will recieve a `None`. On a
/// `None`, you must then consult the external data source that this structure is acting
/// as a cache for.
pub fn get<'b, Q: ?Sized>(&'a self, k: &'b Q) -> Option<&'a V>
where
K: Borrow<Q>,
Q: Hash + Eq + Ord,
{
let k_hash: u64 = self.cache.prehash(k);
let r: Option<&V> = if let Some(tci) = self.tlocal.get(k) {
match tci {
ThreadCacheItem::Present(v, _clean, _size) => {
let v = v as *const _;
unsafe { Some(&(*v)) }
}
ThreadCacheItem::Removed(_clean) => {
return None;
}
}
} else {
// If we have been requested to clear, the main cache is "empty"
// but we can't do that until a commit, so we just flag it and avoid.
let is_cleared = unsafe {
let clear_ptr = self.clear.get();
*clear_ptr
};
if !is_cleared {
if let Some(v) = self.cache.get_prehashed(k, k_hash) {
(*v).to_vref()
} else {
None
}
} else {
None
}
};
// How do we track this was a hit?
// Remember, we don't track misses - they are *implied* by the fact they'll trigger
// an inclusion from the external system. Subsequent, any further re-hit on an
// included value WILL be tracked, allowing arc to adjust appropriately.
if self.above_watermark && r.is_some() {
unsafe {
let hit_ptr = self.hit.get();
(*hit_ptr).push(k_hash);
}
}
r
}
/// Determine if this cache contains the following key.
pub fn contains_key<'b, Q: ?Sized>(&'a self, k: &'b Q) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq + Ord,
{
self.get(k).is_some()
}
/// Add a value to the cache. This may be because you have had a cache miss and
/// now wish to include in the thread local storage, or because you have written
/// a new value and want it to be submitted for caching. This item is marked as
/// clean, IE you have synced it to whatever associated store exists.
pub fn insert(&mut self, k: K, v: V) {
self.tlocal.insert(k, ThreadCacheItem::Present(v, true, 1));
}
/// Insert an item to the cache, with an associated weight/size factor. See also [insert]
pub fn insert_sized(&mut self, k: K, v: V, size: usize) {
self.tlocal
.insert(k, ThreadCacheItem::Present(v, true, size));
}
/// Remove this value from the thread local cache IE mask from from being
/// returned until this thread performs an insert. This item is marked as clean
/// IE you have synced it to whatever associated store exists.
pub fn remove(&mut self, k: K) {
self.tlocal.insert(k, ThreadCacheItem::Removed(true));
}
/// Add a value to the cache. This may be because you have had a cache miss and
/// now wish to include in the thread local storage, or because you have written
/// a new value and want it to be submitted for caching. This item is marked as
/// dirty, because you have *not* synced it. You MUST call iter_mut_mark_clean before calling
/// `commit` on this transaction, or a panic will occur.
pub fn insert_dirty(&mut self, k: K, v: V) {
self.tlocal.insert(k, ThreadCacheItem::Present(v, false, 1));
}
/// Insert a dirty item to the cache, with an associated weight/size factor. See also [insert_dirty]
pub fn insert_dirty_sized(&mut self, k: K, v: V, size: usize) {
self.tlocal
.insert(k, ThreadCacheItem::Present(v, false, size));
}
/// Remove this value from the thread local cache IE mask from from being
/// returned until this thread performs an insert. This item is marked as
/// dirty, because you have *not* synced it. You MUST call iter_mut_mark_clean before calling
/// `commit` on this transaction, or a panic will occur.
pub fn remove_dirty(&mut self, k: K) {
self.tlocal.insert(k, ThreadCacheItem::Removed(false));
}
/// Determines if dirty elements exist in this cache or not.
pub fn is_dirty(&self) -> bool {
self.iter_dirty().take(1).next().is_some()
}
/// Yields an iterator over all values that are currently dirty. As the iterator
/// progresses, items will NOT be marked clean. This allows you to examine
/// any currently dirty items in the cache.
pub fn iter_dirty(&self) -> impl Iterator<Item = (&K, Option<&V>)> {
self.tlocal
.iter()
.filter(|(_k, v)| match v {
ThreadCacheItem::Present(_v, c, _size) => !c,
ThreadCacheItem::Removed(c) => !c,
})
.map(|(k, v)| {
// Get the data.
let data = match v {
ThreadCacheItem::Present(v, _c, _size) => Some(v),
ThreadCacheItem::Removed(_c) => None,
};
(k, data)
})
}
/// Yields a mutable iterator over all values that are currently dirty. As the iterator
/// progresses, items will NOT be marked clean. This allows you to modify and
/// change any currently dirty items as required.
pub fn iter_mut_dirty(&mut self) -> impl Iterator<Item = (&K, Option<&mut V>)> {
self.tlocal
.iter_mut()
.filter(|(_k, v)| match v {
ThreadCacheItem::Present(_v, c, _size) => !c,
ThreadCacheItem::Removed(c) => !c,
})
.map(|(k, v)| {
// Get the data.
let data = match v {
ThreadCacheItem::Present(v, _c, _size) => Some(v),
ThreadCacheItem::Removed(_c) => None,
};
(k, data)
})
}
/// Yields an iterator over all values that are currently dirty. As the iterator
/// progresses, items will be marked clean. This is where you should sync dirty
/// cache content to your associated store. The iterator is K, Option<V>, where
/// the Option<V> indicates if the item has been remove (None) or is updated (Some).
pub fn iter_mut_mark_clean(&mut self) -> impl Iterator<Item = (&K, Option<&mut V>)> {
self.tlocal
.iter_mut()
.filter(|(_k, v)| match v {
ThreadCacheItem::Present(_v, c, _size) => !c,
ThreadCacheItem::Removed(c) => !c,
})
.map(|(k, v)| {
// Mark it clean.
match v {
ThreadCacheItem::Present(_v, c, _size) => *c = true,
ThreadCacheItem::Removed(c) => *c = true,
}
// Get the data.
let data = match v {
ThreadCacheItem::Present(v, _c, _size) => Some(v),
ThreadCacheItem::Removed(_c) => None,
};
(k, data)
})
}
#[cfg(test)]
pub(crate) fn iter_rec(&self) -> impl Iterator<Item = &K> {
self.cache.values().filter_map(|ci| match &ci {
CacheItem::Rec(lln, _) => unsafe {
let cii = &*((**lln).k.as_ptr());
Some(&cii.k)
},
_ => None,
})
}
#[cfg(test)]
pub(crate) fn iter_ghost_rec(&self) -> impl Iterator<Item = &K> {
self.cache.values().filter_map(|ci| match &ci {
CacheItem::GhostRec(lln) => unsafe {
let cii = &*((**lln).k.as_ptr());
Some(&cii.k)
},
_ => None,
})
}
#[cfg(test)]
pub(crate) fn iter_ghost_freq(&self) -> impl Iterator<Item = &K> {
self.cache.values().filter_map(|ci| match &ci {
CacheItem::GhostFreq(lln) => unsafe {
let cii = &*((**lln).k.as_ptr());
Some(&cii.k)
},
_ => None,
})
}
#[cfg(test)]
pub(crate) fn peek_hit(&self) -> &[u64] {
let hit_ptr = self.hit.get();
unsafe { &(*hit_ptr) }
}
#[cfg(test)]
pub(crate) fn peek_cache<'b, Q: ?Sized>(&'a self, k: &'b Q) -> CacheState
where
K: Borrow<Q>,
Q: Hash + Eq + Ord,
{
if let Some(v) = self.cache.get(k) {
(*v).to_state()
} else {
CacheState::None
}
}
#[cfg(test)]
pub(crate) fn peek_stat(&self) -> CStat {
let inner = self.caller.inner.lock();
let shared = self.caller.shared.read();
CStat {
max: shared.max,
cache: self.cache.len(),
tlocal: self.tlocal.len(),
freq: inner.freq.len(),
rec: inner.rec.len(),
ghost_freq: inner.ghost_freq.len(),
ghost_rec: inner.ghost_rec.len(),
haunted: inner.haunted.len(),
p: inner.p,
}
}
// get_mut
// If it's in tlocal, return that as get_mut
// if it's in the cache, clone to tlocal, then get_mut to tlock
// if not, return none.
// to_snapshot
}
impl<
'a,
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
> ARCacheReadTxn<'a, K, V>
{
/// Attempt to retieve a k-v pair from the cache. If it is present in the main cache OR
/// the thread local cache, a `Some` is returned, else you will recieve a `None`. On a
/// `None`, you must then consult the external data source that this structure is acting
/// as a cache for.
pub fn get<'b, Q: ?Sized>(&'b self, k: &'b Q) -> Option<&'b V>
where
K: Borrow<Q>,
Q: Hash + Eq + Ord,
{
let k_hash: u64 = self.cache.prehash(k);
let r: Option<&V> = self
.tlocal
.as_ref()
.and_then(|cache| {
cache.set.get(k).map(|v| unsafe {
// Indicate a hit on the tlocal cache.
if self.above_watermark {
// let _ = self.tx.try_send(
let _ = self.queue.push(CacheEvent::Hit {
t: Instant::now(),
k_hash,
is_tlocal: true,
});
}
let v = &(**v).as_ref().v as *const _;
// This discards the lifetime and repins it to &'b.
&(*v)
})
})
.or_else(|| {
self.cache.get_prehashed(k, k_hash).and_then(|v| {
(*v).to_vref().map(|vin| unsafe {
// Indicate a hit on the main cache.
if self.above_watermark {
// let _ = self.tx.try_send(
let _ = self.queue.push(CacheEvent::Hit {
t: Instant::now(),
k_hash,
is_tlocal: false,
});
}
let vin = vin as *const _;
&(*vin)
})
})
});
r
}
/// Determine if this cache contains the following key.
pub fn contains_key<'b, Q: ?Sized>(&mut self, k: &'b Q) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq + Ord,
{
self.get(k).is_some()
}
/// Insert an item to the cache, with an associated weight/size factor. See also [insert]
pub fn insert_sized(&mut self, k: K, v: V, size: usize) {
let mut v = v;
// Send a copy forward through time and space.
// let _ = self.tx.try_send(
let _ = self.queue.push(CacheEvent::Include {
t: Instant::now(),
k: k.clone(),
v: v.clone(),
txid: self.cache.get_txid(),
size,
});
// We have a cache, so lets update it.
if let Some(ref mut cache) = self.tlocal {
let n = if cache.tlru.len() >= cache.read_size {
let n = cache.tlru.pop();
// swap the old_key/old_val out
let mut k_clone = k.clone();
unsafe {
mem::swap(&mut k_clone, &mut (*n).as_mut().k);
mem::swap(&mut v, &mut (*n).as_mut().v);
}
// remove old K from the tree:
cache.set.remove(&k_clone);
n
} else {
// Just add it!
cache.tlru.append_k(ReadCacheItem {
k: k.clone(),
v,
size,
})
};
let r = cache.set.insert(k, n);
// There should never be a previous value.
assert!(r.is_none());
}
}
/// Add a value to the cache. This may be because you have had a cache miss and
/// now wish to include in the thread local storage.
///
/// Note that is invalid to insert an item who's key already exists in this thread local cache,
/// and this is asserted IE will panic if you attempt this. It is also invalid for you to insert
/// a value that does not match the source-of-truth state, IE inserting a different
/// value than another thread may percieve. This is a *read* thread, so you should only be adding
/// values that are relevant to this read transaction and this point in time. If you do not
/// heed this warning, you may alter the fabric of time and space and have some interesting
/// distortions in your data over time.
pub fn insert(&mut self, k: K, v: V) {
self.insert_sized(k, v, 1)
}
}
impl<
'a,
K: Hash + Eq + Ord + Clone + Debug + Sync + Send + 'static,
V: Clone + Debug + Sync + Send + 'static,
> Drop for ARCacheReadTxn<'a, K, V>
{
fn drop(&mut self) {
self.caller.try_quiesce();
}
}
#[cfg(test)]
mod tests {
use crate::arcache::ARCache as Arc;
use crate::arcache::CStat;
use crate::arcache::CacheState;
#[test]
fn test_cache_arc_basic() {
let arc: Arc<usize, usize> = Arc::new_size(4, 4);
let mut wr_txn = arc.write();
assert!(wr_txn.get(&1) == None);
assert!(wr_txn.peek_hit().len() == 0);
wr_txn.insert(1, 1);
assert!(wr_txn.get(&1) == Some(&1));
assert!(wr_txn.peek_hit().len() == 1);
wr_txn.commit();
// Now we start the second txn, and see if it's in there.
let wr_txn = arc.write();
assert!(wr_txn.peek_cache(&1) == CacheState::Rec);
assert!(wr_txn.get(&1) == Some(&1));
assert!(wr_txn.peek_hit().len() == 1);
wr_txn.commit();
// And now check it's moved to Freq due to the extra
let wr_txn = arc.write();
assert!(wr_txn.peek_cache(&1) == CacheState::Freq);
println!("{:?}", wr_txn.peek_stat());
}
#[test]
fn test_cache_evict() {
println!("== 1");
let arc: Arc<usize, usize> = Arc::new_size(4, 4);
let mut wr_txn = arc.write();
assert!(
CStat {
max: 4,
cache: 0,
tlocal: 0,
freq: 0,
rec: 0,
ghost_freq: 0,
ghost_rec: 0,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
// In the first txn we insert 4 items.
wr_txn.insert(1, 1);
wr_txn.insert(2, 2);
wr_txn.insert(3, 3);
wr_txn.insert(4, 4);
assert!(
CStat {
max: 4,
cache: 0,
tlocal: 4,
freq: 0,
rec: 0,
ghost_freq: 0,
ghost_rec: 0,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
wr_txn.commit();
// Now we start the second txn, and check the stats.
println!("== 2");
let wr_txn = arc.write();
assert!(
CStat {
max: 4,
cache: 4,
tlocal: 0,
freq: 0,
rec: 4,
ghost_freq: 0,
ghost_rec: 0,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
// Now touch two items, this promote to the freq set.
// Remember, a double hit doesn't weight any more than 1 hit.
assert!(wr_txn.get(&1) == Some(&1));
assert!(wr_txn.get(&1) == Some(&1));
assert!(wr_txn.get(&2) == Some(&2));
wr_txn.commit();
// Now we start the third txn, and check the stats.
println!("== 3");
let mut wr_txn = arc.write();
assert!(
CStat {
max: 4,
cache: 4,
tlocal: 0,
freq: 2,
rec: 2,
ghost_freq: 0,
ghost_rec: 0,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
// Add one more item, this will trigger an evict.
wr_txn.insert(5, 5);
wr_txn.commit();
// Now we start the fourth txn, and check the stats.
println!("== 4");
let wr_txn = arc.write();
println!("stat -> {:?}", wr_txn.peek_stat());
assert!(
CStat {
max: 4,
cache: 5,
tlocal: 0,
freq: 2,
rec: 2,
ghost_freq: 0,
ghost_rec: 1,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
// And assert what's in the sets to be sure of what went where.
// 🚨 Can no longer peek these with hashmap backing as the keys may
// be evicted out-of-order, but the stats are correct!
// Now touch the two recent items to bring them also to freq
let rec_set: Vec<usize> = wr_txn.iter_rec().take(2).copied().collect();
assert!(wr_txn.get(&rec_set[0]) == Some(&rec_set[0]));
assert!(wr_txn.get(&rec_set[1]) == Some(&rec_set[1]));
wr_txn.commit();
// Now we start the fifth txn, and check the stats.
println!("== 5");
let mut wr_txn = arc.write();
println!("stat -> {:?}", wr_txn.peek_stat());
assert!(
CStat {
max: 4,
cache: 5,
tlocal: 0,
freq: 4,
rec: 0,
ghost_freq: 0,
ghost_rec: 1,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
// And assert what's in the sets to be sure of what went where.
// 🚨 Can no longer peek these with hashmap backing as the keys may
// be evicted out-of-order, but the stats are correct!
// Now touch the one item that's in ghost rec - this will trigger
// an evict from ghost freq
let grec: usize = wr_txn.iter_ghost_rec().take(1).copied().next().unwrap();
wr_txn.insert(grec, grec);
assert!(wr_txn.get(&grec) == Some(&grec));
// When we add 3, we are basically issuing a demand that the rec set should be
// allowed to grow as we had a potential cache miss here.
wr_txn.commit();
// Now we start the sixth txn, and check the stats.
println!("== 6");
let mut wr_txn = arc.write();
println!("stat -> {:?}", wr_txn.peek_stat());
assert!(
CStat {
max: 4,
cache: 5,
tlocal: 0,
freq: 3,
rec: 1,
ghost_freq: 1,
ghost_rec: 0,
haunted: 0,
p: 1
} == wr_txn.peek_stat()
);
// And assert what's in the sets to be sure of what went where.
// 🚨 Can no longer peek these with hashmap backing as the keys may
// be evicted out-of-order, but the stats are correct!
assert!(wr_txn.peek_cache(&grec) == CacheState::Rec);
// Right, seventh txn - we show how a cache scan doesn't cause p shifting or evict.
// tl;dr - attempt to include a bunch in a scan, and it will be ignored as p is low,
// and any miss on rec won't shift p unless it's in the ghost rec.
wr_txn.insert(10, 10);
wr_txn.insert(11, 11);
wr_txn.insert(12, 12);
wr_txn.commit();
println!("== 7");
let mut wr_txn = arc.write();
println!("stat -> {:?}", wr_txn.peek_stat());
assert!(
CStat {
max: 4,
cache: 8,
tlocal: 0,
freq: 3,
rec: 1,
ghost_freq: 1,
ghost_rec: 3,
haunted: 0,
p: 1
} == wr_txn.peek_stat()
);
// 🚨 Can no longer peek these with hashmap backing as the keys may
// be evicted out-of-order, but the stats are correct!
// Eight txn - now that we had a demand for items before, we re-demand them - this will trigger
// a shift in p, causing some more to be in the rec cache.
let grec_set: Vec<usize> = wr_txn.iter_ghost_rec().take(3).copied().collect();
grec_set.iter().for_each(|i| wr_txn.insert(*i, *i));
wr_txn.commit();
println!("== 8");
let mut wr_txn = arc.write();
println!("stat -> {:?}", wr_txn.peek_stat());
assert!(
CStat {
max: 4,
cache: 8,
tlocal: 0,
freq: 0,
rec: 4,
ghost_freq: 4,
ghost_rec: 0,
haunted: 0,
p: 4
} == wr_txn.peek_stat()
);
grec_set
.iter()
.for_each(|i| assert!(wr_txn.peek_cache(i) == CacheState::Rec));
// Now lets go back the other way - we want freq items to come back.
let gfreq_set: Vec<usize> = wr_txn.iter_ghost_freq().take(4).copied().collect();
gfreq_set.iter().for_each(|i| wr_txn.insert(*i, *i));
wr_txn.commit();
println!("== 9");
let wr_txn = arc.write();
println!("stat -> {:?}", wr_txn.peek_stat());
assert!(
CStat {
max: 4,
cache: 8,
tlocal: 0,
freq: 4,
rec: 0,
ghost_freq: 0,
ghost_rec: 4,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
// 🚨 Can no longer peek these with hashmap backing as the keys may
// be evicted out-of-order, but the stats are correct!
gfreq_set
.iter()
.for_each(|i| assert!(wr_txn.peek_cache(i) == CacheState::Freq));
// And done!
wr_txn.commit();
// See what stats did
let stats = arc.view_stats();
println!("{:?}", *stats);
}
#[test]
fn test_cache_concurrent_basic() {
// Now we want to check some basic interactions of read and write together.
// Setup the cache.
let arc: Arc<usize, usize> = Arc::new_size(4, 4);
// start a rd
{
let mut rd_txn = arc.read();
// add items to the rd
rd_txn.insert(1, 1);
rd_txn.insert(2, 2);
rd_txn.insert(3, 3);
rd_txn.insert(4, 4);
// Should be in the tlocal
// assert!(rd_txn.get(&1).is_some());
// assert!(rd_txn.get(&2).is_some());
// assert!(rd_txn.get(&3).is_some());
// assert!(rd_txn.get(&4).is_some());
// end the rd
}
arc.try_quiesce();
// What state is the cache now in?
println!("== 2");
let wr_txn = arc.write();
println!("{:?}", wr_txn.peek_stat());
assert!(
CStat {
max: 4,
cache: 4,
tlocal: 0,
freq: 0,
rec: 4,
ghost_freq: 0,
ghost_rec: 0,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
assert!(wr_txn.peek_cache(&1) == CacheState::Rec);
assert!(wr_txn.peek_cache(&2) == CacheState::Rec);
assert!(wr_txn.peek_cache(&3) == CacheState::Rec);
assert!(wr_txn.peek_cache(&4) == CacheState::Rec);
// Magic! Without a single write op we included items!
// Lets have the read touch two items, and then add two new.
// This will trigger evict on 1/2
{
let mut rd_txn = arc.read();
// add items to the rd
assert!(rd_txn.get(&3) == Some(&3));
assert!(rd_txn.get(&4) == Some(&4));
rd_txn.insert(5, 5);
rd_txn.insert(6, 6);
// end the rd
}
// Now commit and check the state.
wr_txn.commit();
println!("== 3");
let wr_txn = arc.write();
assert!(
CStat {
max: 4,
cache: 6,
tlocal: 0,
freq: 2,
rec: 2,
ghost_freq: 0,
ghost_rec: 2,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
assert!(wr_txn.peek_cache(&1) == CacheState::GhostRec);
assert!(wr_txn.peek_cache(&2) == CacheState::GhostRec);
assert!(wr_txn.peek_cache(&3) == CacheState::Freq);
assert!(wr_txn.peek_cache(&4) == CacheState::Freq);
assert!(wr_txn.peek_cache(&5) == CacheState::Rec);
assert!(wr_txn.peek_cache(&6) == CacheState::Rec);
// Now trigger hits on 1/2 which will cause a shift in P.
{
let mut rd_txn = arc.read();
// add items to the rd
rd_txn.insert(1, 1);
rd_txn.insert(2, 2);
// end the rd
}
wr_txn.commit();
println!("== 4");
let wr_txn = arc.write();
assert!(
CStat {
max: 4,
cache: 6,
tlocal: 0,
freq: 2,
rec: 2,
ghost_freq: 0,
ghost_rec: 2,
haunted: 0,
p: 2
} == wr_txn.peek_stat()
);
assert!(wr_txn.peek_cache(&1) == CacheState::Rec);
assert!(wr_txn.peek_cache(&2) == CacheState::Rec);
assert!(wr_txn.peek_cache(&3) == CacheState::Freq);
assert!(wr_txn.peek_cache(&4) == CacheState::Freq);
assert!(wr_txn.peek_cache(&5) == CacheState::GhostRec);
assert!(wr_txn.peek_cache(&6) == CacheState::GhostRec);
// See what stats did
let stats = arc.view_stats();
println!("{:?}", *stats);
}
// Test edge cases that are horrifying and could destroy peoples lives
// and sanity.
#[test]
fn test_cache_concurrent_cursed_1() {
// Case 1 - It's possible for a read transaction to last for a long time,
// and then have a cache include, which may cause an attempt to include
// an outdated value into the cache. To handle this the haunted set exists
// so that all keys and their eviction ids are always tracked for all of time
// to ensure that we never incorrectly include a value that may have been updated
// more recently.
let arc: Arc<usize, usize> = Arc::new_size(4, 4);
// Start a wr
let mut wr_txn = arc.write();
// Start a rd
let mut rd_txn = arc.read();
// Add the value 1,1 via the wr.
wr_txn.insert(1, 1);
// assert 1 is not in rd.
assert!(rd_txn.get(&1) == None);
// Commit wr
wr_txn.commit();
// Even after the commit, it's not in rd.
assert!(rd_txn.get(&1) == None);
// begin wr
let mut wr_txn = arc.write();
// We now need to flood the cache, to cause ghost rec eviction.
wr_txn.insert(10, 1);
wr_txn.insert(11, 1);
wr_txn.insert(12, 1);
wr_txn.insert(13, 1);
wr_txn.insert(14, 1);
wr_txn.insert(15, 1);
wr_txn.insert(16, 1);
wr_txn.insert(17, 1);
// commit wr
wr_txn.commit();
// begin wr
let wr_txn = arc.write();
// assert that 1 is haunted.
assert!(wr_txn.peek_cache(&1) == CacheState::Haunted);
// assert 1 is not in rd.
assert!(rd_txn.get(&1) == None);
// now that 1 is hanuted, in rd attempt to insert 1, X
rd_txn.insert(1, 100);
// commit wr
wr_txn.commit();
// start wr
let wr_txn = arc.write();
// assert that 1 is still haunted.
assert!(wr_txn.peek_cache(&1) == CacheState::Haunted);
// assert that 1, x is in rd.
assert!(rd_txn.get(&1) == Some(&100));
// done!
}
#[test]
fn test_cache_clear() {
let arc: Arc<usize, usize> = Arc::new_size(4, 4);
// Start a wr
let mut wr_txn = arc.write();
// Add a bunch of values, and touch some twice.
wr_txn.insert(10, 10);
wr_txn.insert(11, 11);
wr_txn.insert(12, 12);
wr_txn.insert(13, 13);
wr_txn.insert(14, 14);
wr_txn.insert(15, 15);
wr_txn.insert(16, 16);
wr_txn.insert(17, 17);
wr_txn.commit();
// Begin a new write.
let wr_txn = arc.write();
// Touch two values that are in the rec set.
let rec_set: Vec<usize> = wr_txn.iter_rec().take(2).copied().collect();
println!("{:?}", rec_set);
assert!(wr_txn.get(&rec_set[0]) == Some(&rec_set[0]));
assert!(wr_txn.get(&rec_set[1]) == Some(&rec_set[1]));
// commit wr
wr_txn.commit();
// Begin a new write.
let mut wr_txn = arc.write();
println!("stat -> {:?}", wr_txn.peek_stat());
assert!(
CStat {
max: 4,
cache: 8,
tlocal: 0,
freq: 2,
rec: 2,
ghost_freq: 0,
ghost_rec: 4,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
// Clear
wr_txn.clear();
// Now commit
wr_txn.commit();
// Now check their states.
let wr_txn = arc.write();
// See what stats did
println!("stat -> {:?}", wr_txn.peek_stat());
// stat -> CStat { max: 4, cache: 8, tlocal: 0, freq: 0, rec: 0, ghost_freq: 2, ghost_rec: 6, haunted: 0, p: 0 }
assert!(
CStat {
max: 4,
cache: 8,
tlocal: 0,
freq: 0,
rec: 0,
ghost_freq: 2,
ghost_rec: 6,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
let stats = arc.view_stats();
println!("{:?}", *stats);
}
#[test]
fn test_cache_clear_rollback() {
let arc: Arc<usize, usize> = Arc::new_size(4, 4);
// Start a wr
let mut wr_txn = arc.write();
// Add a bunch of values, and touch some twice.
wr_txn.insert(10, 10);
wr_txn.insert(11, 11);
wr_txn.insert(12, 12);
wr_txn.insert(13, 13);
wr_txn.insert(14, 14);
wr_txn.insert(15, 15);
wr_txn.insert(16, 16);
wr_txn.insert(17, 17);
wr_txn.commit();
// Begin a new write.
let wr_txn = arc.write();
let rec_set: Vec<usize> = wr_txn.iter_rec().take(2).copied().collect();
println!("{:?}", rec_set);
let r = wr_txn.get(&rec_set[0]);
println!("{:?}", r);
assert!(r == Some(&rec_set[0]));
assert!(wr_txn.get(&rec_set[1]) == Some(&rec_set[1]));
// commit wr
wr_txn.commit();
// Begin a new write.
let mut wr_txn = arc.write();
println!("stat -> {:?}", wr_txn.peek_stat());
assert!(
CStat {
max: 4,
cache: 8,
tlocal: 0,
freq: 2,
rec: 2,
ghost_freq: 0,
ghost_rec: 4,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
// Clear
wr_txn.clear();
// Now abort the clear - should do nothing!
drop(wr_txn);
// Check the states, should not have changed
let wr_txn = arc.write();
println!("stat -> {:?}", wr_txn.peek_stat());
assert!(
CStat {
max: 4,
cache: 8,
tlocal: 0,
freq: 2,
rec: 2,
ghost_freq: 0,
ghost_rec: 4,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
}
#[test]
fn test_cache_clear_cursed() {
let arc: Arc<usize, usize> = Arc::new_size(4, 4);
// Setup for the test
// --
let mut wr_txn = arc.write();
wr_txn.insert(10, 1);
wr_txn.commit();
// --
let wr_txn = arc.write();
assert!(wr_txn.peek_cache(&10) == CacheState::Rec);
wr_txn.commit();
// --
// Okay, now the test starts. First, we begin a read
let mut rd_txn = arc.read();
// Then while that read exists, we open a write, and conduct
// a cache clear.
let mut wr_txn = arc.write();
wr_txn.clear();
// Commit the clear write.
wr_txn.commit();
// Now on the read, we perform a touch of an item, and we include
// something that was not yet in the cache.
assert!(rd_txn.get(&10) == Some(&1));
rd_txn.insert(11, 1);
// Complete the read
std::mem::drop(rd_txn);
// Perform a cache quiesce
arc.try_quiesce();
// --
// Assert that the items that we provided were NOT included, and are
// in the correct states.
let wr_txn = arc.write();
assert!(wr_txn.peek_cache(&10) == CacheState::GhostRec);
println!("--> {:?}", wr_txn.peek_cache(&11));
assert!(wr_txn.peek_cache(&11) == CacheState::None);
}
#[test]
fn test_cache_dirty_write() {
let arc: Arc<usize, usize> = Arc::new_size(4, 4);
let mut wr_txn = arc.write();
wr_txn.insert_dirty(10, 1);
wr_txn.iter_mut_mark_clean().for_each(|(_k, _v)| {});
wr_txn.commit();
}
#[test]
fn test_cache_read_no_tlocal() {
// Check a cache with no read local thread capacity
// Setup the cache.
let arc: Arc<usize, usize> = Arc::new_size(4, 0);
// start a rd
{
let mut rd_txn = arc.read();
// add items to the rd
rd_txn.insert(1, 1);
rd_txn.insert(2, 2);
rd_txn.insert(3, 3);
rd_txn.insert(4, 4);
// end the rd
// Everything should be missing frm the tlocal.
assert!(rd_txn.get(&1).is_none());
assert!(rd_txn.get(&2).is_none());
assert!(rd_txn.get(&3).is_none());
assert!(rd_txn.get(&4).is_none());
}
arc.try_quiesce();
// What state is the cache now in?
println!("== 2");
let wr_txn = arc.write();
assert!(
CStat {
max: 4,
cache: 4,
tlocal: 0,
freq: 0,
rec: 4,
ghost_freq: 0,
ghost_rec: 0,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
assert!(wr_txn.peek_cache(&1) == CacheState::Rec);
assert!(wr_txn.peek_cache(&2) == CacheState::Rec);
assert!(wr_txn.peek_cache(&3) == CacheState::Rec);
assert!(wr_txn.peek_cache(&4) == CacheState::Rec);
}
#[derive(Clone, Debug)]
struct Weighted {
i: u64,
}
#[test]
fn test_cache_weighted() {
let arc: Arc<usize, Weighted> = Arc::new_size(4, 0);
let mut wr_txn = arc.write();
assert!(
CStat {
max: 4,
cache: 0,
tlocal: 0,
freq: 0,
rec: 0,
ghost_freq: 0,
ghost_rec: 0,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
// In the first txn we insert 2 weight 2 items.
wr_txn.insert_sized(1, Weighted { i: 1 }, 2);
wr_txn.insert_sized(2, Weighted { i: 2 }, 2);
assert!(
CStat {
max: 4,
cache: 0,
tlocal: 2,
freq: 0,
rec: 0,
ghost_freq: 0,
ghost_rec: 0,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
wr_txn.commit();
// Now once commited, the proper sizes kick in.
let wr_txn = arc.write();
// eprintln!("{:?}", wr_txn.peek_stat());
assert!(
CStat {
max: 4,
cache: 2,
tlocal: 0,
freq: 0,
rec: 4,
ghost_freq: 0,
ghost_rec: 0,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
wr_txn.commit();
// Check the numbers move properly.
let wr_txn = arc.write();
wr_txn.get(&1);
wr_txn.commit();
let mut wr_txn = arc.write();
assert!(
CStat {
max: 4,
cache: 2,
tlocal: 0,
freq: 2,
rec: 2,
ghost_freq: 0,
ghost_rec: 0,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
wr_txn.insert_sized(3, Weighted { i: 3 }, 2);
wr_txn.insert_sized(4, Weighted { i: 4 }, 2);
wr_txn.commit();
// Check the evicts
let wr_txn = arc.write();
assert!(
CStat {
max: 4,
cache: 4,
tlocal: 0,
freq: 2,
rec: 2,
ghost_freq: 0,
ghost_rec: 4,
haunted: 0,
p: 0
} == wr_txn.peek_stat()
);
wr_txn.commit();
let stats = arc.view_stats();
println!("{:?}", *stats);
}
}