cached 3.1.0

Generic cache implementations and simplified function memoization
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
use super::{CacheEvict, Cached, DefaultHashBuilder, LruCache};
use crate::{CacheExpiry, CachedIter, CachedPeek, CloneCached};
use std::hash::{BuildHasher, Hash};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

#[cfg(feature = "async_core")]
use {super::CachedGetOrSetAsync, std::future::Future};

/// Implemented by values stored in [`ExpiringLruCache`] and [`ExpiringCache`](crate::ExpiringCache)
/// so the value itself decides when it is stale. Expired values are not returned by lookups
/// and are removed on access:
///
/// ```rust
/// use cached::{CachedExt, Expires, ExpiringCache, ExpiringLruCache};
///
/// struct Token {
///     #[allow(dead_code)]
///     value: String,
///     expired: bool,
/// }
/// impl Expires for Token {
///     fn is_expired(&self) -> bool {
///         self.expired
///     }
/// }
///
/// // Unbounded store (default for `#[cached(expires = true)]`)
/// let mut cache: ExpiringCache<u32, Token> = ExpiringCache::new();
/// cache.set(1, Token { value: "live".into(), expired: false });
/// assert!(cache.get(&1).is_some());
/// cache.set(2, Token { value: "stale".into(), expired: true });
/// assert!(cache.get(&2).is_none()); // expired -> not returned
///
/// // LRU-bounded store (`#[cached(expires = true, max_size = N)]`)
/// let mut lru: ExpiringLruCache<u32, Token> = ExpiringLruCache::new(8);
/// lru.set(3, Token { value: "live".into(), expired: false });
/// assert!(lru.get(&3).is_some());
/// ```
pub trait Expires {
    /// `is_expired` returns whether the value has expired.
    ///
    /// This is the authoritative liveness check: callers must use `is_expired` to
    /// decide whether a cached value may be returned, not `expires_at`.
    fn is_expired(&self) -> bool;

    /// Returns the [`crate::time::Instant`] at which this value expires, or `None` if the
    /// expiry instant is unknown or not tracked by this type.
    ///
    /// The default implementation returns `None`. Override this in types that record a
    /// concrete deadline. Without the override this returns `None`, so
    /// `CacheExpiry::cache_peek_expires_at` reports no deadline for the value and any
    /// remaining-ttl policy built on it never fires.
    ///
    /// `is_expired()` remains the authoritative liveness check; `expires_at` is advisory
    /// and must not be used as a substitute for `is_expired`.
    fn expires_at(&self) -> Option<crate::time::Instant> {
        None
    }
}

/// LRU-bounded cache with per-value expiry.
///
/// Stores values that implement the [`Expires`] trait so that expiration
/// is determined by the values themselves. This is useful for caching
/// values which themselves contain an expiry timestamp.
///
/// For an unbounded variant (no size cap), see [`ExpiringCache`](crate::ExpiringCache).
/// When using the `#[cached]` proc macro, `expires = true` selects this store when `max_size`
/// is also specified; without `max_size`, it selects the unbounded `ExpiringCache`.
///
/// Note: This cache is in-memory only.
///
/// **`cache_size` / `iter` / `evict` contract**: `cache_size()` returns the raw stored entry count
/// and may include expired-but-not-yet-swept entries. `iter()` omits expired entries
/// from the view but does not remove them. Call `evict()` (via [`CacheEvict`](crate::CacheEvict))
/// to physically remove expired entries and obtain an accurate live count.
///
/// Note: once specialization is stable (`#[feature(specialization)]`), the expiry-checking
/// behavior here could be folded into [`LruCache`] via a specialized `Cached<K, V>` impl
/// for `V: Expires`, eliminating this separate type. Until then, the two must remain
/// distinct because overlapping blanket impls are not allowed on stable Rust.
pub struct ExpiringLruCache<K, V, S = DefaultHashBuilder> {
    pub(super) store: LruCache<K, V, S>,
    pub(super) hits: AtomicU64,
    pub(super) misses: AtomicU64,
    pub(super) evictions: AtomicU64,
    pub(super) on_evict: Option<super::OnEvict<K, V>>,
}

impl<K, V, S> std::fmt::Debug for ExpiringLruCache<K, V, S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExpiringLruCache")
            .field("hits", &self.hits.load(Ordering::Relaxed))
            .field("misses", &self.misses.load(Ordering::Relaxed))
            .field("evictions", &self.evictions.load(Ordering::Relaxed))
            .field("on_evict", &self.on_evict.as_ref().map(|_| "on_evict"))
            .finish()
    }
}

/// Two `ExpiringLruCache` values are equal when their stored entries are equal
/// (same keys, same values). Equality is membership-based: LRU recency order is
/// not compared. Metrics (hits, misses, evictions) and the `on_evict` callback
/// are not part of the comparison.
impl<K, V, S> PartialEq for ExpiringLruCache<K, V, S>
where
    K: Clone + Hash + Eq,
    V: PartialEq,
    S: BuildHasher,
{
    fn eq(&self, other: &Self) -> bool {
        self.store == other.store
    }
}

impl<K, V, S> Eq for ExpiringLruCache<K, V, S>
where
    K: Clone + Hash + Eq,
    V: Eq,
    S: BuildHasher,
{
}

impl<K, V, S> Clone for ExpiringLruCache<K, V, S>
where
    K: Clone + Hash + Eq,
    V: Clone,
    S: Clone,
{
    fn clone(&self) -> Self {
        Self {
            store: self.store.clone(),
            hits: AtomicU64::new(self.hits.load(Ordering::Relaxed)),
            misses: AtomicU64::new(self.misses.load(Ordering::Relaxed)),
            evictions: AtomicU64::new(self.evictions.load(Ordering::Relaxed)),
            on_evict: self.on_evict.clone(),
        }
    }
}

/// Builder for [`ExpiringLruCache`].
///
/// Note: there is intentionally **no `.ttl()` setter**. An `ExpiringLruCache` has no global
/// expiry duration -- each value decides when it is expired via the [`Expires`] trait, while
/// `max_size` bounds the entry count via LRU. For a single global TTL applied to every entry,
/// use [`LruTtlCache`](crate::stores::LruTtlCache) instead.
#[doc(alias = "ttl")]
pub struct ExpiringLruCacheBuilder<K, V, S = DefaultHashBuilder> {
    size: Option<usize>,
    on_evict: Option<super::OnEvict<K, V>>,
    hasher: S,
}

impl<K, V> Default for ExpiringLruCacheBuilder<K, V, DefaultHashBuilder> {
    fn default() -> Self {
        Self {
            size: None,
            on_evict: None,
            hasher: super::new_default_hash_builder(),
        }
    }
}

impl<K, V> ExpiringLruCacheBuilder<K, V> {
    /// Create a builder with default settings. Equivalent to [`ExpiringLruCache::builder`].
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

impl<K, V, S> ExpiringLruCacheBuilder<K, V, S> {
    /// Set the maximum number of entries.
    #[doc(alias = "size")]
    #[doc(alias = "capacity")]
    #[must_use]
    pub fn max_size(mut self, max_size: usize) -> Self {
        self.size = Some(max_size);
        self
    }

    /// Set a callback to be invoked when an entry is evicted. The callback fires for:
    /// - LRU capacity eviction: inserting past `max_size` evicts the least-recently-used entry.
    /// - Capacity shrink via [`set_max_size`](ExpiringLruCache::set_max_size) /
    ///   [`try_set_max_size`](ExpiringLruCache::try_set_max_size).
    /// - An expired value encountered during `cache_get`, `cache_get_mut`,
    ///   `cache_get_or_set_with_mut`, `cache_try_get_or_set_with_mut` (the primary
    ///   implementations), `cache_get_or_set_with`, `cache_try_get_or_set_with` (default-impl
    ///   wrappers that delegate to the `_mut` variants), and their async equivalents.
    /// - Overwriting an already-expired entry via [`cache_set`](crate::Cached::cache_set):
    ///   the displaced value is filtered from the return (`None`), so it fires the callback
    ///   and counts an eviction.
    /// - An explicit [`evict`](ExpiringLruCache::evict) sweep.
    /// - Explicit [`cache_remove`](crate::Cached::cache_remove) /
    ///   [`cache_remove_entry`](crate::Cached::cache_remove_entry), including when the removed
    ///   entry was already expired.
    ///
    /// It does **not** fire on [`cache_clear`](crate::Cached::cache_clear) or `cache_reset`.
    /// Use [`cache_clear_with_on_evict`](ExpiringLruCache::cache_clear_with_on_evict)
    /// instead to opt into callback firing and eviction counter increments when clearing
    /// all entries.
    #[must_use]
    pub fn on_evict(mut self, on_evict: impl Fn(&K, &V) + Send + Sync + 'static) -> Self {
        self.on_evict = Some(Arc::new(on_evict));
        self
    }

    /// Switch to a custom hash builder `S2`, returning a builder parameterized on `S2`.
    ///
    /// The hasher is used to hash keys in the internal `LruCache`. Calling this method
    /// changes the builder's type parameter so `build()` returns an `ExpiringLruCache<K, V, S2>`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cached::{Cached, Expires, ExpiringLruCache};
    /// use std::collections::hash_map::RandomState;
    ///
    /// struct Val(bool);
    /// impl Expires for Val { fn is_expired(&self) -> bool { self.0 } }
    ///
    /// let mut cache = ExpiringLruCache::<u32, Val>::builder()
    ///     .max_size(10)
    ///     .hasher(RandomState::new())
    ///     .build()
    ///     .unwrap();
    /// cache.cache_set(1, Val(false));
    /// assert!(cache.cache_get(&1).is_some());
    /// ```
    #[doc(alias = "with_hasher")]
    #[must_use]
    pub fn hasher<S2: BuildHasher>(self, hasher: S2) -> ExpiringLruCacheBuilder<K, V, S2> {
        ExpiringLruCacheBuilder {
            size: self.size,
            on_evict: self.on_evict,
            hasher,
        }
    }

    /// Build the cache.
    ///
    /// # Errors
    ///
    /// Returns [`BuildError::MissingRequired`](super::BuildError) if `max_size` was not set,
    /// or [`BuildError::InvalidValue`](super::BuildError) if `max_size` is `0`.
    pub fn build(self) -> Result<ExpiringLruCache<K, V, S>, super::BuildError>
    where
        K: Hash + Eq + Clone,
        S: BuildHasher,
    {
        let size = self
            .size
            .ok_or(super::BuildError::MissingRequired("max_size"))?;
        let mut store = LruCache::builder()
            .max_size(size)
            .hasher(self.hasher)
            .build()?;
        store.disable_hit_miss_tracking();
        // Two separate callbacks for two separate eviction causes:
        //   cache.on_evict    -- fires when ExpiringLruCache itself removes an expired entry
        //   cache.store.on_evict -- fires when LruCache::check_capacity evicts for capacity
        // Both must be registered independently so neither path is silently skipped.
        let mut cache = ExpiringLruCache {
            store,
            hits: AtomicU64::new(0),
            misses: AtomicU64::new(0),
            evictions: AtomicU64::new(0),
            on_evict: self.on_evict.clone(),
        };
        if let Some(on_evict) = self.on_evict {
            cache.store.on_evict = Some(on_evict);
        }
        Ok(cache)
    }
}

impl<K: Clone + Hash + Eq, V: Expires> ExpiringLruCache<K, V> {
    /// Construct a ready-to-use [`ExpiringLruCache`] holding up to `max_size` entries.
    ///
    /// For optional settings (`on_evict`) use [`builder`](Self::builder).
    ///
    /// # Panics
    ///
    /// Panics if `max_size` is `0`, or if pre-allocating the backing store for
    /// `max_size` entries fails (e.g. `usize::MAX`). Use [`builder`](Self::builder)
    /// with [`build`](ExpiringLruCacheBuilder::build) to handle those cases without panicking.
    #[must_use]
    pub fn new(max_size: usize) -> Self {
        Self::builder()
            .max_size(max_size)
            .build()
            .expect("ExpiringLruCache::new requires a non-zero max_size with a valid allocation")
    }

    /// Return a builder for constructing an [`ExpiringLruCache`].
    #[must_use]
    pub fn builder() -> ExpiringLruCacheBuilder<K, V> {
        ExpiringLruCacheBuilder::default()
    }
}

impl<K: Clone + Hash + Eq, V: Expires, S: BuildHasher> ExpiringLruCache<K, V, S> {
    /// Returns the maximum number of entries this cache will hold before evicting.
    ///
    /// This is the bound set via [`ExpiringLruCacheBuilder::max_size`],
    /// not the current number of entries — use [`cache_size`](crate::Cached::cache_size) for that.
    #[doc(alias = "size")]
    #[doc(alias = "max_size")]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.store.capacity()
    }

    /// Change the maximum number of entries, returning the previous capacity;
    /// shrinking below the current entry count immediately evicts least-recently-used
    /// entries.
    ///
    /// Eviction on shrink fires `on_evict` and counts evictions until the cache
    /// fits. Growing the capacity does not pre-allocate; the backing stores grow
    /// on demand as entries are inserted.
    ///
    /// This is useful for sizing a `#[cached(create = "{ ... }")]` cache from a value
    /// loaded at startup (e.g. config), then adjusting it later as load changes.
    ///
    /// # Panics
    ///
    /// Panics if `max_size` is 0. Use [`try_set_max_size`](ExpiringLruCache::try_set_max_size)
    /// to validate first and avoid the panic.
    pub fn set_max_size(&mut self, max_size: usize) -> Option<usize> {
        self.store.set_max_size(max_size)
    }

    /// Fallible counterpart of [`set_max_size`](ExpiringLruCache::set_max_size): validates
    /// that `max_size` is non-zero and then delegates to `set_max_size`.
    /// Returns the previous capacity wrapped in `Some` on success.
    ///
    /// # Errors
    ///
    /// Returns [`SetMaxSizeError::ZeroMaxSize`](super::SetMaxSizeError) if `max_size` is 0.
    pub fn try_set_max_size(
        &mut self,
        max_size: usize,
    ) -> Result<Option<usize>, super::SetMaxSizeError> {
        self.store.try_set_max_size(max_size)
    }

    /// Evict expired values from the cache.
    #[must_use]
    pub fn evict(&mut self) -> usize {
        // Two-phase: select, then remove, then count, then notify. The scan collects every
        // doomed slot before unlinking any of them, so counting or notifying from inside the
        // scan predicate would fire the side effects
        // for entries that are still stored -- and a panic anywhere in the scan would leave
        // them served after their `on_evict` cleanup already ran.
        let doomed = self.doomed_indices(|_key, value| value.is_expired());
        self.remove_and_notify(doomed)
    }

    /// Phase 1 of a two-phase sweep: inner-store slot indices (MRU -> LRU) of the entries
    /// `doomed` selects.
    ///
    /// Reads only, so a panic out of `doomed` (it runs the caller's `retain` predicate and
    /// the value's own [`Expires::is_expired`]) leaves the cache exactly as it was: nothing
    /// removed, nothing counted, nothing notified. Mirrors `LruCache::retain`'s scan.
    fn doomed_indices<F: FnMut(&K, &V) -> bool>(&self, mut doomed: F) -> Vec<usize> {
        let mut out = Vec::with_capacity(self.store.store.len());
        out.extend(self.store.order.iter_indices().filter(|&index| {
            let (key, value) = self.store.order.get(index);
            doomed(key, value)
        }));
        out
    }

    /// Phase 2 of a two-phase sweep: remove every selected slot, then count the batch as
    /// evictions, then notify `on_evict`. Returns the number of entries removed.
    ///
    /// Indices stay valid because nothing is inserted between the scan and the removals.
    /// Every entry is out of the store and counted before the first notification, so a
    /// panicking `on_evict` can never leave a cleaned-up entry still reachable, nor an
    /// entry removed-but-uncounted.
    fn remove_and_notify(&mut self, doomed: Vec<usize>) -> usize {
        let removed: Vec<(K, V)> = doomed
            .into_iter()
            .map(|index| self.store.remove_index(index))
            .collect();
        if !removed.is_empty() {
            self.evictions
                .fetch_add(removed.len() as u64, Ordering::Relaxed);
        }
        if let Some(on_evict) = &self.on_evict {
            for (key, value) in &removed {
                on_evict(key, value);
            }
        }
        removed.len()
    }

    /// Retain only entries that are unexpired and satisfy `keep`.
    ///
    /// Iterates the entries held in the underlying LRU store (most- to
    /// least-recently-used) and removes every entry that is already expired
    /// (per [`Expires::is_expired`]) **or** for which `keep` returns `false` —
    /// expired entries are removed without consulting `keep`. `on_evict` is
    /// called and the eviction counter incremented for each removed entry.
    /// The LRU recency order of the surviving entries is unchanged.
    ///
    /// This matches [`LruTtlCache::retain`](crate::LruTtlCache::retain); the plain
    /// [`LruCache::retain`](crate::LruCache::retain) has no expiry dimension and
    /// removes solely on the predicate.
    ///
    /// Returns the number of entries removed: the count folds together entries `keep`
    /// rejected and entries swept for having already expired, since expiry removal is
    /// unconditional regardless of what `keep` returns. `retain` is deliberately not
    /// `#[must_use]`: discarding the count is a legitimate and common use, matching
    /// existing bare `cache.retain(...);` call sites.
    pub fn retain<F: FnMut(&K, &V) -> bool>(&mut self, mut keep: F) -> usize {
        // Two-phase (see `doomed_indices` / `remove_and_notify`): the selection pass must be
        // side-effect free so a panicking `keep` leaves the cache untouched rather than
        // half-notified with every scanned entry still stored.
        let doomed = self.doomed_indices(|key, value| value.is_expired() || !keep(key, value));
        self.remove_and_notify(doomed)
    }

    /// Remove all entries and fire the `on_evict` callback for each one, incrementing the
    /// evictions counter.
    ///
    /// Unlike [`cache_clear`](crate::Cached::cache_clear) (which removes entries silently),
    /// this method invokes `on_evict` for every removed entry (whether or not they had expired)
    /// and increments `evictions`. The eviction count does not depend on whether an
    /// `on_evict` callback is configured.
    pub fn cache_clear_with_on_evict(&mut self) {
        // `drain_all` walks the LRU chain once taking owned pairs (MRU -> LRU, the same
        // order the old key-by-key drain fired in) -- no key clones, no re-hashing.
        let removed = self.store.drain_all();
        let count = removed.len() as u64;
        if count > 0 {
            self.evictions.fetch_add(count, Ordering::Relaxed);
        }
        if let Some(on_evict) = &self.on_evict {
            for (k, v) in &removed {
                on_evict(k, v);
            }
        }
    }

    /// Return all live entries in current LRU order (most-recently-used first)
    /// as `(K, `[`CacheValue<V>`](super::CacheValue)`)` pairs. `ExpiringLruCache`
    /// carries no per-entry metadata beyond what `V: Expires` itself exposes, so
    /// the wrapper's metadata type is `()`; the wrapper `Deref`s to `V`.
    /// Expired entries are excluded.
    #[must_use]
    pub fn iter_order(&self) -> Vec<(K, super::CacheValue<V>)>
    where
        K: Clone,
        V: Clone,
    {
        self.store
            .iter_order_raw()
            .into_iter()
            .filter(|(_, v)| !v.is_expired())
            .map(|(k, v)| (k, super::CacheValue::new(v, ())))
            .collect()
    }

    /// Return a `Vec` of keys in the current order from most to least recently
    /// used. Expired entries are excluded.
    #[must_use]
    pub fn key_order(&self) -> Vec<K>
    where
        K: Clone,
    {
        // Upper-bound pre-size on the raw stored count (may include expired entries not
        // yet swept); the filter below can only shrink the final length.
        let mut out = Vec::with_capacity(self.store.cache_size());
        out.extend(self.store.order.iter().filter_map(|(k, v)| {
            if v.is_expired() {
                None
            } else {
                Some(k.clone())
            }
        }));
        out
    }

    /// Return a `Vec` of [`CacheValue`](super::CacheValue)-wrapped values in the
    /// current order from most to least recently used. Expired entries are excluded.
    #[must_use]
    pub fn value_order(&self) -> Vec<super::CacheValue<V>>
    where
        V: Clone,
    {
        // Upper-bound pre-size on the raw stored count (may include expired entries not
        // yet swept); the filter below can only shrink the final length.
        let mut out = Vec::with_capacity(self.store.cache_size());
        out.extend(self.store.order.iter().filter_map(|(_, v)| {
            if v.is_expired() {
                None
            } else {
                Some(super::CacheValue::new(v.clone(), ()))
            }
        }));
        out
    }
}

// https://docs.rs/cached/latest/cached/trait.Cached.html
impl<K: Hash + Eq + Clone, V: Expires, S: BuildHasher> Cached<K, V> for ExpiringLruCache<K, V, S> {
    type Error = std::convert::Infallible;

    fn cache_get<Q>(&mut self, k: &Q) -> Option<&V>
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + ?Sized,
    {
        let hash = self.store.hash(k);
        if let Some(index) = self.store.get_index(hash, k) {
            let value = &self.store.order.get(index).1;
            if !value.is_expired() {
                self.store.order.move_to_front(index);
                self.hits.fetch_add(1, Ordering::Relaxed);
                Some(&self.store.order.get(index).1)
            } else {
                self.misses.fetch_add(1, Ordering::Relaxed);
                // `hash` was already computed above for `get_index`; reuse it instead of
                // letting `pop_raw` re-hash the same key.
                if let Some((key, old)) = self.store.pop_raw_with_hash(hash, k) {
                    // Count BEFORE notifying: a panicking callback must never leave
                    // an entry removed-but-uncounted.
                    self.evictions.fetch_add(1, Ordering::Relaxed);
                    if let Some(on_evict) = &self.on_evict {
                        on_evict(&key, &old);
                    }
                }
                None
            }
        } else {
            self.misses.fetch_add(1, Ordering::Relaxed);
            None
        }
    }

    fn cache_get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + ?Sized,
    {
        let hash = self.store.hash(key);
        if let Some(index) = self.store.get_index(hash, key) {
            let value = &self.store.order.get(index).1;
            if !value.is_expired() {
                self.store.order.move_to_front(index);
                self.hits.fetch_add(1, Ordering::Relaxed);
                Some(&mut self.store.order.get_mut(index).1)
            } else {
                self.misses.fetch_add(1, Ordering::Relaxed);
                // `hash` was already computed above for `get_index`; reuse it instead of
                // letting `pop_raw` re-hash the same key.
                if let Some((k, old)) = self.store.pop_raw_with_hash(hash, key) {
                    // Count BEFORE notifying: a panicking callback must never leave
                    // an entry removed-but-uncounted.
                    self.evictions.fetch_add(1, Ordering::Relaxed);
                    if let Some(on_evict) = &self.on_evict {
                        on_evict(&k, &old);
                    }
                }
                None
            }
        } else {
            self.misses.fetch_add(1, Ordering::Relaxed);
            None
        }
    }

    fn cache_get_or_set_with_mut<F: FnOnce() -> V>(&mut self, k: K, f: F) -> &mut V {
        // Count the miss the instant the factory runs, matching the try variant so the two
        // paths agree even when the factory panics (C10). The inner store invokes the factory
        // only on a miss (vacant slot or expired entry), so a hit never counts one.
        let counted_f = {
            let misses = &self.misses;
            move || {
                misses.fetch_add(1, Ordering::Relaxed);
                f()
            }
        };
        // get_or_set_with_if will set the value in the cache if an existing
        // value is not valid, which, in our case, is if the value has expired.
        // On replacement it hands back the STORED key/value of the displaced entry, so the
        // callback sees the instance that was actually cached, not the (equal-but-distinct)
        // lookup key (C1/C8).
        let (was_present, was_valid, old_val, v) =
            self.store
                .get_or_set_with_if(k, counted_f, |v| !v.is_expired());
        if was_present && was_valid {
            self.hits.fetch_add(1, Ordering::Relaxed);
        } else if let Some((old_key, old)) = old_val {
            // Count BEFORE notifying: a panicking callback must never leave an
            // entry removed-but-uncounted.
            self.evictions.fetch_add(1, Ordering::Relaxed);
            if let Some(on_evict) = &self.on_evict {
                on_evict(&old_key, &old);
            }
        }
        v
    }
    fn cache_try_get_or_set_with_mut<F: FnOnce() -> Result<V, E>, E>(
        &mut self,
        key: K,
        f: F,
    ) -> Result<&mut V, E> {
        // Count the miss the instant the factory runs. The inner store calls it only on a miss
        // (vacant slot or expired entry), so a hit never counts one; and because the increment
        // lands before `f` returns, an `Err` still records the miss instead of losing it on the
        // `?` early return. This matches `ExpiringCache`'s try-path accounting (EXP-2).
        let counted_f = {
            let misses = &self.misses;
            move || {
                misses.fetch_add(1, Ordering::Relaxed);
                f()
            }
        };
        // On replacement the store returns the STORED key/value of the displaced entry (C1/C8).
        let (was_present, was_valid, old_val, v) =
            self.store
                .try_get_or_set_with_if(key, counted_f, |v| !v.is_expired())?;
        if was_present && was_valid {
            self.hits.fetch_add(1, Ordering::Relaxed);
        } else if let Some((old_key, old)) = old_val {
            // Count BEFORE notifying: a panicking callback must never leave an
            // entry removed-but-uncounted.
            self.evictions.fetch_add(1, Ordering::Relaxed);
            if let Some(on_evict) = &self.on_evict {
                on_evict(&old_key, &old);
            }
        }
        Ok(v)
    }
    fn cache_set(&mut self, k: K, v: V) -> Option<V> {
        // `cache_set_returning_entry` hands back the STORED key/value of the displaced
        // entry, so no caller-side key clone is needed to feed `on_evict` (unlike the old
        // `LruCache::cache_set` + `k.clone()` combination, which cloned the key on every
        // insert whenever `on_evict` was configured). Like the plain `LruCache::cache_set`
        // it does NOT fire `on_evict` on an overwrite itself, so an expired displaced value
        // would otherwise be dropped silently; filter it from the return and fire
        // `on_evict` + count once here -- now with the STORED key, matching
        // `LruTtlCache::set_entry`.
        match self.store.cache_set_returning_entry(k, v) {
            Some((stored_key, old)) if old.is_expired() => {
                // Count BEFORE notifying: a panicking callback must never leave an
                // entry removed-but-uncounted.
                self.evictions.fetch_add(1, Ordering::Relaxed);
                if let Some(on_evict) = &self.on_evict {
                    on_evict(&stored_key, &old);
                }
                None
            }
            Some((_, old)) => Some(old),
            None => None,
        }
    }
    /// Removes the entry and returns the value only if it is still live;
    /// an expired value is removed but reported as `None`. Use
    /// [`cache_remove_entry`](Cached::cache_remove_entry) to receive the
    /// value regardless of expiry.
    fn cache_remove<Q>(&mut self, k: &Q) -> Option<V>
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + ?Sized,
    {
        let (stored_k, v) = self.store.pop_raw(k)?;
        // Judge expiry at the moment of removal, BEFORE the callback runs. Asking the value
        // again on the way out (as delegating to `cache_remove_entry` used to) would let a
        // slow `on_evict` push it past its deadline and report `None` for a value that was
        // live when it was taken out.
        let expired = v.is_expired();
        // Count BEFORE notifying: a panicking callback must never leave an
        // entry removed-but-uncounted.
        self.evictions.fetch_add(1, Ordering::Relaxed);
        if let Some(on_evict) = &self.on_evict {
            on_evict(&stored_k, &v);
        }
        if expired { None } else { Some(v) }
    }

    /// Removes the entry and returns it **regardless of expiry** (unlike
    /// [`cache_remove`](Cached::cache_remove), which filters expired values).
    fn cache_remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + ?Sized,
    {
        if let Some((stored_k, v)) = self.store.pop_raw(k) {
            // Count BEFORE notifying: a panicking callback must never leave an
            // entry removed-but-uncounted.
            self.evictions.fetch_add(1, Ordering::Relaxed);
            if let Some(on_evict) = &self.on_evict {
                on_evict(&stored_k, &v);
            }
            Some((stored_k, v))
        } else {
            None
        }
    }

    fn cache_clear(&mut self) {
        self.store.cache_clear();
    }
    fn cache_reset(&mut self) {
        // Entries are dropped in-place; `on_evict` is NOT called for cleared entries.
        // Delegate to the inner LruCache's reset which preserves the hash builder and
        // already resets the inner metrics. Reset outer-level metrics here directly to
        // avoid a redundant second call to the inner store's cache_reset_metrics.
        self.store.cache_reset();
        self.hits.store(0, Ordering::Relaxed);
        self.misses.store(0, Ordering::Relaxed);
        self.evictions.store(0, Ordering::Relaxed);
    }
    fn cache_size(&self) -> usize {
        self.store.cache_size()
    }
    fn cache_capacity(&self) -> Option<usize> {
        // Bounded by the inner `LruCache`; report it like the other bounded
        // stores so `metrics().capacity` is accurate.
        self.store.cache_capacity()
    }
    fn cache_hits(&self) -> Option<u64> {
        Some(self.hits.load(Ordering::Relaxed))
    }
    fn cache_misses(&self) -> Option<u64> {
        Some(self.misses.load(Ordering::Relaxed))
    }
    fn cache_evictions(&self) -> Option<u64> {
        Some(self.evictions.load(Ordering::Relaxed) + self.store.cache_evictions().unwrap_or(0))
    }
    fn cache_reset_metrics(&mut self) {
        self.hits.store(0, Ordering::Relaxed);
        self.misses.store(0, Ordering::Relaxed);
        self.evictions.store(0, Ordering::Relaxed);
        self.store.cache_reset_metrics();
    }

    /// Check whether the cache contains a live (non-expired) entry for `k`.
    ///
    /// Delegates to [`CachedPeek::cache_peek`], so it records no hit/miss
    /// metrics, performs no recency promotion, and reports absent/expired
    /// entries as `false`.
    fn cache_contains<Q>(&mut self, k: &Q) -> bool
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + ?Sized,
    {
        crate::CachedPeek::cache_peek(self, k).is_some()
    }
}

impl<K: Hash + Eq + Clone, V: Expires, S: BuildHasher> CachedIter<K, V>
    for ExpiringLruCache<K, V, S>
{
    fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a K, &'a V)> + 'a
    where
        K: 'a,
        V: 'a,
    {
        self.store
            .iter()
            .filter_map(|(k, v)| if v.is_expired() { None } else { Some((k, v)) })
    }
}

impl<K: Hash + Eq + Clone, V: Expires, S: BuildHasher> CachedPeek<K, V>
    for ExpiringLruCache<K, V, S>
{
    fn cache_peek<Q>(&self, key: &Q) -> Option<&V>
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + ?Sized,
    {
        self.store.cache_peek(key).and_then(|value| {
            if value.is_expired() {
                None
            } else {
                Some(value)
            }
        })
    }
}

#[cfg(feature = "async_core")]
#[cfg_attr(docsrs, doc(cfg(feature = "async_core")))]
impl<K, V, S> CachedGetOrSetAsync<K, V> for ExpiringLruCache<K, V, S>
where
    K: Hash + Eq + Clone + Send,
    V: Expires + Send,
    S: BuildHasher + Send,
{
    fn async_cache_get_or_set_with_mut<'a, F, Fut>(
        &'a mut self,
        k: K,
        f: F,
    ) -> impl Future<Output = &'a mut V> + Send + 'a
    where
        K: 'a,
        V: Send + 'a,
        F: FnOnce() -> Fut + Send + 'a,
        Fut: Future<Output = V> + Send + 'a,
    {
        async move {
            // Count the miss when the factory runs (miss path only), matching the try variant
            // so the two paths agree on a panicking factory (C10).
            let counted_f = {
                let misses = &self.misses;
                move || {
                    misses.fetch_add(1, Ordering::Relaxed);
                    f()
                }
            };
            // On replacement the store returns the STORED key/value of the displaced entry (C1/C8).
            let (was_present, was_valid, old_val, v) = self
                .store
                .get_or_set_with_if_async(k, counted_f, |v| !v.is_expired())
                .await;
            if was_present && was_valid {
                self.hits.fetch_add(1, Ordering::Relaxed);
            } else if let Some((old_key, old)) = old_val {
                // Count BEFORE notifying: a panicking callback must never leave an
                // entry removed-but-uncounted.
                self.evictions.fetch_add(1, Ordering::Relaxed);
                if let Some(on_evict) = &self.on_evict {
                    on_evict(&old_key, &old);
                }
            }
            v
        }
    }

    fn async_cache_try_get_or_set_with_mut<'a, F, Fut, E>(
        &'a mut self,
        k: K,
        f: F,
    ) -> impl Future<Output = Result<&'a mut V, E>> + Send + 'a
    where
        K: 'a,
        V: Send + 'a,
        E: 'a,
        F: FnOnce() -> Fut + Send + 'a,
        Fut: Future<Output = Result<V, E>> + Send + 'a,
    {
        async move {
            // Count the miss when the factory is invoked (miss path only), so an `Err` from the
            // async factory still records it instead of losing it on the `?` early return.
            // Mirrors the sync try path and `ExpiringCache` (EXP-2).
            let counted_f = {
                let misses = &self.misses;
                move || {
                    misses.fetch_add(1, Ordering::Relaxed);
                    f()
                }
            };
            // On replacement the store returns the STORED key/value of the displaced entry (C1/C8).
            let (was_present, was_valid, old_val, v) = self
                .store
                .try_get_or_set_with_if_async(k, counted_f, |v| !v.is_expired())
                .await?;
            if was_present && was_valid {
                self.hits.fetch_add(1, Ordering::Relaxed);
            } else if let Some((old_key, old)) = old_val {
                // Count BEFORE notifying: a panicking callback must never leave an
                // entry removed-but-uncounted.
                self.evictions.fetch_add(1, Ordering::Relaxed);
                if let Some(on_evict) = &self.on_evict {
                    on_evict(&old_key, &old);
                }
            }
            Ok(v)
        }
    }
}

impl<K: Hash + Eq + Clone, V: Expires + Clone, S: BuildHasher> CloneCached<K, V>
    for ExpiringLruCache<K, V, S>
{
    fn cache_get_with_expiry_status<Q>(&mut self, k: &Q) -> (Option<V>, bool)
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + ?Sized,
    {
        let hash = self.store.hash(k);
        if let Some(index) = self.store.get_index(hash, k) {
            let value = &self.store.order.get(index).1;
            let expired = value.is_expired();
            if expired {
                self.misses.fetch_add(1, Ordering::Relaxed);
                // Don't move to front — expired entries must not be promoted.
                // Return the stale value so callers using `result_fallback` can
                // use it during revalidation.
                (Some(self.store.order.get(index).1.clone()), true)
            } else {
                self.store.order.move_to_front(index);
                self.hits.fetch_add(1, Ordering::Relaxed);
                (Some(self.store.order.get(index).1.clone()), false)
            }
        } else {
            self.misses.fetch_add(1, Ordering::Relaxed);
            (None, false)
        }
    }

    /// Peek at the entry (including expired entries) without any read side effects.
    ///
    /// Returns `(Some(v), true)` for an expired entry, `(Some(v), false)` for a live
    /// entry, and `(None, false)` when the key is absent. Does not update hit/miss
    /// counters and does not promote in LRU order.
    fn cache_peek_with_expiry_status<Q>(&self, k: &Q) -> (Option<V>, bool)
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + ?Sized,
        V: Clone,
    {
        // Use the inner LruCache's `cache_peek` to avoid LRU promotion.
        if let Some(value) = self.store.cache_peek(k) {
            let expired = value.is_expired();
            (Some(value.clone()), expired)
        } else {
            (None, false)
        }
    }
}

impl<K: Hash + Eq + Clone, V: Expires, S: BuildHasher> CacheExpiry<K, V>
    for ExpiringLruCache<K, V, S>
{
    /// Returns the stored value and its expiry instant, with no read side effects.
    ///
    /// The instant is whatever [`Expires::expires_at`] reports for the value, and on
    /// this store that is advisory only: it is `None` unless the value type overrides
    /// `expires_at` (including for an entry that is expired), and it may be in the
    /// past for an entry [`Expires::is_expired`] reports as live. `is_expired` remains
    /// the authority on liveness here; use
    /// [`cache_peek_with_expiry_status`](CloneCached::cache_peek_with_expiry_status) for
    /// that. Uses the same lookup as that peek (the inner `LruCache`'s non-promoting
    /// `cache_peek`): no hit/miss counting, no LRU promotion, no removal of an expired
    /// entry.
    fn cache_peek_expires_at<Q>(&self, k: &Q) -> (Option<V>, Option<crate::time::Instant>)
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + ?Sized,
        V: Clone,
    {
        if let Some(value) = self.store.cache_peek(k) {
            (Some(value.clone()), value.expires_at())
        } else {
            (None, None)
        }
    }

    /// Returns whether the key is present and its expiry instant, without the value.
    ///
    /// The value-free counterpart of
    /// [`cache_peek_expires_at`](CacheExpiry::cache_peek_expires_at): same non-promoting
    /// lookup (the inner `LruCache`'s `cache_peek`), same advisory deadline, no clone and
    /// no `V: Clone` bound. `(false, None)` when the key is absent; `(true, deadline)`
    /// when it is present, where `deadline` is whatever [`Expires::expires_at`] reports
    /// for the stored value.
    ///
    /// **The presence flag is not advisory: the deadline is.** On this store the deadline
    /// is `None` for any value type that does not override `Expires::expires_at`,
    /// *including an entry that is expired* -- so `(true, None)` means "present, deadline
    /// unknown", not "present and live". `is_expired`, not this deadline, remains the
    /// authority on liveness; see the [`CacheExpiry`] trait docs' `Expires`-store caveat.
    /// An expired entry is reported present and is **not** removed. No hit/miss
    /// counting, no LRU promotion.
    fn cache_expires_at<Q>(&self, k: &Q) -> (bool, Option<crate::time::Instant>)
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + ?Sized,
    {
        match self.store.cache_peek(k) {
            Some(value) => (true, value.expires_at()),
            None => (false, None),
        }
    }
}

impl<K: std::hash::Hash + Eq + Clone, V: Expires, S: BuildHasher> CacheEvict
    for ExpiringLruCache<K, V, S>
{
    fn evict(&mut self) -> usize {
        ExpiringLruCache::evict(self)
    }
}

#[cfg(test)]
/// Expiring Value Cache tests
mod tests {
    use super::*;
    use crate::{Cached, CachedExt};
    use std::sync::atomic::{AtomicU64, Ordering};

    type ExpiredU8 = u8;

    impl Expires for ExpiredU8 {
        fn is_expired(&self) -> bool {
            *self > 10
        }
    }

    #[test]
    fn new_returns_ready_cache_respecting_max_size() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::new(2);
        assert_eq!(c.capacity(), 2);
        assert_eq!(c.set(1, 5), None);
        assert_eq!(c.get(&1), Some(&5));
        c.set(2, 6);
        c.set(3, 7); // evicts LRU (1)
        assert_eq!(c.cache_size(), 2);
        assert_eq!(c.get(&1), None);
    }

    #[test]
    #[should_panic(expected = "non-zero max_size")]
    fn new_zero_max_size_panics() {
        let _c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::new(0);
    }

    #[test]
    fn expiring_value_cache_get_miss() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();

        // Getting a non-existent cache key.
        assert!(c.get(&1).is_none());
        assert_eq!(c.cache_hits(), Some(0));
        assert_eq!(c.cache_misses(), Some(1));
    }

    #[test]
    fn cache_set_over_expired_returns_none_fires_on_evict_and_counts() {
        use std::sync::{Arc, Mutex};
        let fired: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(vec![]));
        let fired2 = fired.clone();
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(4)
            .on_evict(move |k: &u8, _v: &ExpiredU8| fired2.lock().unwrap().push(*k))
            .build()
            .unwrap();
        c.set(1, 15); // expired (>10)
        let before = c.cache_evictions().unwrap();
        // Overwriting an expired value: filtered from the return (None), fires on_evict once,
        // counts one eviction.
        assert_eq!(c.cache_set(1, 3), None);
        assert_eq!(c.cache_evictions(), Some(before + 1));
        assert_eq!(fired.lock().unwrap().clone(), vec![1]);
        // Overwriting a live value returns it, and does not fire on_evict or count.
        assert_eq!(c.cache_set(1, 4), Some(3));
        assert_eq!(c.cache_evictions(), Some(before + 1));
        assert_eq!(fired.lock().unwrap().clone(), vec![1]);
    }

    #[test]
    fn cache_set_over_expired_counts_eviction_without_callback() {
        // Pins that the evictions counter increments when overwriting an expired entry
        // even when no on_evict callback is configured.
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        c.set(1, 15); // expired (>10)
        let before = c.cache_evictions().unwrap();
        assert_eq!(c.cache_set(1, 3), None);
        assert_eq!(
            c.cache_evictions(),
            Some(before + 1),
            "evictions must increment by 1 on expired-entry overwrite even without on_evict"
        );
        // Overwriting a live value must not count as an eviction.
        assert_eq!(c.cache_set(1, 4), Some(3));
        assert_eq!(
            c.cache_evictions(),
            Some(before + 1),
            "overwriting a live entry must not increment evictions"
        );
    }

    // B1 regression: on_evict must receive the STORED key, not the caller's lookup key.
    // Key types can have fields not covered by Eq/Hash; the stored key and the new key may
    // differ in those extra fields even though they compare equal.
    #[test]
    fn on_evict_receives_stored_key_not_callers_key() {
        use std::sync::{Arc, Mutex};

        // A key whose Hash/PartialEq use only `id`; `tag` is transparent to equality.
        #[derive(Clone, Debug)]
        struct TaggedKey {
            id: u32,
            tag: &'static str,
        }
        impl PartialEq for TaggedKey {
            fn eq(&self, other: &Self) -> bool {
                self.id == other.id
            }
        }
        impl Eq for TaggedKey {}
        impl std::hash::Hash for TaggedKey {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                self.id.hash(state);
            }
        }

        let evicted_tags: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
        let evicted_tags2 = evicted_tags.clone();

        let mut cache: ExpiringLruCache<TaggedKey, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(4)
            .on_evict(move |k: &TaggedKey, _v: &ExpiredU8| {
                evicted_tags2.lock().unwrap().push(k.tag);
            })
            .build()
            .unwrap();

        // Insert with tag "a"; value 15 is expired (>10).
        cache.cache_set(TaggedKey { id: 1, tag: "a" }, 15);
        // Overwrite with an equal key (same id) but different tag "b".
        // The displaced entry was stored with tag "a"; on_evict must report "a".
        cache.cache_set(TaggedKey { id: 1, tag: "b" }, 3);

        let tags = evicted_tags.lock().unwrap();
        assert_eq!(
            tags.as_slice(),
            &["a"],
            "on_evict must receive the stored key (tag='a'), not the caller's key (tag='b')"
        );
    }

    #[test]
    fn cache_set_overwrite_promotes_to_mru() {
        // `cache_set` goes through `LruCache::cache_set_returning_entry`, which promotes an
        // overwritten key to MRU: a write is an access. The user-visible consequence is
        // which entry a later capacity eviction picks.
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 1); // live
        c.cache_set(2, 2); // live
        c.cache_set(3, 3); // live
        // LRU order after inserts (MRU -> LRU): 3, 2, 1.
        assert_eq!(c.key_order(), vec![3, 2, 1]);

        // Overwrite key 1 -- the least-recently-used entry -- with a new live value.
        // The write promotes it, so 2 becomes the LRU entry.
        assert_eq!(c.cache_set(1, 10), Some(1));
        assert_eq!(c.key_order(), vec![1, 3, 2]);

        // Insert a 4th key to force a capacity eviction: key 2 is now the victim.
        c.cache_set(4, 4);
        assert_eq!(c.cache_size(), 3);
        assert_eq!(
            c.cache_get(&2),
            None,
            "key 2 is the LRU victim -- cache_set promoted key 1 on overwrite"
        );
        assert_eq!(c.cache_get(&1), Some(&10));
        assert_eq!(c.cache_get(&3), Some(&3));
        assert_eq!(c.cache_get(&4), Some(&4));
    }

    #[test]
    fn cache_set_over_current_mru_and_sole_entry_keep_the_list_intact() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 1);
        c.cache_set(2, 2);
        c.cache_set(3, 3);
        // Overwriting the head exercises `move_to_front` on an already-front slot.
        assert_eq!(c.cache_set(3, 4), Some(3));
        assert_eq!(c.key_order(), vec![3, 2, 1]);
        assert_eq!(c.cache_size(), 3);
        let values: Vec<u8> = c.value_order().iter().map(|v| **v).collect();
        assert_eq!(values, vec![4u8, 2, 1]);

        // Sole entry of a 1-capacity cache.
        let mut d: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(1).build().unwrap();
        d.cache_set(1, 1);
        assert_eq!(d.cache_set(1, 2), Some(1));
        assert_eq!(d.key_order(), vec![1]);
        assert_eq!(d.cache_size(), 1);
    }

    #[test]
    fn cache_peek_still_does_not_promote_after_set_does() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 1);
        c.cache_set(2, 2);
        c.cache_set(3, 3);
        assert!(CachedPeek::cache_peek(&c, &1).is_some());
        assert_eq!(c.key_order(), vec![3, 2, 1], "peek must not promote");
        assert_eq!(c.cache_set(1, 4), Some(1));
        assert_eq!(c.key_order(), vec![1, 3, 2]);
    }

    #[test]
    fn expiring_lru_try_get_or_set_with_err_keeps_expired_and_counts_miss() {
        // EXP-2: on a factory Err over an expired entry, ExpiringLruCache counts a miss the
        // instant the factory runs (matching ExpiringCache) instead of losing it on the `?`
        // early return, and leaves the expired entry in place without firing on_evict.
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        c.set(1, 15); // expired (>10)
        let result: Result<&ExpiredU8, &str> = c.cache_try_get_or_set_with(1, || Err("fail"));
        assert!(result.is_err());
        assert_eq!(c.cache_size(), 1, "expired entry must remain after Err");
        assert_eq!(c.cache_evictions(), Some(0));
        assert_eq!(
            c.cache_misses(),
            Some(1),
            "miss must be counted before f() even on Err"
        );
    }

    #[test]
    fn expiring_lru_try_get_or_set_with_ok_evicts_and_counts_miss() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        c.set(1, 15); // expired
        let result: Result<&ExpiredU8, &str> = c.cache_try_get_or_set_with(1, || Ok(3));
        assert_eq!(*result.unwrap(), 3);
        assert_eq!(c.cache_evictions(), Some(1));
        assert_eq!(c.cache_misses(), Some(1));
    }

    #[test]
    fn expiring_value_cache_reports_capacity() {
        // Regression: `ExpiringLruCache` is size-bounded, so it must report a
        // capacity like the other bounded stores (was falling through to the
        // `Cached` default `None`, making `metrics().capacity` inaccurate).
        let c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(7).build().unwrap();
        assert_eq!(c.cache_capacity(), Some(7));
        assert_eq!(c.metrics().capacity, Some(7));
    }

    #[test]
    fn capacity_returns_bound_not_live_size() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        assert_eq!(c.capacity(), 3);
        assert_eq!(c.cache_size(), 0);

        c.cache_set(1, 5);
        c.cache_set(2, 6);
        assert_eq!(c.capacity(), 3);
        assert_eq!(c.cache_size(), 2);

        // Eviction past the bound keeps capacity fixed while live count stays capped.
        c.cache_set(3, 7);
        c.cache_set(4, 8);
        assert_eq!(c.capacity(), 3);
        assert_eq!(c.cache_size(), 3);
    }

    #[test]
    fn builder_rejects_zero_max_size() {
        let result = ExpiringLruCache::<u8, ExpiredU8>::builder()
            .max_size(0)
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn expiring_value_cache_get_hit() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();

        // Getting a cached value.
        assert!(c.set(1, 2).is_none());
        assert_eq!(c.get(&1), Some(&2));
        assert_eq!(c.cache_hits(), Some(1));
        assert_eq!(c.cache_misses(), Some(0));
    }

    #[test]
    fn cache_get_lazy_sweep_of_expired_fires_on_evict_with_correct_key_and_removes_entry() {
        // Perf shard item 3: cache_get's expired branch now reuses the hash already
        // computed for get_index via pop_raw_with_hash instead of letting pop_raw
        // re-hash. Pin that the sweep still fires on_evict with the right key/value,
        // increments evictions exactly once, and physically removes the entry.
        use std::sync::{Arc, Mutex};
        let fired: Arc<Mutex<Vec<(u8, u8)>>> = Arc::new(Mutex::new(Vec::new()));
        let fired2 = fired.clone();
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(4)
            .on_evict(move |k: &u8, v: &ExpiredU8| fired2.lock().unwrap().push((*k, *v)))
            .build()
            .unwrap();
        c.cache_set(1, 20); // expired: 20 > 10
        assert_eq!(c.cache_get(&1), None, "expired entry must not be returned");
        assert_eq!(
            fired.lock().unwrap().clone(),
            vec![(1u8, 20u8)],
            "on_evict must fire once with the expired entry's key and value"
        );
        assert_eq!(c.cache_evictions(), Some(1));
        assert_eq!(
            c.cache_size(),
            0,
            "the expired entry must be physically removed by the lazy sweep"
        );
    }

    #[test]
    fn cache_get_mut_lazy_sweep_of_expired_fires_on_evict_with_correct_key_and_removes_entry() {
        // Same as the cache_get variant above, for cache_get_mut's expired branch.
        use std::sync::{Arc, Mutex};
        let fired: Arc<Mutex<Vec<(u8, u8)>>> = Arc::new(Mutex::new(Vec::new()));
        let fired2 = fired.clone();
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(4)
            .on_evict(move |k: &u8, v: &ExpiredU8| fired2.lock().unwrap().push((*k, *v)))
            .build()
            .unwrap();
        c.cache_set(1, 20); // expired: 20 > 10
        assert_eq!(
            c.cache_get_mut(&1),
            None,
            "expired entry must not be returned"
        );
        assert_eq!(
            fired.lock().unwrap().clone(),
            vec![(1u8, 20u8)],
            "on_evict must fire once with the expired entry's key and value"
        );
        assert_eq!(c.cache_evictions(), Some(1));
        assert_eq!(
            c.cache_size(),
            0,
            "the expired entry must be physically removed by the lazy sweep"
        );
    }

    #[test]
    fn expiring_value_cache_get_expired() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();

        assert!(c.set(2, 12).is_none());

        assert!(c.get(&2).is_none());
        assert_eq!(c.cache_hits(), Some(0));
        assert_eq!(c.cache_misses(), Some(1));
    }

    #[test]
    fn expiring_value_cache_get_mut_miss() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();

        // Getting a non-existent cache key.
        assert!(c.cache_get_mut(&1).is_none());
        assert_eq!(c.cache_hits(), Some(0));
        assert_eq!(c.cache_misses(), Some(1));
    }

    #[test]
    fn expiring_value_cache_get_mut_hit() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();

        // Getting a cached value.
        assert!(c.set(1, 2).is_none());
        assert_eq!(c.cache_get_mut(&1), Some(&mut 2));
        assert_eq!(c.cache_hits(), Some(1));
        assert_eq!(c.cache_misses(), Some(0));
    }

    #[test]
    fn expiring_value_cache_get_mut_expired() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();

        assert!(c.set(2, 12).is_none());

        assert!(c.get(&2).is_none());
        assert_eq!(c.cache_hits(), Some(0));
        assert_eq!(c.cache_misses(), Some(1));
    }

    #[test]
    fn expiring_value_cache_get_or_set_with_missing() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();

        assert_eq!(c.cache_get_or_set_with(1, || 1), &1);
        assert_eq!(c.cache_hits(), Some(0));
        assert_eq!(c.cache_misses(), Some(1));
    }

    #[test]
    fn expiring_value_cache_get_or_set_with_present() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        assert!(c.set(1, 5).is_none());

        // Existing value is returned rather than setting new value.
        assert_eq!(c.cache_get_or_set_with(1, || 1), &5);
        assert_eq!(c.cache_hits(), Some(1));
        assert_eq!(c.cache_misses(), Some(0));
    }

    #[test]
    fn expiring_value_cache_get_or_set_with_expired() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        assert!(c.set(1, 11).is_none());

        // New value is returned as existing had expired.
        assert_eq!(c.cache_get_or_set_with(1, || 1), &1);
        assert_eq!(c.cache_hits(), Some(0));
        assert_eq!(c.cache_misses(), Some(1));
    }

    #[test]
    fn expiring_value_cache_try_get_or_set_with_missing() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();

        assert_eq!(c.cache_try_get_or_set_with(1, || Ok::<_, ()>(1)), Ok(&1));
        assert_eq!(c.cache_hits(), Some(0));
        assert_eq!(c.cache_misses(), Some(1));

        assert_eq!(c.cache_try_get_or_set_with(1, || Err(())), Ok(&1));
        assert_eq!(c.cache_hits(), Some(1));
        assert_eq!(c.cache_misses(), Some(1));

        assert_eq!(c.cache_try_get_or_set_with(2, || Ok::<_, ()>(2)), Ok(&2));
        assert_eq!(c.cache_hits(), Some(1));
        assert_eq!(c.cache_misses(), Some(2));
    }

    #[test]
    fn evict_expired() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();

        assert_eq!(c.set(1, 100), None);
        // The previous value 100 was expired (>10), so it is filtered from the return (None),
        // matching the TTL stores' cache_set contract.
        assert_eq!(c.set(1, 200), None);
        assert_eq!(c.set(2, 1), None);
        assert_eq!(c.cache_size(), 2);

        // It should only evict n > 10
        assert_eq!(2, c.cache_size());
        let _ = c.evict();
        assert_eq!(1, c.cache_size());
    }

    #[test]
    fn reset_rebuilds_store_and_preserves_on_evict() {
        let evicted = Arc::new(AtomicU64::new(0));
        let evicted_for_callback = evicted.clone();
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(1)
            .on_evict(move |_key: &u8, _value: &ExpiredU8| {
                evicted_for_callback.fetch_add(1, Ordering::Relaxed);
            })
            .build()
            .unwrap();

        c.set(1, 1);
        c.cache_reset();
        assert_eq!(0, c.cache_size());

        // Inserting two values into a capacity-1 cache should evict exactly one.
        c.set(2, 2);
        c.set(3, 3);
        assert_eq!(1, evicted.load(Ordering::Relaxed));

        // Insert a third value — eviction count should now be exactly 2, not more.
        c.set(4, 4);
        assert_eq!(2, evicted.load(Ordering::Relaxed));
    }

    #[test]
    fn cache_get_with_expiry_status_does_not_promote_expired_entry() {
        // Build a capacity-2 cache. Insert A then B, making B the MRU entry.
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(2).build().unwrap();
        c.set(1, 100); // A — value 100 > 10, so it is expired
        c.set(2, 100); // B — also expired

        // Calling cache_get_with_expiry_status on A must NOT promote A to MRU.
        let (val, expired) = c.cache_get_with_expiry_status(&1u8);
        assert!(val.is_some(), "expired entry should still be returned");
        assert!(expired, "entry should be flagged as expired");

        // Now insert a third key C to force a capacity eviction.
        // If A was wrongly promoted it would be MRU and B would be evicted instead.
        // Correct behaviour: B is still MRU → A (LRU) is evicted first.
        c.set(3, 1); // C — value 1 <= 10, live
        assert_eq!(c.cache_size(), 2);
        // A should have been evicted (LRU), B and C should still be present.
        assert!(
            c.get(&1u8).is_none(),
            "key 1 (A) should have been evicted as LRU"
        );
        assert!(
            c.get(&2u8).is_none(),
            "key 2 (B) is expired — none after get"
        );
        assert!(c.get(&3u8).is_some(), "key 3 (C) should be live");
    }

    #[test]
    fn cache_clear_with_on_evict_fires_for_all_entries() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
        let count = Arc::new(AtomicUsize::new(0));
        let count2 = count.clone();
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(5)
            .on_evict(move |_k: &u8, _v: &ExpiredU8| {
                count2.fetch_add(1, AOrdering::Relaxed);
            })
            .build()
            .unwrap();
        c.cache_set(1, 5); // live (value <= 10)
        c.cache_set(2, 12); // expired (value > 10)
        c.cache_set(3, 8); // live
        c.cache_clear_with_on_evict();
        assert_eq!(c.cache_size(), 0);
        assert_eq!(
            count.load(AOrdering::Relaxed),
            3,
            "on_evict fires for all entries including expired"
        );
        assert_eq!(c.evictions.load(AOrdering::Relaxed), 3);
    }

    #[test]
    fn cache_clear_with_on_evict_fires_in_mru_to_lru_order() {
        // Perf shard item 1: `cache_clear_with_on_evict` was rewritten to use
        // `LruCache::drain_all`, which must preserve the same MRU -> LRU firing order
        // the old key-by-key `key_order()` + `pop_raw` loop produced.
        use std::sync::{Arc, Mutex};
        let fired: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
        let fired2 = fired.clone();
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(5)
            .on_evict(move |k: &u8, _v: &ExpiredU8| {
                fired2.lock().unwrap().push(*k);
            })
            .build()
            .unwrap();
        // Insert order: 1, 2, 3 -> LRU order after inserts: 1 < 2 < 3.
        c.cache_set(1, 5);
        c.cache_set(2, 6);
        c.cache_set(3, 7);
        // Access 1 then 2 so the final MRU -> LRU order is: 2, 1, 3.
        let _ = c.cache_get(&1);
        let _ = c.cache_get(&2);

        c.cache_clear_with_on_evict();

        assert_eq!(
            fired.lock().unwrap().clone(),
            vec![2u8, 1, 3],
            "on_evict must fire in most-recently-used to least-recently-used order"
        );
    }

    #[test]
    fn cache_clear_does_not_fire_on_evict() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering as AOrdering};
        let count = Arc::new(AtomicUsize::new(0));
        let count2 = count.clone();
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(5)
            .on_evict(move |_k: &u8, _v: &ExpiredU8| {
                count2.fetch_add(1, AOrdering::Relaxed);
            })
            .build()
            .unwrap();
        c.cache_set(1, 5);
        c.cache_set(2, 8);
        c.cache_clear();
        assert_eq!(c.cache_size(), 0);
        assert_eq!(
            count.load(AOrdering::Relaxed),
            0,
            "cache_clear must not fire on_evict"
        );
    }

    #[test]
    fn cache_reset_does_not_fire_on_evict() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};
        let evict_count = Arc::new(AtomicUsize::new(0));
        let evict_count2 = evict_count.clone();
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(4)
            .on_evict(move |_k, _v| {
                evict_count2.fetch_add(1, Ordering::Relaxed);
            })
            .build()
            .unwrap();
        c.cache_set(1, 5);
        c.cache_set(2, 5);
        c.cache_set(3, 5);
        c.cache_reset();
        assert_eq!(
            evict_count.load(Ordering::Relaxed),
            0,
            "cache_reset must not fire on_evict"
        );
        assert_eq!(c.cache_size(), 0);
    }

    #[test]
    fn cache_reset_zeroes_all_metrics() {
        // CLN-2: cache_reset must reset metrics exactly once; verify the result is zero,
        // including the inner LruCache's own capacity-eviction counter.
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(2).build().unwrap();
        c.cache_set(1, 5); // live
        c.cache_set(2, 5); // live
        // Drive an inner-store capacity eviction so the inner evictions counter is non-zero.
        c.cache_set(3, 5); // evicts LRU (1) in the inner LruCache
        assert!(
            c.store.cache_evictions().unwrap() >= 1,
            "precondition: inner store must record a capacity eviction before reset"
        );
        // Accumulate hits, misses, and an expiry eviction (to exercise the outer counter too).
        let _ = c.cache_get(&3); // live -> hit
        let _ = c.cache_get(&99); // miss
        c.cache_set(3, 15); // overwrite live 3 with expired value (returns Some, no eviction)
        c.cache_set(3, 5); // overwrite expired -> outer eviction
        c.cache_reset();
        assert_eq!(
            c.cache_hits(),
            Some(0),
            "hits must be zero after cache_reset"
        );
        assert_eq!(
            c.cache_misses(),
            Some(0),
            "misses must be zero after cache_reset"
        );
        assert_eq!(
            c.cache_evictions(),
            Some(0),
            "evictions must be zero after cache_reset"
        );
        assert_eq!(
            c.store.cache_evictions(),
            Some(0),
            "inner store evictions must be zero after cache_reset"
        );
        assert_eq!(c.cache_size(), 0, "size must be zero after cache_reset");
    }

    #[test]
    fn cache_reset_metrics_standalone_zeroes_outer_and_inner() {
        // CLN-2 (regression guard): cache_reset_metrics() called on its own — NOT via
        // cache_reset — must zero BOTH the outer counters (hits/misses/evictions) AND the
        // inner LruCache's counters, while leaving stored entries untouched. Unlike
        // cache_reset (which rebuilds the inner store), cache_reset_metrics must explicitly
        // delegate to store.cache_reset_metrics(); a half-reset touching only the outer
        // counter would leave the inner capacity-eviction count and this test fails.
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(2).build().unwrap();
        // Inner capacity eviction: 3 live inserts into a size-2 cache evicts the LRU key.
        c.cache_set(1, 1);
        c.cache_set(2, 2);
        c.cache_set(3, 3); // inner evictions -> 1
        assert!(
            c.store.cache_evictions().unwrap() >= 1,
            "precondition: inner store must record a capacity eviction"
        );
        // Outer metrics: a hit, a miss, and an expiry eviction via expired-entry overwrite.
        let _ = c.cache_get(&3); // live -> hit
        let _ = c.cache_get(&99); // miss
        c.cache_set(3, 15); // overwrite live 3 with expired value (returns Some, no eviction)
        c.cache_set(3, 5); // overwrite expired -> outer eviction
        assert!(
            c.hits.load(Ordering::Relaxed) >= 1,
            "precondition: outer hits must be non-zero"
        );
        assert!(
            c.evictions.load(Ordering::Relaxed) >= 1,
            "precondition: outer evictions must be non-zero"
        );

        c.cache_reset_metrics();

        assert_eq!(
            c.hits.load(Ordering::Relaxed),
            0,
            "outer hits must be zero after standalone cache_reset_metrics"
        );
        assert_eq!(
            c.misses.load(Ordering::Relaxed),
            0,
            "outer misses must be zero after standalone cache_reset_metrics"
        );
        assert_eq!(
            c.evictions.load(Ordering::Relaxed),
            0,
            "outer evictions must be zero after standalone cache_reset_metrics"
        );
        assert_eq!(
            c.store.cache_evictions(),
            Some(0),
            "inner store evictions must be zero after standalone cache_reset_metrics"
        );
        assert_eq!(
            c.cache_evictions(),
            Some(0),
            "combined (outer + inner) evictions must be zero after cache_reset_metrics"
        );
        // cache_reset_metrics must NOT drop stored entries.
        assert!(
            c.cache_size() >= 1,
            "cache_reset_metrics must not clear stored entries"
        );
    }

    #[test]
    fn test_expiring_value_cache_iter_excludes_expired() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 5); // live
        c.cache_set(2, 12); // expired (value > 10)
        c.cache_set(3, 8); // live

        let mut keys: Vec<u8> = c.iter().map(|(&k, _)| k).collect();
        keys.sort();
        assert_eq!(keys, vec![1, 3]);
    }

    #[test]
    fn test_expiring_value_cache_clone() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 5);
        c.cache_set(2, 6);

        let mut cloned = c.clone();
        assert_eq!(cloned.cache_size(), 2);
        assert_eq!(cloned.cache_get(&1), Some(&5));
        assert_eq!(cloned.cache_get(&2), Some(&6));
    }

    #[test]
    fn test_expiring_value_cache_debug() {
        let c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        let debug_str = format!("{:?}", c);
        assert!(debug_str.contains("ExpiringLruCache"));
        assert!(debug_str.contains("hits"));
        assert!(debug_str.contains("misses"));
        assert!(debug_str.contains("evictions"));
    }

    #[test]
    fn test_expiring_value_cache_remove_and_clear() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 5);
        c.cache_set(2, 6);

        assert_eq!(c.cache_remove(&1), Some(5));
        assert_eq!(c.cache_size(), 1);
        assert_eq!(c.cache_get(&1), None);

        c.cache_clear();
        assert_eq!(c.cache_size(), 0);
    }

    #[test]
    fn cache_remove_entry_returns_some_for_live_entry() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        c.cache_set(1, 5); // not expired: 5 <= 10
        let removed = c.cache_remove_entry(&1u8);
        assert_eq!(removed, Some((1u8, 5u8)));
        assert_eq!(c.cache_size(), 0);
    }

    #[test]
    fn cache_remove_entry_returns_some_for_expired_entry() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        c.cache_set(1, 20u8); // expired: 20 > 10

        // cache_remove returns None for an expired entry.
        c.cache_set(2, 20u8);
        assert_eq!(c.cache_remove(&2u8), None); // expired

        // cache_remove_entry returns Some even for an expired entry.
        let removed = c.cache_remove_entry(&1u8);
        assert_eq!(
            removed.expect("cache_remove_entry must return Some for expired entry"),
            (1u8, 20u8)
        );
    }

    #[test]
    fn cache_delete_returns_true_for_expired_entry() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        c.cache_set(1, 20u8); // expired
        assert!(
            c.cache_delete(&1u8),
            "cache_delete must return true for expired entry"
        );
        assert!(!c.cache_delete(&1u8), "cache_delete false when absent");
    }

    #[test]
    fn cache_remove_entry_fires_on_evict_for_expired() {
        let count = std::sync::Arc::new(AtomicU64::new(0));
        let count2 = count.clone();
        let mut c = ExpiringLruCache::builder()
            .max_size(4)
            .on_evict(move |_k: &u8, _v: &ExpiredU8| {
                count2.fetch_add(1, Ordering::Relaxed);
            })
            .build()
            .unwrap();
        c.cache_set(1u8, 20u8); // expired

        let _ = c.cache_remove_entry(&1u8);
        assert_eq!(
            count.load(Ordering::Relaxed),
            1,
            "on_evict fires for expired entries"
        );

        let _ = c.cache_remove_entry(&99u8);
        assert_eq!(count.load(Ordering::Relaxed), 1, "no fire for absent key");
    }

    #[test]
    fn cache_remove_entry_with_panicking_on_evict_still_counts_eviction() {
        // The entry is popped and counted BEFORE `on_evict` runs, so a panicking
        // callback must not leave the removed entry uncounted.
        use std::panic::{AssertUnwindSafe, catch_unwind};
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(4)
            .on_evict(|_k: &u8, _v: &ExpiredU8| panic!("boom"))
            .build()
            .unwrap();
        c.cache_set(1u8, 1u8); // live
        let r = catch_unwind(AssertUnwindSafe(|| c.cache_remove_entry(&1u8)));
        assert!(r.is_err(), "on_evict should have panicked");
        assert_eq!(
            c.cache_size(),
            0,
            "entry must still be removed from the store"
        );
        assert_eq!(
            c.cache_evictions(),
            Some(1),
            "eviction must be counted even though on_evict panicked"
        );
    }

    #[test]
    fn retain_with_panicking_on_evict_still_counts_eviction() {
        // Same invariant on the `retain` path: the predicate closure counts BEFORE
        // notifying, so a panicking callback still leaves the eviction counted.
        use std::panic::{AssertUnwindSafe, catch_unwind};
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(4)
            .on_evict(|_k: &u8, _v: &ExpiredU8| panic!("boom"))
            .build()
            .unwrap();
        c.cache_set(1u8, 1u8); // live
        let r = catch_unwind(AssertUnwindSafe(|| c.retain(|_, _| false)));
        assert!(r.is_err(), "on_evict should have panicked");
        assert_eq!(
            c.cache_evictions(),
            Some(1),
            "eviction must be counted even though on_evict panicked"
        );
    }

    #[test]
    fn cache_get_lazy_sweep_with_panicking_on_evict_still_counts_eviction() {
        // `cache_get` on an expired entry pops it and counts the eviction BEFORE
        // `on_evict` runs, so a panicking callback must not leave it uncounted.
        use std::panic::{AssertUnwindSafe, catch_unwind};
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(4)
            .on_evict(|_k: &u8, _v: &ExpiredU8| panic!("boom"))
            .build()
            .unwrap();
        c.cache_set(1u8, 15u8); // already expired (>10)
        let r = catch_unwind(AssertUnwindSafe(|| {
            let _ = c.cache_get(&1u8);
        }));
        assert!(r.is_err(), "on_evict should have panicked");
        assert_eq!(
            c.cache_size(),
            0,
            "the expired entry must still be swept from the store"
        );
        assert_eq!(
            c.cache_evictions(),
            Some(1),
            "eviction must be counted even though on_evict panicked"
        );
    }

    #[test]
    fn cache_set_over_expired_with_panicking_on_evict_still_counts_eviction() {
        // Overwriting an expired entry fires `on_evict` for the displaced value;
        // `cache_set` counts the eviction BEFORE notifying.
        use std::panic::{AssertUnwindSafe, catch_unwind};
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(4)
            .on_evict(|_k: &u8, _v: &ExpiredU8| panic!("boom"))
            .build()
            .unwrap();
        c.cache_set(1u8, 15u8); // already expired (>10)
        let r = catch_unwind(AssertUnwindSafe(|| c.cache_set(1u8, 1u8)));
        assert!(r.is_err(), "on_evict should have panicked");
        assert_eq!(
            c.cache_evictions(),
            Some(1),
            "eviction must be counted even though on_evict panicked"
        );
    }

    #[test]
    fn cache_remove_entry_absent_returns_none() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        assert_eq!(c.cache_remove_entry(&42u8), None);
    }

    #[test]
    fn cache_remove_entry_increments_eviction_counter() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        c.cache_set(1u8, 20u8); // expired: 20 > 10
        let before = c.cache_evictions().expect("evictions are always tracked");
        let _ = c.cache_remove_entry(&1u8); // expired but present - must increment
        let _ = c.cache_remove_entry(&99u8); // absent - must not increment
        assert_eq!(
            c.cache_evictions().expect("evictions are always tracked") - before,
            1,
            "cache_remove_entry must increment evictions for present key only"
        );
    }

    #[test]
    fn set_max_size_changes_capacity_and_evicts() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 1);
        c.cache_set(2, 2);
        c.cache_set(3, 3);
        assert_eq!(c.capacity(), 3);

        // Shrink to 2: LRU entry (1) should be evicted.
        let prev = c.set_max_size(2);
        assert_eq!(prev, Some(3));
        assert_eq!(c.capacity(), 2);
        assert_eq!(c.cache_size(), 2);

        // Insert beyond new cap triggers eviction.
        c.cache_set(4, 4);
        assert_eq!(c.cache_size(), 2);
    }

    #[test]
    fn set_max_size_shrink_fires_on_evict_and_counts_evictions() {
        use std::sync::{Arc, Mutex};
        let evicted_keys: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));
        let evicted_keys2 = evicted_keys.clone();
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(4)
            .on_evict(move |k: &u8, _v: &ExpiredU8| {
                evicted_keys2.lock().unwrap().push(*k);
            })
            .build()
            .unwrap();

        // Values 1..=4 are all <= 10, so none are expired.
        c.cache_set(1, 1);
        c.cache_set(2, 2);
        c.cache_set(3, 3);
        c.cache_set(4, 4);
        // Touch 1 and 2 so 3 and 4 become least-recently-used.
        assert_eq!(c.cache_get(&1), Some(&1));
        assert_eq!(c.cache_get(&2), Some(&2));

        let evictions_before = c.cache_evictions().expect("evictions tracked");
        let prev = c.set_max_size(2);
        assert_eq!(prev, Some(4));
        assert_eq!(c.capacity(), 2);
        assert_eq!(c.cache_size(), 2);

        // Two entries were dropped; eviction counter must reflect that.
        assert_eq!(
            c.cache_evictions().expect("evictions tracked") - evictions_before,
            2,
            "set_max_size shrink must increment cache_evictions by the number of dropped entries"
        );

        // on_evict must have fired for exactly the two LRU keys (3 and 4).
        let mut fired: Vec<u8> = evicted_keys.lock().unwrap().clone();
        fired.sort();
        assert_eq!(
            fired,
            vec![3, 4],
            "on_evict must fire for the evicted (least-recently-used) keys"
        );

        // The two most-recently-used entries must survive.
        assert_eq!(c.cache_get(&1), Some(&1));
        assert_eq!(c.cache_get(&2), Some(&2));
        assert_eq!(c.cache_get(&3), None);
        assert_eq!(c.cache_get(&4), None);
    }

    #[test]
    fn retain_increments_outer_evictions_not_inner() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        c.cache_set(1, 1); // live, kept by the predicate
        c.cache_set(2, 4); // live, removed by the predicate
        c.cache_set(3, 20); // expired, removed despite the predicate matching it

        let removed = c.retain(|_, v| *v == 1 || *v == 20);
        assert_eq!(c.cache_size(), 1);
        assert_eq!(c.cache_get(&1), Some(&1));

        // `retain` posts its removals to the outer `evictions` counter, not the
        // inner LruCache capacity counter; `cache_reset_metrics` resets the two
        // independently, so the bucket matters, not just the combined total.
        assert_eq!(c.evictions.load(Ordering::Relaxed), 2);
        assert_eq!(c.store.cache_evictions(), Some(0));
        assert_eq!(c.cache_evictions(), Some(2));
        // The returned count folds together the one predicate rejection (key 2) and
        // the one expired sweep (key 3).
        assert_eq!(removed, 2);
    }

    #[test]
    fn retain_returns_count_folding_expired_and_predicate_rejections() {
        // The returned count must fold together BOTH predicate-rejected entries and
        // entries removed for having already expired, and must agree with the
        // `cache_size()` delta and the number of `on_evict` invocations.
        use std::sync::Arc;
        use std::sync::atomic::AtomicUsize;

        let fired = Arc::new(AtomicUsize::new(0));
        let fired2 = fired.clone();
        let mut c: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(10)
            .on_evict(move |_k: &u8, _v: &ExpiredU8| {
                fired2.fetch_add(1, Ordering::Relaxed);
            })
            .build()
            .unwrap();

        c.cache_set(1, 20); // expired (>10): swept regardless of predicate
        c.cache_set(2, 2); // even, live: kept
        c.cache_set(3, 3); // odd, live: rejected by predicate
        c.cache_set(4, 4); // even, live: kept

        let size_before = c.cache_size();
        let removed = c.retain(|_, v| v % 2 == 0);
        let size_after = c.cache_size();

        assert_eq!(
            removed, 2,
            "one expired sweep (key 1) + one predicate rejection (key 3)"
        );
        assert_eq!(size_before - size_after, removed);
        assert_eq!(fired.load(Ordering::Relaxed), removed);
        assert_eq!(c.cache_get(&2), Some(&2));
        assert_eq!(c.cache_get(&3), None);
        assert_eq!(c.cache_get(&4), Some(&4));
    }

    #[test]
    fn try_set_max_size_rejects_zero() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        assert_eq!(
            c.try_set_max_size(0),
            Err(super::super::SetMaxSizeError::ZeroMaxSize)
        );
        assert_eq!(c.try_set_max_size(5).unwrap(), Some(3));
    }

    #[test]
    #[should_panic(expected = "max_size must be greater than zero")]
    fn set_max_size_zero_panics() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.set_max_size(0);
    }

    #[test]
    fn eq_same_entries_compare_equal() {
        let mut a: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        let mut b: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        a.cache_set(1, 5);
        a.cache_set(2, 6);
        // Insert in a different order: inner LruCache equality is membership-based.
        b.cache_set(2, 6);
        b.cache_set(1, 5);
        assert_eq!(
            a, b,
            "caches with the same stored entries must compare equal"
        );
    }

    #[test]
    fn eq_ignores_metrics_and_on_evict() {
        // Equality is over stored entries only: differing metrics and an
        // `on_evict` callback on one side must not break it.
        let mut a: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        let mut b: ExpiringLruCache<u8, ExpiredU8> = ExpiringLruCache::builder()
            .max_size(4)
            .on_evict(|_k: &u8, _v: &ExpiredU8| {})
            .build()
            .unwrap();
        a.cache_set(1, 5);
        b.cache_set(1, 5);
        // Drive `a`'s metrics away from `b`'s.
        a.cache_get(&1);
        a.cache_get(&99);
        assert_ne!(a.cache_hits(), b.cache_hits());
        assert_eq!(
            a, b,
            "metrics and on_evict must not participate in equality"
        );
    }

    #[test]
    fn ne_differing_entries() {
        let mut a: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        let mut b: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        a.cache_set(1, 5);
        b.cache_set(1, 6); // same key, different value
        assert_ne!(a, b, "differing values must compare unequal");

        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        c.cache_set(1, 5);
        c.cache_set(2, 5); // extra key
        assert_ne!(a, c, "differing key sets must compare unequal");

        // An empty cache differs from a populated one and equals another empty one.
        let empty1: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        let empty2: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();
        assert_eq!(empty1, empty2);
        assert_ne!(empty1, a);
    }

    // --- expires_at tests ---

    /// A type that overrides `expires_at` to return a concrete deadline.
    #[derive(Clone, Copy, Debug, PartialEq)]
    struct TimedValue {
        deadline: crate::time::Instant,
    }

    impl Expires for TimedValue {
        fn is_expired(&self) -> bool {
            crate::time::Instant::now() >= self.deadline
        }

        fn expires_at(&self) -> Option<crate::time::Instant> {
            Some(self.deadline)
        }
    }

    #[test]
    fn expires_at_default_returns_none() {
        // ExpiredU8 does not override expires_at, so the default must return None.
        let v: ExpiredU8 = 5;
        assert_eq!(
            v.expires_at(),
            None,
            "default expires_at must return None for types that do not track a deadline"
        );
    }

    #[test]
    fn expires_at_override_returns_some_instant() {
        let deadline = crate::time::Instant::now() + std::time::Duration::from_secs(60);
        let v = TimedValue { deadline };
        assert_eq!(
            v.expires_at(),
            Some(deadline),
            "expires_at must return the overridden deadline when the impl provides one"
        );
        // Confirm is_expired is not confused: a future deadline is not yet expired.
        assert!(
            !v.is_expired(),
            "a value whose deadline is in the future must not be expired"
        );
    }

    /// `is_expired` is the authoritative liveness check; `expires_at` is advisory only.
    /// This type deliberately reports a deadline that is already in the past while
    /// claiming to be live. A correct cache must consult `is_expired` (live), NOT
    /// `expires_at` (past), and therefore keep the entry.
    #[derive(Clone, Copy, Debug, PartialEq)]
    struct LiveDespitePastDeadline {
        past: crate::time::Instant,
    }

    impl Expires for LiveDespitePastDeadline {
        fn is_expired(&self) -> bool {
            // Authoritative: always live, regardless of the advisory deadline below.
            false
        }

        fn expires_at(&self) -> Option<crate::time::Instant> {
            // Advisory: a deadline in the past. Must not be used for liveness.
            Some(self.past)
        }
    }

    #[test]
    fn expires_at_past_does_not_override_is_expired_for_value() {
        // Sanity at the value level: the two methods disagree on purpose.
        let v = LiveDespitePastDeadline {
            past: crate::time::Instant::now() - std::time::Duration::from_secs(3600),
        };
        assert!(
            !v.is_expired(),
            "is_expired is authoritative and reports the value as live"
        );
        let reported = v.expires_at().expect("override returns Some");
        assert!(
            reported < crate::time::Instant::now(),
            "expires_at advisory deadline is in the past"
        );
    }

    #[test]
    fn cache_keeps_entry_with_past_expires_at_but_live_is_expired() {
        // Contract: the cache must decide liveness from is_expired, not expires_at.
        // The stored value's expires_at is in the past, but is_expired() == false,
        // so the entry must be returned as a live hit and survive in the cache.
        let past = crate::time::Instant::now() - std::time::Duration::from_secs(3600);
        let mut c: ExpiringLruCache<u8, LiveDespitePastDeadline> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, LiveDespitePastDeadline { past });

        // get must treat it as a live hit (is_expired() == false).
        assert!(
            c.cache_get(&1u8).is_some(),
            "entry whose is_expired() is false must be returned even if expires_at is in the past"
        );
        assert_eq!(c.cache_hits(), Some(1), "the access must count as a hit");
        assert_eq!(
            c.cache_misses(),
            Some(0),
            "an entry the cache treats as live must not register a miss"
        );
        assert_eq!(c.cache_size(), 1, "the live entry must remain in the cache");

        // evict() must also consult is_expired, not expires_at: nothing is removed.
        assert_eq!(
            c.evict(),
            0,
            "evict must not remove an entry whose is_expired() is false"
        );
        assert_eq!(c.cache_size(), 1);

        // peek and iter must likewise keep it.
        assert!(
            c.cache_peek(&1u8).is_some(),
            "peek must surface the live entry"
        );
        let keys: Vec<u8> = c.iter().map(|(&k, _)| k).collect();
        assert_eq!(keys, vec![1], "iter must include the live entry");
    }

    /// A type that provides ONLY `is_expired`, relying on the trait default for
    /// `expires_at`. The fact that this compiles and is usable as a cache value is
    /// the contract: adding `expires_at` did not break impls that omit it.
    struct OnlyIsExpired(bool);

    impl Expires for OnlyIsExpired {
        fn is_expired(&self) -> bool {
            self.0
        }
        // expires_at intentionally not provided — exercises the default impl.
    }

    #[test]
    fn impl_with_only_is_expired_compiles_and_defaults_expires_at_to_none() {
        let live = OnlyIsExpired(false);
        assert!(!live.is_expired());
        assert_eq!(
            live.expires_at(),
            None,
            "an impl omitting expires_at must inherit the None default"
        );

        // And it works as a cache value type end to end.
        let mut c: ExpiringLruCache<u8, OnlyIsExpired> =
            ExpiringLruCache::builder().max_size(2).build().unwrap();
        c.cache_set(1, OnlyIsExpired(false)); // live
        c.cache_set(2, OnlyIsExpired(true)); // expired
        assert!(c.cache_get(&1u8).is_some(), "live entry returned");
        assert!(c.cache_get(&2u8).is_none(), "expired entry not returned");
    }

    // --- CacheExpiry::cache_peek_expires_at ---

    /// A value type whose `is_expired` reports EXPIRED while `expires_at` (advisory)
    /// reports a deadline still in the future -- the other direction of disagreement
    /// from [`LiveDespitePastDeadline`]. Pins that `cache_peek_expires_at` surfaces the
    /// advisory deadline unreconciled even when it contradicts `is_expired` by claiming
    /// the entry is still good.
    #[derive(Clone, Copy, Debug, PartialEq)]
    struct ExpiredDespiteFutureDeadline {
        future: crate::time::Instant,
    }

    impl Expires for ExpiredDespiteFutureDeadline {
        fn is_expired(&self) -> bool {
            true
        }

        fn expires_at(&self) -> Option<crate::time::Instant> {
            Some(self.future)
        }
    }

    #[test]
    fn peek_expires_at_absent_key_returns_none_none() {
        let c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        assert_eq!(c.cache_peek_expires_at(&1u8), (None, None));
    }

    #[test]
    fn peek_expires_at_alias_agrees_with_required_method() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 2);
        assert_eq!(
            c.peek_expires_at(&1u8),
            c.cache_peek_expires_at(&1u8),
            "the alias must agree with the required method"
        );
    }

    #[test]
    fn peek_expires_at_alias_agrees_with_required_method_across_all_return_shapes() {
        // The trait docs enumerate four return shapes: (None, None) absent,
        // (Some(v), None) no known deadline, (Some(v), Some(t)) with t in the future,
        // and (Some(v), Some(t)) with t in the past. The alias must agree with the
        // required method on every one of them, not just the first shape exercised
        // above.
        let mut c: ExpiringLruCache<u8, TimedValue> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();

        // Shape 1: (None, None) -- absent key.
        assert_eq!(c.peek_expires_at(&1u8), c.cache_peek_expires_at(&1u8));
        assert_eq!(c.peek_expires_at(&1u8), (None, None));

        // Shape 2: (Some(v), Some(t)) with t in the future -- present, live, deadline known.
        let future = crate::time::Instant::now() + std::time::Duration::from_secs(60);
        c.cache_set(1, TimedValue { deadline: future });
        assert_eq!(c.peek_expires_at(&1u8), c.cache_peek_expires_at(&1u8));
        assert_eq!(
            c.peek_expires_at(&1u8),
            (Some(TimedValue { deadline: future }), Some(future))
        );

        // Shape 3: (Some(v), Some(t)) with t in the past -- deadline known but stale.
        let past = crate::time::Instant::now() - std::time::Duration::from_secs(60);
        c.cache_set(2, TimedValue { deadline: past });
        assert_eq!(c.peek_expires_at(&2u8), c.cache_peek_expires_at(&2u8));
        assert_eq!(
            c.peek_expires_at(&2u8),
            (Some(TimedValue { deadline: past }), Some(past))
        );

        // Shape 4: (Some(v), None) -- present, no known deadline.
        let mut d: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        d.cache_set(1, 2);
        assert_eq!(d.peek_expires_at(&1u8), d.cache_peek_expires_at(&1u8));
        assert_eq!(d.peek_expires_at(&1u8), (Some(2), None));
    }

    #[test]
    fn peek_expires_at_value_overriding_expires_at_returns_its_deadline() {
        let deadline = crate::time::Instant::now() + std::time::Duration::from_secs(60);
        let mut c: ExpiringLruCache<u8, TimedValue> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, TimedValue { deadline });

        let (value, expires_at) = c.cache_peek_expires_at(&1u8);
        assert_eq!(value, Some(TimedValue { deadline }));
        assert_eq!(
            expires_at,
            Some(deadline),
            "the reported deadline must be the one the value reports"
        );
    }

    #[test]
    fn peek_expires_at_value_not_overriding_expires_at_returns_no_deadline() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 2); // live: is_expired() is false
        assert_eq!(
            c.cache_peek_expires_at(&1u8),
            (Some(2), None),
            "a value type that does not override expires_at must report no deadline"
        );
    }

    #[test]
    fn peek_expires_at_expired_entry_without_override_returns_no_deadline() {
        // Pins the documented caveat: `None` does not imply live. The entry IS
        // expired (is_expired() == true) but the value type never overrode
        // expires_at, so the advisory deadline is still None, and the entry is
        // kept (not removed) by the peek.
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 99); // 99 > 10, so is_expired() is true

        let (value, expires_at) = c.cache_peek_expires_at(&1u8);
        assert_eq!(value, Some(99), "an expired entry is still returned");
        assert_eq!(
            expires_at, None,
            "None on this store does not mean live: the value never tracked a deadline"
        );
        assert_eq!(
            c.cache_peek_with_expiry_status(&1u8),
            (Some(99), true),
            "is_expired, not expires_at, remains the authority on liveness"
        );
        assert_eq!(c.cache_size(), 1, "the peek must not remove the entry");
    }

    #[test]
    fn peek_expires_at_advisory_past_deadline_survives_while_is_expired_reports_live() {
        // Pins the documented caveat in the other direction: the advisory deadline
        // can be in the past for an entry is_expired() reports as live, and
        // cache_peek_expires_at must surface that stale deadline unchanged rather
        // than reconciling it against is_expired().
        let past = crate::time::Instant::now() - std::time::Duration::from_secs(3600);
        let mut c: ExpiringLruCache<u8, LiveDespitePastDeadline> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, LiveDespitePastDeadline { past });

        let (value, expires_at) = c.cache_peek_expires_at(&1u8);
        assert_eq!(value, Some(LiveDespitePastDeadline { past }));
        assert_eq!(
            expires_at,
            Some(past),
            "the advisory deadline must be surfaced unchanged, even though it is in the past"
        );
        assert_eq!(
            c.cache_peek_with_expiry_status(&1u8),
            (Some(LiveDespitePastDeadline { past }), false),
            "cache_peek_with_expiry_status must still report the entry as live"
        );
    }

    #[test]
    fn peek_expires_at_does_not_touch_hit_or_miss_counters() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 2);
        let hits = c.cache_hits();
        let misses = c.cache_misses();

        let _ = c.cache_peek_expires_at(&1u8); // present
        let _ = c.cache_peek_expires_at(&2u8); // absent

        assert_eq!(c.cache_hits(), hits, "a peek must not count a hit");
        assert_eq!(c.cache_misses(), misses, "a peek must not count a miss");
    }

    #[test]
    fn peek_expires_at_does_not_promote_recency() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 1);
        c.cache_set(2, 2);
        c.cache_set(3, 3);
        // LRU order after inserts (MRU -> LRU): 3, 2, 1.
        assert_eq!(c.key_order(), vec![3, 2, 1]);

        // Peek the least-recently-used key: cache_peek_expires_at must not promote it.
        let _ = c.cache_peek_expires_at(&1u8);
        assert_eq!(
            c.key_order(),
            vec![3, 2, 1],
            "cache_peek_expires_at must not reorder recency"
        );

        // Control: a real access does promote, so the assertion above is not vacuous.
        assert_eq!(c.cache_get(&1u8), Some(&1));
        assert_eq!(c.key_order(), vec![1, 3, 2]);
    }

    #[test]
    fn peek_expires_at_peeked_lru_tail_remains_the_next_eviction_victim() {
        // Behavioral (not just representation-level) confirmation of non-promotion:
        // peeking the current LRU-tail key and then forcing a capacity eviction must
        // still evict exactly that key, not one of its neighbors. All three stored
        // values are live, so nothing here is evicted for having expired -- the only
        // way key 1 survives to be the eviction victim is if the peek genuinely left
        // recency order untouched.
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 1); // becomes LRU tail
        c.cache_set(2, 2);
        c.cache_set(3, 3); // MRU

        let _ = c.cache_peek_expires_at(&1u8);

        // Insert a 4th key: this forces a capacity eviction of the LRU tail.
        c.cache_set(4, 4);
        assert_eq!(c.cache_size(), 3);
        assert_eq!(
            c.cache_get(&1u8),
            None,
            "the peeked key must still be the eviction victim -- the peek did not \
             promote it out of the LRU tail"
        );
        assert_eq!(c.cache_get(&2u8), Some(&2));
        assert_eq!(c.cache_get(&3u8), Some(&3));
        assert_eq!(c.cache_get(&4u8), Some(&4));
    }

    #[test]
    fn peek_expires_at_advisory_future_deadline_survives_while_is_expired_reports_expired() {
        // The other direction of disagreement from the past-deadline-while-live test
        // above: a future advisory deadline while is_expired() reports EXPIRED.
        // cache_peek_expires_at must surface the future deadline unreconciled, but
        // is_expired must still be the authority the store itself acts on -- a real
        // access (cache_get) must treat the entry as gone despite the future-looking
        // advisory deadline.
        let future = crate::time::Instant::now() + std::time::Duration::from_secs(3600);
        let mut c: ExpiringLruCache<u8, ExpiredDespiteFutureDeadline> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, ExpiredDespiteFutureDeadline { future });

        let (value, expires_at) = c.cache_peek_expires_at(&1u8);
        assert_eq!(value, Some(ExpiredDespiteFutureDeadline { future }));
        assert_eq!(
            expires_at,
            Some(future),
            "the advisory deadline must be surfaced unchanged, even though it is in the future"
        );
        assert_eq!(
            c.cache_peek_with_expiry_status(&1u8),
            (Some(ExpiredDespiteFutureDeadline { future }), true),
            "cache_peek_with_expiry_status must still report the entry as expired"
        );
        assert_eq!(c.cache_size(), 1, "the peek must not remove the entry");

        // The store's real read path must obey is_expired, not the advisory deadline.
        assert_eq!(
            c.cache_get(&1u8),
            None,
            "is_expired remains the authority the store acts on, regardless of a \
             future-looking advisory deadline"
        );
        assert_eq!(
            c.cache_size(),
            0,
            "the expired entry must be swept on the real access"
        );
    }

    #[test]
    fn peek_expires_at_reflects_new_deadline_after_overwrite() {
        // Overwriting a key with a value carrying a different advisory deadline must
        // not leave the old deadline visible: the store re-reads the currently stored
        // value on every peek rather than caching a stale expires_at snapshot.
        let first_deadline = crate::time::Instant::now() + std::time::Duration::from_secs(60);
        let second_deadline = crate::time::Instant::now() + std::time::Duration::from_secs(120);
        let mut c: ExpiringLruCache<u8, TimedValue> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();

        c.cache_set(
            1,
            TimedValue {
                deadline: first_deadline,
            },
        );
        assert_eq!(
            c.cache_peek_expires_at(&1u8),
            (
                Some(TimedValue {
                    deadline: first_deadline
                }),
                Some(first_deadline)
            )
        );

        c.cache_set(
            1,
            TimedValue {
                deadline: second_deadline,
            },
        );
        assert_eq!(
            c.cache_peek_expires_at(&1u8),
            (
                Some(TimedValue {
                    deadline: second_deadline
                }),
                Some(second_deadline)
            ),
            "an overwrite must replace the visible deadline, not retain the old one"
        );
    }

    #[test]
    fn peek_expires_at_reports_absent_after_evict_removes_the_entry() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 99); // 99 > 10, so is_expired() is true

        let (value, expires_at) = c.cache_peek_expires_at(&1u8);
        assert_eq!(value, Some(99));
        assert_eq!(expires_at, None, "ExpiredU8 never overrides expires_at");

        assert_eq!(
            c.evict(),
            1,
            "evict must physically remove the expired entry"
        );
        let (value, expires_at) = c.cache_peek_expires_at(&1u8);
        assert!(
            value.is_none(),
            "a physically removed entry must be reported as absent"
        );
        assert_eq!(expires_at, None);
    }

    #[test]
    fn peek_expires_at_reports_absent_after_cache_remove() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 2); // live: is_expired() is false
        let removed = c.cache_remove(&1u8);
        assert_eq!(removed, Some(2));

        let (value, expires_at) = c.cache_peek_expires_at(&1u8);
        assert!(value.is_none());
        assert_eq!(expires_at, None);
        let (value, expires_at) = c.peek_expires_at(&1u8);
        assert!(value.is_none());
        assert_eq!(expires_at, None);
    }

    // --- CacheExpiry::cache_expires_at ---

    #[test]
    fn expires_at_absent_key_returns_false_none() {
        let c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        assert_eq!(c.cache_expires_at(&1u8), (false, None));
    }

    #[test]
    fn expires_at_value_overriding_expires_at_returns_its_deadline() {
        let deadline = crate::time::Instant::now() + std::time::Duration::from_secs(60);
        let mut c: ExpiringLruCache<u8, TimedValue> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, TimedValue { deadline });

        let (present, expires_at) = c.cache_expires_at(&1u8);
        assert!(present);
        assert_eq!(
            expires_at,
            Some(deadline),
            "the reported deadline must be the one the value reports"
        );
    }

    #[test]
    fn expires_at_expired_entry_without_override_returns_present_no_deadline() {
        // The entry IS expired (is_expired() == true) but the value type never overrode
        // expires_at, so the deadline is still None -- None here does not mean live, and
        // the presence flag is independent of expiry.
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 99); // 99 > 10, so is_expired() is true

        assert_eq!(
            c.cache_expires_at(&1u8),
            (true, None),
            "present with no deadline, not evidence of liveness"
        );
        assert_eq!(
            c.cache_peek_with_expiry_status(&1u8),
            (Some(99), true),
            "is_expired remains the authority on liveness"
        );
        assert_eq!(c.cache_size(), 1, "the read must not remove the entry");
    }

    #[test]
    fn expires_at_advisory_future_deadline_survives_while_is_expired_reports_expired() {
        // A future advisory deadline while is_expired() reports EXPIRED must be surfaced
        // unreconciled.
        let future = crate::time::Instant::now() + std::time::Duration::from_secs(3600);
        let mut c: ExpiringLruCache<u8, ExpiredDespiteFutureDeadline> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, ExpiredDespiteFutureDeadline { future });

        assert_eq!(
            c.cache_expires_at(&1u8),
            (true, Some(future)),
            "the advisory future deadline must be surfaced unreconciled"
        );
        assert_eq!(
            c.cache_peek_with_expiry_status(&1u8),
            (Some(ExpiredDespiteFutureDeadline { future }), true),
            "is_expired must still report the entry as expired"
        );
    }

    #[test]
    fn expires_at_advisory_past_deadline_survives_while_is_expired_reports_live() {
        // The other direction: an advisory deadline in the past while is_expired()
        // reports live must also be surfaced unreconciled.
        let past = crate::time::Instant::now() - std::time::Duration::from_secs(3600);
        let mut c: ExpiringLruCache<u8, LiveDespitePastDeadline> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, LiveDespitePastDeadline { past });

        assert_eq!(
            c.cache_expires_at(&1u8),
            (true, Some(past)),
            "the advisory past deadline must be surfaced unreconciled"
        );
        assert_eq!(
            c.cache_peek_with_expiry_status(&1u8),
            (Some(LiveDespitePastDeadline { past }), false),
            "is_expired must still report the entry as live"
        );
    }

    // The two reads must never disagree: identical deadline, and the presence flag must
    // track whether the value-bearing read returned `Some`. Covers all four return shapes
    // including the alias.
    #[test]
    fn expires_at_agrees_with_peek_expires_at_across_all_return_shapes() {
        let mut c: ExpiringLruCache<u8, TimedValue> =
            ExpiringLruCache::builder().max_size(4).build().unwrap();

        let check = |c: &ExpiringLruCache<u8, TimedValue>, k: u8, label: &str| {
            let (value, peeked) = c.cache_peek_expires_at(&k);
            let (present, deadline) = c.cache_expires_at(&k);
            assert_eq!(
                present,
                value.is_some(),
                "presence flag disagrees ({label})"
            );
            assert_eq!(deadline, peeked, "deadline disagrees ({label})");
            assert_eq!(
                c.expires_at(&k),
                c.cache_expires_at(&k),
                "alias disagrees ({label})"
            );
        };

        // absent
        check(&c, 1, "absent");
        assert_eq!(c.cache_expires_at(&1u8), (false, None));

        // live, deadline known
        let future = crate::time::Instant::now() + std::time::Duration::from_secs(60);
        c.cache_set(1, TimedValue { deadline: future });
        check(&c, 1, "live");

        // expired (is_expired), deadline known and in the past
        let past = crate::time::Instant::now() - std::time::Duration::from_secs(60);
        c.cache_set(2, TimedValue { deadline: past });
        check(&c, 2, "expired");

        // present, no known deadline
        let mut d: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        d.cache_set(1, 2);
        let (value, peeked) = d.cache_peek_expires_at(&1u8);
        let (present, deadline) = d.cache_expires_at(&1u8);
        assert_eq!(
            present,
            value.is_some(),
            "presence flag disagrees (no-deadline)"
        );
        assert_eq!(deadline, peeked, "deadline disagrees (no-deadline)");
        assert_eq!(
            d.expires_at(&1u8),
            d.cache_expires_at(&1u8),
            "alias disagrees (no-deadline)"
        );
        assert_eq!(d.cache_expires_at(&1u8), (true, None));
    }

    #[test]
    fn expires_at_does_not_touch_hit_or_miss_counters() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 2);
        let hits = c.cache_hits();
        let misses = c.cache_misses();

        let _ = c.cache_expires_at(&1u8); // present
        let _ = c.cache_expires_at(&2u8); // absent
        let _ = c.expires_at(&1u8); // alias

        assert_eq!(c.cache_hits(), hits, "the read must not count a hit");
        assert_eq!(c.cache_misses(), misses, "the read must not count a miss");
    }

    #[test]
    fn expires_at_does_not_promote_recency() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 1);
        c.cache_set(2, 2);
        c.cache_set(3, 3);
        // LRU order after inserts (MRU -> LRU): 3, 2, 1.
        assert_eq!(c.key_order(), vec![3, 2, 1]);

        let _ = c.cache_expires_at(&1u8);
        assert_eq!(
            c.key_order(),
            vec![3, 2, 1],
            "cache_expires_at must not reorder recency"
        );

        // Control: a real access does promote, so the assertion above is not vacuous.
        assert_eq!(c.cache_get(&1u8), Some(&1));
        assert_eq!(c.key_order(), vec![1, 3, 2]);
    }

    #[test]
    fn expires_at_peeked_lru_tail_remains_the_next_eviction_victim() {
        // Behavioral (not just representation-level) confirmation of non-promotion: reading
        // the deadline of the current LRU-tail key and then forcing a capacity eviction must
        // still evict exactly that key. All three stored values are live, so nothing here is
        // evicted for having expired -- the only way key 1 survives to be the eviction victim
        // is if the read genuinely left recency order untouched.
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 1); // becomes LRU tail
        c.cache_set(2, 2);
        c.cache_set(3, 3); // MRU

        let _ = c.cache_expires_at(&1u8);

        // Insert a 4th key: this forces a capacity eviction of the LRU tail.
        c.cache_set(4, 4);
        assert_eq!(c.cache_size(), 3);
        assert_eq!(
            c.cache_get(&1u8),
            None,
            "the key read via cache_expires_at must still be the eviction victim -- the \
             read did not promote it out of the LRU tail"
        );
        assert_eq!(c.cache_get(&2u8), Some(&2));
        assert_eq!(c.cache_get(&3u8), Some(&3));
        assert_eq!(c.cache_get(&4u8), Some(&4));
    }

    #[test]
    fn expires_at_reports_absent_after_evict_removes_the_entry() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 99); // 99 > 10, so is_expired() is true

        assert_eq!(
            c.cache_expires_at(&1u8),
            (true, None),
            "the expired entry is still stored before the sweep"
        );
        assert_eq!(
            c.evict(),
            1,
            "evict must physically remove the expired entry"
        );
        assert_eq!(
            c.cache_expires_at(&1u8),
            (false, None),
            "a physically removed entry must be reported absent"
        );
    }

    #[test]
    fn expires_at_reports_absent_after_cache_remove() {
        let mut c: ExpiringLruCache<u8, ExpiredU8> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, 2); // live: is_expired() is false
        assert_eq!(c.cache_remove(&1u8), Some(2));

        assert_eq!(c.cache_expires_at(&1u8), (false, None));
        assert_eq!(
            c.expires_at(&1u8),
            (false, None),
            "the alias must agree on the removed key too"
        );
    }

    // The point of moving `V: Clone` off the impl block and onto the value-bearing method:
    // a deadline read must work on a cache whose value type is not `Clone` at all. The
    // helper carries no `V: Clone` bound anywhere, so this fails to compile if the bound
    // creeps back onto either the trait method or the impl.
    #[test]
    fn expires_at_reads_a_deadline_for_a_value_type_that_is_not_clone() {
        #[derive(Debug, PartialEq)]
        struct NotClone(u32);

        impl Expires for NotClone {
            fn is_expired(&self) -> bool {
                false
            }
            fn expires_at(&self) -> Option<crate::time::Instant> {
                Some(crate::time::Instant::now() + std::time::Duration::from_secs(60))
            }
        }

        fn deadline<K: Hash + Eq + Clone, V: Expires>(
            c: &ExpiringLruCache<K, V>,
            k: &K,
        ) -> (bool, Option<crate::time::Instant>) {
            c.cache_expires_at(k)
        }

        let mut c: ExpiringLruCache<u8, NotClone> =
            ExpiringLruCache::builder().max_size(3).build().unwrap();
        c.cache_set(1, NotClone(100));

        let (present, expires_at) = deadline(&c, &1);
        assert!(present);
        assert!(
            expires_at.expect("a live entry with an override must record a deadline")
                > crate::time::Instant::now()
        );
        assert_eq!(deadline(&c, &2), (false, None), "absent key");
        // The alias is equally bound-free.
        assert!(c.expires_at(&1u8).0);
        // The value was never cloned or moved out: it is still in the store.
        assert_eq!(c.cache_peek(&1u8), Some(&NotClone(100)));
    }
}