cached 3.0.0-rc.10

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
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
use crate::time::Duration;
use crate::time::Instant;
use std::cmp::Eq;
use std::hash::Hash;

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

use crate::{CachedIter, CachedPeek, CloneCached};

use super::{CacheEvict, Cached, DefaultHashBuilder, LruCache, TimedEntry};
use std::hash::BuildHasher;
use std::marker::PhantomData;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

/// Timed LRU Cache
///
/// Stores a limited number of values,
/// evicting expired and least-used entries.
/// Time expiration is determined based on entry insertion time.
/// By default, the TTL of an entry is not refreshed on retrieval.
/// Set `refresh = true` to refresh the TTL on cache hits.
///
/// Note: This cache is in-memory only
///
/// **`len` / `iter` / `evict` contract**: `len()` 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.
///
/// The optional type parameter `S` selects the hash builder. It defaults to
/// [`DefaultHashBuilder`] (ahash when the `ahash` feature is enabled, otherwise
/// `std::collections::hash_map::RandomState`). Supply a custom `S` via
/// [`LruTtlCacheBuilder::hasher`] to use a different hasher.
#[doc(alias = "TimedSizedCache")]
pub struct LruTtlCache<K, V, S = DefaultHashBuilder> {
    pub(super) store: LruCache<K, TimedEntry<V>, S>,
    pub(super) size: usize,
    pub(super) ttl: Duration,
    pub(super) hits: AtomicU64,
    pub(super) misses: AtomicU64,
    pub(super) evictions: AtomicU64,
    pub(super) refresh: bool,
    pub(super) on_evict: Option<super::OnEvict<K, V>>,
}

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

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

/// Typestate marker for [`LruTtlCacheBuilder`]: no eviction callback set.
///
/// This appears as the builder's `E` type parameter default. It only encodes
/// builder state; most code never names it directly.
#[derive(Clone, Copy, Debug, Default)]
pub struct NoEvict;

/// Typestate marker for [`LruTtlCacheBuilder`]: eviction callback has been set.
///
/// When this marker is active, [`LruTtlCacheBuilder::build`] requires
/// `K: 'static` and `V: 'static` because the callback must be wired into
/// the inner LRU store. It only encodes builder state; most code never
/// names it directly.
#[derive(Clone, Copy, Debug, Default)]
pub struct HasEvict;

/// Builder for [`LruTtlCache`].
///
/// Obtain one via [`LruTtlCache::builder`].
///
/// The `E` type parameter is a compile-time marker:
/// - [`NoEvict`] (the default): no eviction callback has been set; `build`
///   does **not** require `K: 'static` or `V: 'static`.
/// - [`HasEvict`]: an eviction callback was registered via [`on_evict`](LruTtlCacheBuilder::on_evict);
///   `build` requires `K: 'static + V: 'static` so the callback
///   can be wired into the inner LRU eviction path.
///
/// The `S` type parameter selects the hash builder; it defaults to [`DefaultHashBuilder`].
/// Call [`.hasher()`](LruTtlCacheBuilder::hasher) to use a custom hasher.
pub struct LruTtlCacheBuilder<K, V, E = NoEvict, S = DefaultHashBuilder> {
    size: Option<usize>,
    ttl: Option<Duration>,
    refresh: bool,
    on_evict: Option<super::OnEvict<K, V>>,
    hasher: S,
    _evict: PhantomData<E>,
}

impl<K, V> Default for LruTtlCacheBuilder<K, V> {
    fn default() -> Self {
        Self {
            size: None,
            ttl: None,
            refresh: false,
            on_evict: None,
            hasher: super::new_default_hash_builder(),
            _evict: PhantomData,
        }
    }
}

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

// size / ttl / refresh work regardless of eviction state or hasher
impl<K, V, E, S> LruTtlCacheBuilder<K, V, E, S> {
    /// Set the maximum number of entries. Required.
    #[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 the TTL for cache entries. Required.
    ///
    /// Overrides any previously set ttl/ttl_secs/ttl_millis on this builder.
    #[must_use]
    pub fn ttl(mut self, ttl: Duration) -> Self {
        self.ttl = Some(ttl);
        self
    }

    /// Set the TTL for cache entries in whole seconds. Equivalent to
    /// `ttl(Duration::from_secs(secs))`.
    ///
    /// Overrides any previously set ttl/ttl_secs/ttl_millis on this builder.
    #[must_use]
    pub fn ttl_secs(self, secs: u64) -> Self {
        self.ttl(Duration::from_secs(secs))
    }

    /// Set the TTL for cache entries in milliseconds. Equivalent to
    /// `ttl(Duration::from_millis(millis))`.
    ///
    /// Overrides any previously set ttl/ttl_secs/ttl_millis on this builder.
    #[must_use]
    pub fn ttl_millis(self, millis: u64) -> Self {
        self.ttl(Duration::from_millis(millis))
    }

    /// Set whether cache hits refresh the TTL of the accessed entry.
    #[must_use]
    pub fn refresh_on_hit(mut self, refresh: bool) -> Self {
        self.refresh = refresh;
        self
    }

    /// Switch to a custom hash builder `S2`, returning a builder parameterized on `S2`.
    ///
    /// The hasher is used to hash keys in the internal backing `LruCache`. Calling this
    /// method changes the builder's `S` type parameter so `build()` returns an
    /// `LruTtlCache<K, V, S2>`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use cached::{Cached, LruTtlCache};
    /// use cached::time::Duration;
    /// use std::collections::hash_map::RandomState;
    ///
    /// let mut cache = LruTtlCache::<u32, u32>::builder()
    ///     .max_size(10)
    ///     .ttl_secs(60)
    ///     .hasher(RandomState::new())
    ///     .build()
    ///     .unwrap();
    /// cache.cache_set(1, 100);
    /// assert_eq!(cache.cache_get(&1), Some(&100));
    /// ```
    #[doc(alias = "with_hasher")]
    #[must_use]
    pub fn hasher<S2: BuildHasher>(self, hasher: S2) -> LruTtlCacheBuilder<K, V, E, S2> {
        LruTtlCacheBuilder {
            size: self.size,
            ttl: self.ttl,
            refresh: self.refresh,
            on_evict: self.on_evict,
            hasher,
            _evict: PhantomData,
        }
    }
}

// on_evict transitions the builder from NoEvict -> HasEvict
impl<K, V, S> LruTtlCacheBuilder<K, V, NoEvict, S> {
    /// 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`](LruTtlCache::set_max_size) /
    ///   [`try_set_max_size`](LruTtlCache::try_set_max_size).
    /// - TTL-expiry sweeps via [`evict`](LruTtlCache::evict).
    /// - Lazy TTL-expiry sweeps on access: a [`cache_get`](crate::Cached::cache_get) /
    ///   `cache_get_mut` (and the `cache_get_or_set*` factory paths) that finds an expired
    ///   entry removes or replaces it and fires the callback.
    /// - Overwriting an already-expired entry via [`cache_set`](crate::Cached::cache_set) /
    ///   [`cache_try_set`](crate::Cached::cache_try_set): the displaced value is filtered from
    ///   the return (`None`), so it fires the callback and counts an eviction.
    /// - Explicit [`cache_remove`](crate::Cached::cache_remove) /
    ///   [`cache_remove_entry`](crate::Cached::cache_remove_entry), even when the removed
    ///   entry was already expired.
    ///
    /// Calling this method changes the builder's type to
    /// `LruTtlCacheBuilder<K, V, `[`HasEvict`]`>`, which requires `K: 'static`
    /// and `V: 'static` at [`build`](LruTtlCacheBuilder::build) time so the
    /// callback can be wired into the inner LRU eviction path.
    ///
    /// Does **not** fire on [`cache_clear`](crate::Cached::cache_clear).
    /// Use [`cache_clear_with_on_evict`](LruTtlCache::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(
        self,
        on_evict: impl Fn(&K, &V) + Send + Sync + 'static,
    ) -> LruTtlCacheBuilder<K, V, HasEvict, S> {
        LruTtlCacheBuilder {
            size: self.size,
            ttl: self.ttl,
            refresh: self.refresh,
            on_evict: Some(Arc::new(on_evict)),
            hasher: self.hasher,
            _evict: PhantomData,
        }
    }
}

// build without an eviction callback -- no 'static required
impl<K, V, S: BuildHasher> LruTtlCacheBuilder<K, V, NoEvict, S> {
    /// Build the cache.
    ///
    /// # Errors
    ///
    /// Returns [`BuildError`](super::BuildError) if `max_size` or `ttl` was not set, if `ttl` is zero, or if `max_size` is `0`.
    pub fn build(self) -> Result<LruTtlCache<K, V, S>, super::BuildError>
    where
        K: Hash + Eq + Clone,
    {
        let size = self
            .size
            .ok_or(super::BuildError::MissingRequired("max_size"))?;
        let ttl = self.ttl.ok_or(super::BuildError::MissingRequired("ttl"))?;
        super::validate_ttl(ttl)?;
        LruTtlCache::new_internal(size, ttl, self.refresh, self.hasher)
    }
}

// build with an eviction callback -- 'static required for sync_on_evict
impl<K, V, S: BuildHasher> LruTtlCacheBuilder<K, V, HasEvict, S> {
    /// Build the cache.
    ///
    /// # Errors
    ///
    /// Returns [`BuildError`](super::BuildError) if `max_size` or `ttl` was not set, if `ttl` is zero, or if `max_size` is `0`.
    pub fn build(self) -> Result<LruTtlCache<K, V, S>, super::BuildError>
    where
        K: Hash + Eq + Clone + 'static,
        V: 'static,
    {
        let size = self
            .size
            .ok_or(super::BuildError::MissingRequired("max_size"))?;
        let ttl = self.ttl.ok_or(super::BuildError::MissingRequired("ttl"))?;
        super::validate_ttl(ttl)?;
        let mut cache = LruTtlCache::new_internal(size, ttl, self.refresh, self.hasher)?;
        cache.on_evict = self.on_evict;
        cache.sync_on_evict();
        Ok(cache)
    }
}

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

    /// Return a builder for constructing a [`LruTtlCache`].
    #[must_use]
    pub fn builder() -> LruTtlCacheBuilder<K, V> {
        LruTtlCacheBuilder {
            size: None,
            ttl: None,
            refresh: false,
            on_evict: None,
            hasher: super::new_default_hash_builder(),
            _evict: PhantomData,
        }
    }
}

impl<K: Hash + Eq + Clone, V, S: BuildHasher> LruTtlCache<K, V, S> {
    pub(super) fn sync_on_evict(&mut self)
    where
        K: 'static,
        V: 'static,
    {
        if self.on_evict.is_some() {
            let on_evict_ext = self.on_evict.clone();
            self.store.on_evict = Some(Arc::new(move |k, entry| {
                if let Some(on_evict) = &on_evict_ext {
                    on_evict(k, &entry.value);
                }
            }));
        }
    }

    /// `true` if the entry is still live.
    /// `expires_at = None` means the entry never expires (TTL was disabled at insert time).
    #[inline]
    pub(super) fn entry_live(expires_at: Option<Instant>) -> bool {
        expires_at.is_none_or(|t| Instant::now() < t)
    }

    /// Same as [`entry_live`](Self::entry_live) but takes an already-sampled `now`
    /// instead of reading the clock. Lets hot paths that already have `now` in hand
    /// (e.g. a caller that just computed a fresh expiry, or a sweep that snapshotted
    /// the clock once for the whole pass) avoid a redundant clock read.
    ///
    /// The boundary convention is identical: an entry is live only while
    /// `now < expires_at`, so `now == expires_at` is already expired.
    #[inline]
    pub(super) fn entry_live_at(expires_at: Option<Instant>, now: Instant) -> bool {
        expires_at.is_none_or(|t| now < t)
    }

    /// Insert `entry` for `key`, returning the previous value only if it was still live.
    ///
    /// A displaced expired value is filtered from the return (matching the get paths), so it is
    /// dropped silently from the caller's view; in that case fire `on_evict` and count an
    /// eviction. The inner `LruCache::cache_set` does not fire `on_evict` on an overwrite, so the
    /// callback fires exactly once here. The key is cloned only when a callback is configured.
    ///
    /// `now` is the caller's already-sampled clock reading (the same one that produced
    /// `entry.expires_at`), used to decide whether the displaced entry was still live --
    /// avoids a second `Instant::now()` call here.
    fn set_entry(&mut self, key: K, entry: TimedEntry<V>, now: Instant) -> Option<V> {
        match self.store.cache_set_returning_entry(key, entry) {
            Some((_, old)) if Self::entry_live_at(old.expires_at, now) => Some(old.value),
            Some((stored_key, old)) => {
                // 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.value);
                }
                None
            }
            None => None,
        }
    }

    /// Compute the expiry instant for a new or refreshed entry given the current TTL.
    /// Returns `None` when `ttl` is zero (expiry disabled), or `Some(now + ttl)`.
    /// On overflow (`now + ttl` exceeds `Instant`'s representable range, a TTL on the
    /// order of hundreds of years) returns `None`: the entry never expires, matching
    /// the sharded TTL stores.
    #[inline]
    pub(super) fn compute_expires_at(ttl: Duration, now: Instant) -> Option<Instant> {
        if ttl.is_zero() {
            None
        } else {
            now.checked_add(ttl)
        }
    }

    fn new_internal(
        size: usize,
        ttl: Duration,
        refresh: bool,
        hasher: S,
    ) -> Result<Self, super::BuildError> {
        let mut store = LruCache::builder().max_size(size).hasher(hasher).build()?;
        store.disable_hit_miss_tracking();
        Ok(LruTtlCache {
            store,
            size,
            ttl,
            hits: AtomicU64::new(0),
            misses: AtomicU64::new(0),
            evictions: AtomicU64::new(0),
            refresh,
            on_evict: None,
        })
    }

    /// Return all live entries in the current order from most to least recently
    /// used, as `(K, `[`CacheValue`](super::CacheValue)`)` pairs. The wrapper
    /// `Deref`s to `V` and exposes the entry's expiry via
    /// [`expires_at`](super::CacheValue::expires_at).
    /// Items past their expiry will be excluded.
    #[must_use]
    pub fn iter_order(&self) -> Vec<(K, super::CacheValue<V, Option<Instant>>)>
    where
        K: Clone,
        V: Clone,
    {
        // One clock reading for the whole eager pass (as in `evict`), so liveness is
        // judged against a single consistent instant instead of a per-entry read.
        let now = Instant::now();
        // `LRUListIterator` has no `size_hint`, so `collect` would grow the Vec from
        // zero; the stored entry count is a known upper bound on the live entries.
        let mut out = Vec::with_capacity(self.store.cache_size());
        out.extend(self.store.order.iter().filter_map(|(k, entry)| {
            let expires_at = entry.expires_at;
            if Self::entry_live_at(expires_at, now) {
                Some((
                    k.clone(),
                    super::CacheValue::new(entry.value.clone(), expires_at),
                ))
            } else {
                None
            }
        }));
        out
    }

    /// Return a `Vec` of keys in the current order from most
    /// to least recently used.
    /// Items past their expiry will be excluded.
    #[must_use]
    pub fn key_order(&self) -> Vec<K>
    where
        K: Clone,
    {
        // Single clock reading + pre-sized output, as in `iter_order`.
        let now = Instant::now();
        let mut out = Vec::with_capacity(self.store.cache_size());
        out.extend(self.store.order.iter().filter_map(|(k, entry)| {
            if Self::entry_live_at(entry.expires_at, now) {
                Some(k.clone())
            } else {
                None
            }
        }));
        out
    }

    /// Return a `Vec` of [`CacheValue`](super::CacheValue)-wrapped values (each
    /// carrying its expiry) in the current order from most to least recently used.
    /// Items past their expiry will be excluded.
    #[must_use]
    pub fn value_order(&self) -> Vec<super::CacheValue<V, Option<Instant>>>
    where
        V: Clone,
    {
        // Single clock reading + pre-sized output, as in `iter_order`.
        let now = Instant::now();
        let mut out = Vec::with_capacity(self.store.cache_size());
        out.extend(self.store.order.iter().filter_map(|(_k, entry)| {
            let expires_at = entry.expires_at;
            if Self::entry_live_at(expires_at, now) {
                Some(super::CacheValue::new(entry.value.clone(), expires_at))
            } else {
                None
            }
        }));
        out
    }

    /// Returns the maximum number of entries this cache will hold before evicting.
    ///
    /// This is the bound set via [`LruTtlCacheBuilder::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.size
    }

    /// 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`](LruTtlCache::try_set_max_size)
    /// to validate first and avoid the panic.
    ///
    /// # See also
    ///
    /// [`LruCache::set_max_size`](super::LruCache::set_max_size) and
    /// [`TtlSortedCache::set_max_size`](super::TtlSortedCache::set_max_size) are
    /// parallel methods on the other LRU-family stores. All stores also provide a
    /// fallible `try_set_max_size` counterpart.
    pub fn set_max_size(&mut self, max_size: usize) -> Option<usize> {
        assert!(max_size > 0, "max_size must be greater than zero");
        let prev = self.store.set_max_size(max_size);
        self.size = self.store.capacity;
        prev
    }

    /// Fallible counterpart of [`set_max_size`](LruTtlCache::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> {
        if max_size == 0 {
            return Err(super::SetMaxSizeError::ZeroMaxSize);
        }
        Ok(self.set_max_size(max_size))
    }

    /// Evict expired values from the cache.
    #[must_use]
    pub fn evict(&mut self) -> usize {
        let on_evict = &self.on_evict;
        let evictions = &self.evictions;
        let now = Instant::now();
        self.store.retain_silent(|key, entry| {
            // None means never-expires; Some(t) expires when now >= t.
            if Self::entry_live_at(entry.expires_at, now) {
                true
            } else {
                // Count BEFORE notifying: a panicking callback must never leave
                // an entry removed-but-uncounted.
                evictions.fetch_add(1, Ordering::Relaxed);
                if let Some(on_evict) = on_evict {
                    on_evict(key, &entry.value);
                }
                false
            }
        })
    }

    /// 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 TTL-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 [`ExpiringLruCache::retain`](crate::ExpiringLruCache::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 {
        let on_evict = &self.on_evict;
        let evictions = &self.evictions;
        // One clock reading for the whole pass (as in `evict`): every entry is judged
        // against the same instant instead of re-reading the clock per entry.
        let now = Instant::now();
        self.store.retain_silent(|key, entry| {
            let expired = !Self::entry_live_at(entry.expires_at, now);
            if expired || !keep(key, &entry.value) {
                // Count BEFORE notifying: a panicking callback must never leave
                // an entry removed-but-uncounted.
                evictions.fetch_add(1, Ordering::Relaxed);
                if let Some(on_evict) = on_evict {
                    on_evict(key, &entry.value);
                }
                false
            } else {
                true
            }
        })
    }

    /// 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`. If no `on_evict` callback was configured, it falls back to
    /// the plain `cache_clear`.
    pub fn cache_clear_with_on_evict(&mut self) {
        if self.on_evict.is_none() {
            return self.cache_clear();
        }
        // `drain_all` walks the LRU chain once taking owned pairs (MRU -> LRU, the same
        // order the old `key_order` + per-key `pop_raw` drain fired in) -- no key clones
        // and 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, entry) in &removed {
                on_evict(k, &entry.value);
            }
        }
    }
}

impl<K: Hash + Eq + Clone, V, S: BuildHasher> Cached<K, V> for LruTtlCache<K, V, S> {
    type Error = std::convert::Infallible;

    fn cache_get<Q>(&mut self, key: &Q) -> Option<&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) {
            // Sample the clock ONCE for this hit and reuse it for both the liveness
            // check and the `refresh_on_hit` expiry. Sampled after the probe so an
            // absent-key miss reads the clock not at all.
            let now = Instant::now();
            let entry = &self.store.order.get(index).1;
            if Self::entry_live_at(entry.expires_at, now) {
                self.store.order.move_to_front(index);
                self.hits.fetch_add(1, Ordering::Relaxed);
                if self.refresh {
                    let new_exp = Self::compute_expires_at(self.ttl, now).or(self
                        .store
                        .order
                        .get(index)
                        .1
                        .expires_at);
                    self.store.order.get_mut(index).1.expires_at = new_exp;
                }
                Some(&self.store.order.get(index).1.value)
            } else {
                self.misses.fetch_add(1, Ordering::Relaxed);
                // The key's hash is already in hand from the probe above; the lazy
                // sweep must not recompute it (this is the steady-state path -- every
                // entry takes it exactly once).
                if let Some((k, entry)) = 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, &entry.value);
                    }
                }
                None
            }
        } else {
            self.misses.fetch_add(1, Ordering::Relaxed);
            None
        }
    }

    fn cache_get_mut<Q>(&mut self, key: &Q) -> std::option::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) {
            // One clock reading per hit, reused by the refresh below (as in `cache_get`).
            let now = Instant::now();
            let entry = &self.store.order.get(index).1;
            if Self::entry_live_at(entry.expires_at, now) {
                self.store.order.move_to_front(index);
                self.hits.fetch_add(1, Ordering::Relaxed);
                if self.refresh {
                    let new_exp = Self::compute_expires_at(self.ttl, now).or(self
                        .store
                        .order
                        .get(index)
                        .1
                        .expires_at);
                    self.store.order.get_mut(index).1.expires_at = new_exp;
                }
                Some(&mut self.store.order.get_mut(index).1.value)
            } else {
                self.misses.fetch_add(1, Ordering::Relaxed);
                // Reuse the probe's hash for the lazy sweep (as in `cache_get`).
                if let Some((k, entry)) = 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, &entry.value);
                    }
                }
                None
            }
        } else {
            self.misses.fetch_add(1, Ordering::Relaxed);
            None
        }
    }

    fn cache_get_or_set_with_mut<F: FnOnce() -> V>(&mut self, key: K, f: F) -> &mut V {
        let ttl = self.ttl;
        let setter = || {
            // Anchor the expiry AFTER the factory runs so a slow factory does
            // not eat into the fresh entry's TTL (CORE-3). This clock read is
            // deliberately NOT shared with `hit_at` below: `f()` may run arbitrarily
            // long, so the fresh expiry must be anchored once it returns.
            let value = f();
            let now = Instant::now();
            let expires_at = Self::compute_expires_at(ttl, now);
            TimedEntry { expires_at, value }
        };
        // The store calls the validity closure only when the key is present, so sample
        // the clock there and reuse the reading for the refresh below: one read per hit,
        // and the insert path (which anchors its own expiry after the factory) pays none.
        let mut hit_at: Option<Instant> = None;
        // On replacement the store returns the STORED key/entry of the displaced value, 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_entry, entry) =
            self.store.get_or_set_with_if(key, setter, |entry| {
                Self::entry_live_at(entry.expires_at, *hit_at.insert(Instant::now()))
            });
        if was_present && was_valid {
            if self.refresh {
                let now = hit_at.unwrap_or_else(Instant::now);
                let new_exp = Self::compute_expires_at(self.ttl, now).or(entry.expires_at);
                entry.expires_at = new_exp;
            }
            self.hits.fetch_add(1, Ordering::Relaxed);
        } else {
            if let Some((old_key, old)) = old_entry {
                // 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.value);
                }
            }
            self.misses.fetch_add(1, Ordering::Relaxed);
        }
        &mut entry.value
    }

    fn cache_try_get_or_set_with_mut<F: FnOnce() -> Result<V, E>, E>(
        &mut self,
        key: K,
        f: F,
    ) -> Result<&mut V, E> {
        let ttl = self.ttl;
        // Count the miss the instant the setter runs. The inner store calls the setter only
        // when the lookup found no live entry (absent key or expired entry), so a hit never
        // counts one; and because the increment lands before `f` returns, an `Err` factory
        // still records the miss instead of losing it on the `?` early return below. This
        // matches `TtlCache` and `ExpiringLruCache`'s try-path accounting (EXP-2).
        let misses = &self.misses;
        let setter = move || {
            misses.fetch_add(1, Ordering::Relaxed);
            // Anchor the expiry after the factory succeeds (CORE-3); deliberately a
            // fresh clock read, not the `hit_at` sample taken before `f()` ran.
            let value = f()?;
            let now = Instant::now();
            let expires_at = Self::compute_expires_at(ttl, now);
            Ok(TimedEntry { expires_at, value })
        };
        // One clock read per hit, shared by the liveness check and the refresh below.
        let mut hit_at: Option<Instant> = None;
        // On replacement the store returns the STORED key/entry of the displaced value (C1/C8).
        let (was_present, was_valid, old_entry, entry) =
            self.store.try_get_or_set_with_if(key, setter, |entry| {
                Self::entry_live_at(entry.expires_at, *hit_at.insert(Instant::now()))
            })?;
        if was_present && was_valid {
            if self.refresh {
                let now = hit_at.unwrap_or_else(Instant::now);
                let new_exp = Self::compute_expires_at(self.ttl, now).or(entry.expires_at);
                entry.expires_at = new_exp;
            }
            self.hits.fetch_add(1, Ordering::Relaxed);
        } else if let Some((old_key, old)) = old_entry {
            // The miss was already counted by `setter`. On `Err` the expired entry is left
            // in place, so `on_evict` / `evictions` deliberately stay behind until a call
            // actually displaces it -- firing early would double-fire for one physical entry.
            // 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.value);
            }
        }
        Ok(&mut entry.value)
    }

    /// Insert a key-value pair. Returns the previous value only if it had not yet expired.
    /// An expired previous value is filtered from the return; it fires `on_evict` and counts as
    /// an eviction, matching the other removal paths.
    ///
    /// Overwriting an existing key promotes it to most-recently-used: a write counts as an
    /// access, so the entry moves to the front of the eviction order exactly as a fresh
    /// insertion would (its expiry is also reset from the current TTL). Use
    /// [`CachedPeek::cache_peek`](crate::CachedPeek::cache_peek) if you need to inspect an
    /// entry without touching recency.
    fn cache_set(&mut self, key: K, val: V) -> Option<V> {
        let now = Instant::now();
        let expires_at = Self::compute_expires_at(self.ttl, now);
        // `now` is threaded through: `set_entry` judges the displaced entry's liveness
        // against this same reading instead of sampling the clock a second time.
        self.set_entry(
            key,
            TimedEntry {
                expires_at,
                value: val,
            },
            now,
        )
    }

    fn cache_remove<Q>(&mut self, k: &Q) -> Option<V>
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + ?Sized,
    {
        if let Some((stored_k, entry)) = 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, &entry.value);
            }
            if Self::entry_live(entry.expires_at) {
                Some(entry.value)
            } else {
                None
            }
        } else {
            None
        }
    }

    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, entry)) = 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, &entry.value);
            }
            Some((stored_k, entry.value))
        } 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_reset_metrics(&mut self) {
        self.misses.store(0, Ordering::Relaxed);
        self.hits.store(0, Ordering::Relaxed);
        self.evictions.store(0, Ordering::Relaxed);
        self.store.cache_reset_metrics();
    }
    fn cache_size(&self) -> usize {
        self.store.cache_size()
    }
    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> {
        // Combined evictions from underlying store and our time-based removals
        Some(self.evictions.load(Ordering::Relaxed) + self.store.cache_evictions().unwrap_or(0))
    }
    fn cache_capacity(&self) -> Option<usize> {
        Some(self.size)
    }

    /// 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 or TTL refresh, 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, S: BuildHasher> CachedIter<K, V> for LruTtlCache<K, V, S> {
    fn iter<'a>(&'a self) -> impl Iterator<Item = (&'a K, &'a V)> + 'a
    where
        K: 'a,
        V: 'a,
    {
        // Deliberately per-item `entry_live` (a fresh clock read each step) rather than
        // a snapshot taken when the iterator is built: this iterator is lazy and may be
        // held across arbitrary time, so a construction-time `now` would be observable
        // -- entries that expired mid-iteration would still be yielded. The eager
        // collectors (`iter_order`/`key_order`/`value_order`) hoist their reading
        // because they complete in one pass.
        CachedIter::iter(&self.store).filter_map(move |(k, entry)| {
            if Self::entry_live(entry.expires_at) {
                Some((k, &entry.value))
            } else {
                None
            }
        })
    }
}

impl<K: Hash + Eq + Clone, V, S: BuildHasher> CachedPeek<K, V> for LruTtlCache<K, V, S> {
    fn cache_peek<Q>(&self, k: &Q) -> Option<&V>
    where
        K: std::borrow::Borrow<Q>,
        Q: std::hash::Hash + Eq + ?Sized,
    {
        if let Some(entry) = self.store.cache_peek(k)
            && Self::entry_live(entry.expires_at)
        {
            return Some(&entry.value);
        }
        None
    }
}

impl<K: Hash + Eq + Clone, V, S: BuildHasher> crate::CacheTtl for LruTtlCache<K, V, S> {
    fn ttl(&self) -> Option<Duration> {
        // A zero TTL means expiry is disabled.
        if self.ttl.is_zero() {
            None
        } else {
            Some(self.ttl)
        }
    }
    /// A zero `ttl` disables expiry — exactly equivalent to `unset_ttl`.
    /// Returns the previous TTL, or `None` if expiry was already disabled.
    fn set_ttl(&mut self, ttl: Duration) -> Option<Duration> {
        let old = self.ttl;
        self.ttl = ttl;
        if old.is_zero() { None } else { Some(old) }
    }
    fn unset_ttl(&mut self) -> Option<Duration> {
        let old = self.ttl;
        self.ttl = Duration::ZERO;
        if old.is_zero() { None } else { Some(old) }
    }
    fn refresh_on_hit(&self) -> bool {
        self.refresh
    }
    fn set_refresh_on_hit(&mut self, refresh: bool) -> bool {
        let old = self.refresh;
        self.refresh = refresh;
        old
    }
}

impl<K: Hash + Eq + Clone, V: Clone, S: BuildHasher + Clone> CloneCached<K, V>
    for LruTtlCache<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) {
            // One clock reading per hit, reused by the refresh below (as in `cache_get`).
            let now = Instant::now();
            let entry = &self.store.order.get(index).1;
            let expired = !Self::entry_live_at(entry.expires_at, now);
            if expired {
                self.misses.fetch_add(1, Ordering::Relaxed);
                (Some(self.store.order.get(index).1.value.clone()), true)
            } else {
                self.store.order.move_to_front(index);
                self.hits.fetch_add(1, Ordering::Relaxed);
                if self.refresh {
                    let new_exp = Self::compute_expires_at(self.ttl, now).or(self
                        .store
                        .order
                        .get(index)
                        .1
                        .expires_at);
                    self.store.order.get_mut(index).1.expires_at = new_exp;
                }
                (Some(self.store.order.get(index).1.value.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, does not promote in LRU order, and does not renew the TTL.
    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(entry) = self.store.cache_peek(k) {
            let expired = !Self::entry_live(entry.expires_at);
            (Some(entry.value.clone()), expired)
        } else {
            (None, false)
        }
    }
}

#[cfg(feature = "async_core")]
#[cfg_attr(docsrs, doc(cfg(feature = "async_core")))]
impl<K, V, S> CachedGetOrSetAsync<K, V> for LruTtlCache<K, V, S>
where
    K: Hash + Eq + Clone + Send,
    S: BuildHasher + Send,
{
    fn async_cache_get_or_set_with_mut<'a, F, Fut>(
        &'a mut self,
        key: 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 {
            let ttl = self.ttl;
            let setter = || async move {
                // Anchor the expiry after the factory resolves (CORE-3); deliberately a
                // fresh clock read, not the `hit_at` sample taken before it ran.
                let value = f().await;
                let now = Instant::now();
                let expires_at = Self::compute_expires_at(ttl, now);
                TimedEntry { expires_at, value }
            };
            // One clock read per hit, shared by the liveness check and the refresh below.
            let mut hit_at: Option<Instant> = None;
            // On replacement the store returns the STORED key/entry of the displaced value (C1/C8).
            let (was_present, was_valid, old_entry, entry) = self
                .store
                .get_or_set_with_if_async(key, setter, |entry| {
                    Self::entry_live_at(entry.expires_at, *hit_at.insert(Instant::now()))
                })
                .await;
            if was_present && was_valid {
                if self.refresh {
                    let now = hit_at.unwrap_or_else(Instant::now);
                    let new_exp = Self::compute_expires_at(self.ttl, now).or(entry.expires_at);
                    entry.expires_at = new_exp;
                }
                self.hits.fetch_add(1, Ordering::Relaxed);
            } else {
                if let Some((old_key, old)) = old_entry {
                    // 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.value);
                    }
                }
                self.misses.fetch_add(1, Ordering::Relaxed);
            }
            &mut entry.value
        }
    }

    fn async_cache_try_get_or_set_with_mut<'a, F, Fut, E>(
        &'a mut self,
        key: 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 {
            let ttl = self.ttl;
            // Count the miss before awaiting the factory, so an `Err` still records it
            // instead of losing it on the `?` early return below (EXP-2); see the sync
            // `cache_try_get_or_set_with_mut` for the full rationale.
            let misses = &self.misses;
            let setter = move || async move {
                misses.fetch_add(1, Ordering::Relaxed);
                // Fresh clock read anchored after the factory resolves (CORE-3).
                let new_val = f().await?;
                let now = Instant::now();
                let expires_at = Self::compute_expires_at(ttl, now);
                Ok(TimedEntry {
                    expires_at,
                    value: new_val,
                })
            };
            // One clock read per hit, shared by the liveness check and the refresh below.
            let mut hit_at: Option<Instant> = None;
            // On replacement the store returns the STORED key/entry of the displaced value (C1/C8).
            let (was_present, was_valid, old_entry, entry) = self
                .store
                .try_get_or_set_with_if_async(key, setter, |entry| {
                    Self::entry_live_at(entry.expires_at, *hit_at.insert(Instant::now()))
                })
                .await?;
            if was_present && was_valid {
                if self.refresh {
                    let now = hit_at.unwrap_or_else(Instant::now);
                    let new_exp = Self::compute_expires_at(self.ttl, now).or(entry.expires_at);
                    entry.expires_at = new_exp;
                }
                self.hits.fetch_add(1, Ordering::Relaxed);
            } else if let Some((old_key, old)) = old_entry {
                // The miss was already counted by `setter`; on `Err` the expired entry is
                // still stored, so the eviction side deliberately waits for the call that
                // actually displaces it. 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.value);
                }
            }
            Ok(&mut entry.value)
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Cached, CachedExt};
    use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};

    #[test]
    fn iter_order_and_value_order_expose_expiry_via_cache_value() {
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        let before = Instant::now();
        c.cache_set(1, 10);
        c.cache_set(2, 20);

        // MRU-first order; the wrapper Derefs to V and compares against bare values.
        let ordered = c.iter_order();
        assert_eq!(ordered.len(), 2);
        assert_eq!(ordered[0].0, 2);
        assert_eq!(*ordered[0].1, 20);
        assert_eq!(ordered[1].1, 10);
        // Finite ttl: every entry carries a future expiry.
        for (_k, v) in &ordered {
            let exp = v.expires_at().expect("finite ttl entries carry an expiry");
            assert!(exp > before);
        }

        let vals = c.value_order();
        assert_eq!(vals, vec![20, 10]);
        assert!(vals[0].expires_at().is_some());
        assert_eq!(vals[0].value(), &20);
        assert_eq!(vals.into_iter().map(|v| v.into_value()).sum::<u32>(), 30);
    }

    #[test]
    fn cache_set_over_expired_returns_none_fires_on_evict_and_counts() {
        use std::sync::Arc;
        let fired = Arc::new(AtomicUsize::new(0));
        let fired2 = fired.clone();
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_millis(20))
            .on_evict(move |_k: &u32, _v: &u32| {
                fired2.fetch_add(1, AtomicOrdering::Relaxed);
            })
            .build()
            .unwrap();
        c.cache_set(1, 100);
        let before = c.cache_evictions().unwrap();
        std::thread::sleep(std::time::Duration::from_millis(60));
        // The previous value has expired: overwriting filters it (None), fires on_evict once,
        // and counts one eviction.
        assert_eq!(c.cache_set(1, 200), None);
        assert_eq!(c.cache_evictions(), Some(before + 1));
        assert_eq!(fired.load(AtomicOrdering::Relaxed), 1);
        // Overwriting the now-live value returns it, no on_evict and no new eviction.
        assert_eq!(c.cache_set(1, 300), Some(200));
        assert_eq!(c.cache_evictions(), Some(before + 1));
        assert_eq!(fired.load(AtomicOrdering::Relaxed), 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: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_millis(20))
            .build()
            .unwrap();
        c.cache_set(1, 100);
        let before = c.cache_evictions().unwrap();
        std::thread::sleep(std::time::Duration::from_millis(60));
        // Expired entry: overwrite filters it from the return and counts one eviction.
        assert_eq!(c.cache_set(1, 200), None);
        assert_eq!(
            c.cache_evictions(),
            Some(before + 1),
            "evictions must increment by 1 on expired-entry overwrite even without on_evict"
        );
        // Overwriting the now-live value must not count as an eviction.
        assert_eq!(c.cache_set(1, 300), Some(200));
        assert_eq!(
            c.cache_evictions(),
            Some(before + 1),
            "overwriting a live entry must not increment evictions"
        );
    }

    #[test]
    fn cache_set_with_ttl_overflow_stores_never_expiring_entry() {
        // A TTL that would overflow Instant bounds (compute_expires_at's
        // now.checked_add(ttl) -> None) stores the entry with no expiry: it never
        // expires, matching TtlSortedCache's set_with(..).ttl(..) overflow behavior.
        use crate::CacheTtl;
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        c.set_ttl(Duration::MAX);
        assert_eq!(c.cache_set(1, 42), None);
        assert_eq!(c.cache_get(&1), Some(&42));
        // Never-expiring: CacheValue's expires_at() metadata must be None.
        let ordered = c.iter_order();
        assert_eq!(ordered.len(), 1);
        assert_eq!(*ordered[0].1, 42);
        assert_eq!(ordered[0].1.expires_at(), None);
    }

    #[test]
    fn cache_set_over_existing_key_promotes_to_mru() {
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(3)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        c.cache_set(3, 30);
        assert_eq!(c.key_order(), vec![3, 2, 1]);
        // Overwriting the least-recently-used key returns the old (still-live) value
        // and promotes the entry to most-recently-used.
        assert_eq!(c.cache_set(1, 11), Some(10));
        assert_eq!(c.key_order(), vec![1, 3, 2]);
        assert_eq!(c.cache_get(&1), Some(&11));
    }

    #[test]
    fn cache_set_promotion_changes_the_capacity_eviction_victim() {
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(3)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        c.cache_set(3, 30);
        // 1 was the LRU victim; overwriting it makes 2 the victim instead.
        assert_eq!(c.cache_set(1, 11), Some(10));
        c.cache_set(4, 40);
        assert_eq!(c.key_order(), vec![4, 1, 3]);
        assert_eq!(c.cache_get(&2), None, "2 became the LRU victim");
        assert_eq!(c.cache_get(&1), Some(&11));
    }

    #[test]
    fn cache_set_over_current_mru_and_sole_entry_keep_the_list_intact() {
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(3)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        c.cache_set(3, 30);
        // Overwriting the head must not corrupt the chain.
        assert_eq!(c.cache_set(3, 33), Some(30));
        assert_eq!(c.key_order(), vec![3, 2, 1]);
        assert_eq!(c.value_order(), vec![33, 20, 10]);
        assert_eq!(c.cache_size(), 3);

        // Sole entry of a 1-capacity cache.
        let mut d: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(1)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        d.cache_set(1, 10);
        assert_eq!(d.cache_set(1, 11), Some(10));
        assert_eq!(d.key_order(), vec![1]);
        assert_eq!(d.cache_size(), 1);
    }

    #[test]
    fn cache_peek_still_does_not_promote_after_set_does() {
        use crate::CachedPeek;
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(3)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        c.cache_set(3, 30);
        assert_eq!(c.cache_peek(&1), Some(&10));
        assert_eq!(c.key_order(), vec![3, 2, 1], "peek must not promote");
        assert_eq!(c.cache_set(1, 11), Some(10));
        assert_eq!(c.key_order(), vec![1, 3, 2]);
    }

    #[test]
    fn new_returns_ready_cache_respecting_max_size_and_ttl() {
        use crate::CacheTtl;
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::new(2, Duration::from_millis(50));
        assert_eq!(c.capacity(), 2);
        assert_eq!(CacheTtl::ttl(&c), Some(Duration::from_millis(50)));
        assert_eq!(c.cache_set(1, 10), None);
        assert_eq!(c.cache_get(&1), Some(&10));
        // max_size respected.
        c.cache_set(2, 20);
        c.cache_set(3, 30); // evicts LRU (1)
        assert_eq!(c.cache_size(), 2);
        assert_eq!(c.cache_get(&1), None);
        // ttl respected.
        std::thread::sleep(std::time::Duration::from_millis(100));
        assert_eq!(c.cache_get(&2), None, "entry must expire after ttl");
    }

    #[test]
    #[should_panic(expected = "non-zero max_size with a valid allocation and a non-zero ttl")]
    fn new_zero_max_size_panics() {
        let _c: LruTtlCache<u32, u32> = LruTtlCache::new(0, Duration::from_secs(1));
    }

    #[test]
    #[should_panic(expected = "non-zero max_size with a valid allocation and a non-zero ttl")]
    fn new_zero_ttl_panics() {
        let _c: LruTtlCache<u32, u32> = LruTtlCache::new(2, Duration::ZERO);
    }

    #[test]
    fn ttl_secs_and_ttl_millis_set_duration() {
        use crate::CacheTtl;
        let c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl_secs(7)
            .build()
            .unwrap();
        assert_eq!(CacheTtl::ttl(&c), Some(Duration::from_secs(7)));

        let c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl_millis(250)
            .build()
            .unwrap();
        assert_eq!(CacheTtl::ttl(&c), Some(Duration::from_millis(250)));
    }

    #[test]
    fn ttl_setters_override_last_writer_wins() {
        use crate::CacheTtl;
        let c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(10))
            .ttl_secs(5)
            .build()
            .unwrap();
        assert_eq!(CacheTtl::ttl(&c), Some(Duration::from_secs(5)));

        let c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl_secs(10)
            .ttl_millis(500)
            .build()
            .unwrap();
        assert_eq!(CacheTtl::ttl(&c), Some(Duration::from_millis(500)));
    }

    #[test]
    fn status_does_not_inflate_inner_store_hits() {
        let mut cache = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        cache.cache_set(1, 10);
        cache.cache_set(2, 20);
        cache.store.cache_reset_metrics();

        // cache_get calls status() internally
        assert_eq!(cache.cache_get(&1), Some(&10));
        assert_eq!(
            cache.store.cache_hits(),
            Some(0),
            "inner LruCache must not record hits from status() promotion"
        );
        assert_eq!(
            cache.store.cache_misses(),
            Some(0),
            "inner LruCache must not record misses from status() promotion"
        );
    }

    #[test]
    fn capacity_returns_bound_not_live_size() {
        let mut cache = LruTtlCache::builder()
            .max_size(3)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        assert_eq!(cache.capacity(), 3);
        assert_eq!(cache.cache_size(), 0);

        cache.cache_set(1, 10);
        cache.cache_set(2, 20);
        assert_eq!(cache.capacity(), 3);
        assert_eq!(cache.cache_size(), 2);

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

    #[test]
    fn reset_rebuilds_store_and_preserves_on_evict() {
        let evicted = Arc::new(AtomicUsize::new(0));
        let evicted_for_callback = evicted.clone();
        let mut cache = LruTtlCache::builder()
            .max_size(1)
            .ttl(Duration::from_secs(60))
            .on_evict(move |_key: &u8, _value: &u8| {
                evicted_for_callback.fetch_add(1, AtomicOrdering::Relaxed);
            })
            .build()
            .unwrap();

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

        cache.set(2, 20);
        cache.set(3, 30);
        assert_eq!(evicted.load(AtomicOrdering::Relaxed), 1);
    }

    #[test]
    fn try_new() {
        let c = LruTtlCache::<i32, i32>::builder()
            .max_size(0)
            .ttl(Duration::from_secs(1))
            .build();
        assert!(matches!(
            c.unwrap_err(),
            super::super::BuildError::InvalidValue {
                field: "max_size",
                ..
            }
        ));

        let c = LruTtlCache::<i32, i32>::builder()
            .max_size(usize::MAX)
            .ttl(Duration::from_secs(1))
            .build();
        assert!(matches!(
            c.unwrap_err(),
            super::super::BuildError::InvalidValue {
                field: "max_size",
                ..
            }
        ));
    }

    #[test]
    fn cache_clear_with_on_evict_fires_for_all_entries() {
        let count = Arc::new(AtomicUsize::new(0));
        let count2 = count.clone();
        let mut c = LruTtlCache::builder()
            .max_size(5)
            .ttl(Duration::from_secs(60))
            .on_evict(move |_k: &u32, _v: &u32| {
                count2.fetch_add(1, AtomicOrdering::Relaxed);
            })
            .build()
            .unwrap();
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        c.cache_set(3, 30);
        c.cache_clear_with_on_evict();
        assert_eq!(c.cache_size(), 0);
        assert_eq!(count.load(AtomicOrdering::Relaxed), 3);
        assert_eq!(c.evictions.load(AtomicOrdering::Relaxed), 3);
    }

    #[test]
    fn cache_clear_does_not_fire_on_evict() {
        let fired = Arc::new(AtomicUsize::new(0));
        let fired2 = fired.clone();
        let mut c = LruTtlCache::builder()
            .max_size(5)
            .ttl(Duration::from_secs(60))
            .on_evict(move |_k: &u32, _v: &u32| {
                fired2.fetch_add(1, AtomicOrdering::Relaxed);
            })
            .build()
            .unwrap();
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        c.cache_clear();
        assert_eq!(c.cache_size(), 0);
        assert_eq!(
            fired.load(AtomicOrdering::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 = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(60))
            .on_evict(move |_k, _v| {
                evict_count2.fetch_add(1, Ordering::Relaxed);
            })
            .build()
            .unwrap();
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        c.cache_set(3, 30);
        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: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(2)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        // Drive an inner-store capacity eviction so the inner evictions counter is non-zero
        // before the reset. A half-reset that only touched the outer counter would leave this.
        c.cache_set(3, 30); // evicts LRU (1) in the inner LruCache
        assert!(
            c.store.cache_evictions().unwrap() >= 1,
            "precondition: inner store must record a capacity eviction before reset"
        );
        // Drive hits and misses too.
        let _ = c.cache_get(&2);
        let _ = c.cache_get(&99);
        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 and thus trivially clears its metrics),
        // cache_reset_metrics must explicitly delegate to store.cache_reset_metrics(). If the
        // CLN-2 restructure had left this method only touching the outer counter, the inner
        // capacity-eviction count would survive and this test fails.
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(2)
            .ttl(Duration::from_millis(20))
            .build()
            .unwrap();
        // Inner capacity eviction: 3 inserts into a size-2 cache evicts the LRU key.
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        c.cache_set(3, 30); // 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.
        let _ = c.cache_get(&3); // live -> hit
        let _ = c.cache_get(&99); // miss
        std::thread::sleep(std::time::Duration::from_millis(40));
        c.cache_set(3, 40); // overwrite now-expired key 3 -> outer eviction, returns None
        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 builder_does_not_require_static_without_on_evict() {
        // LruTtlCacheBuilder::build must not impose K: 'static or V: 'static
        // when no on_evict callback is configured.
        fn build_with_borrowed<'a>(_k: &'a str, _v: &'a str) -> LruTtlCache<&'a str, &'a str> {
            LruTtlCache::builder()
                .max_size(4)
                .ttl(Duration::from_secs(60))
                .build()
                .unwrap()
        }
        let mut cache = build_with_borrowed("key", "val");
        cache.cache_set("key", "val");
        assert_eq!(cache.cache_get(&"key"), Some(&"val"));
    }

    #[test]
    fn set_max_size_changes_capacity_and_evicts() {
        let mut cache: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(3)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        cache.cache_set(1, 10);
        cache.cache_set(2, 20);
        cache.cache_set(3, 30);
        assert_eq!(cache.capacity(), 3);

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

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

    #[test]
    fn set_max_size_shrink_fires_on_evict_and_counts_evictions() {
        use std::sync::Mutex;
        let evicted_keys: Arc<Mutex<Vec<u32>>> = Arc::new(Mutex::new(Vec::new()));
        let evicted_keys2 = evicted_keys.clone();
        let mut cache = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(60))
            .on_evict(move |k: &u32, _v: &u32| {
                evicted_keys2.lock().unwrap().push(*k);
            })
            .build()
            .unwrap();

        cache.cache_set(1, 10);
        cache.cache_set(2, 20);
        cache.cache_set(3, 30);
        cache.cache_set(4, 40);
        // Touch 1 and 2 so 3 and 4 become least-recently-used.
        assert_eq!(cache.cache_get(&1), Some(&10));
        assert_eq!(cache.cache_get(&2), Some(&20));

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

        // Two entries were dropped; eviction counter must reflect that.
        assert_eq!(
            cache.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<u32> = 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!(cache.cache_get(&1), Some(&10));
        assert_eq!(cache.cache_get(&2), Some(&20));
        assert_eq!(cache.cache_get(&3), None);
        assert_eq!(cache.cache_get(&4), None);
    }

    #[test]
    fn try_set_max_size_rejects_zero() {
        let mut cache: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(3)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        assert_eq!(
            cache.try_set_max_size(0),
            Err(super::super::SetMaxSizeError::ZeroMaxSize)
        );
        assert_eq!(cache.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 cache: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(3)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        cache.set_max_size(0);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn test_async_trait() {
        use crate::CachedGetOrSetAsync;
        let mut c = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();

        async fn _get(n: usize) -> usize {
            n
        }

        assert_eq!(
            CachedGetOrSetAsync::async_cache_get_or_set_with(&mut c, 0, || async { _get(0).await })
                .await,
            &0
        );
        assert_eq!(
            CachedGetOrSetAsync::async_cache_get_or_set_with(&mut c, 1, || async { _get(1).await })
                .await,
            &1
        );
        assert_eq!(
            CachedGetOrSetAsync::async_cache_get_or_set_with(&mut c, 0, || async {
                _get(99).await
            })
            .await,
            &0
        );
    }

    #[test]
    fn test_diagnostics_and_traits() {
        let mut cache = LruTtlCache::builder()
            .max_size(3)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        cache.cache_set(1, 100);
        cache.cache_set(2, 200);

        // Debug
        let debug_str = format!("{:?}", cache);
        assert!(debug_str.contains("LruTtlCache"));
        assert!(debug_str.contains("size"));
        assert!(debug_str.contains("ttl"));
        assert!(debug_str.contains("hits"));
        assert!(debug_str.contains("misses"));

        // Clone
        let mut cloned = cache.clone();
        assert_eq!(cloned.cache_get(&1), Some(&100));
        assert_eq!(cloned.cache_get(&2), Some(&200));

        // Builder build errors
        let builder = LruTtlCache::<u32, u32>::builder();
        let built = builder.build();
        assert!(built.is_err()); // Missing both size and ttl

        let builder = LruTtlCache::<u32, u32>::builder().max_size(3);
        let built = builder.build();
        assert!(built.is_err()); // Missing ttl

        let builder = LruTtlCache::<u32, u32>::builder().ttl(Duration::from_secs(60));
        let built = builder.build();
        assert!(built.is_err()); // Missing size

        let builder = LruTtlCache::<u32, u32>::builder()
            .max_size(0)
            .ttl(Duration::from_secs(60));
        let built = builder.build();
        assert!(built.is_err()); // Size 0 is invalid

        let builder = LruTtlCache::<u32, u32>::builder()
            .max_size(3)
            .ttl(Duration::ZERO);
        let built = builder.build();
        assert!(built.is_err()); // Zero ttl is invalid
    }

    #[test]
    fn cache_remove_entry_returns_some_for_live_entry() {
        let mut c = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        c.cache_set(1u32, 100u32);
        assert_eq!(c.cache_remove_entry(&999u32), None); // absent
        assert_eq!(c.cache_remove_entry(&1u32), Some((1u32, 100u32)));
        assert_eq!(c.cache_get(&1u32), None);
    }

    #[test]
    fn cache_remove_entry_returns_some_for_expired_entry() {
        let mut c = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_millis(50))
            .build()
            .unwrap();
        c.cache_set(1u32, 100u32);
        std::thread::sleep(std::time::Duration::from_millis(100));

        // cache_remove returns None for expired.
        assert_eq!(c.cache_remove(&1u32), None);

        // cache_remove_entry returns Some even for expired.
        c.cache_set(2u32, 200u32);
        std::thread::sleep(std::time::Duration::from_millis(100));
        let removed = c.cache_remove_entry(&2u32);
        assert!(removed.is_some());
        assert_eq!(
            removed.expect("cache_remove_entry returns Some for expired"),
            (2u32, 200u32)
        );
    }

    #[test]
    fn cache_delete_returns_true_for_expired_entry() {
        let mut c = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_millis(50))
            .build()
            .unwrap();
        c.cache_set(1u32, 100u32);
        std::thread::sleep(std::time::Duration::from_millis(100));
        assert!(
            c.cache_delete(&1u32),
            "cache_delete must be true even for expired entry"
        );
        assert!(!c.cache_delete(&1u32), "cache_delete false when absent");
    }

    #[test]
    fn cache_remove_entry_fires_on_evict_for_expired() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};
        let count = Arc::new(AtomicUsize::new(0));
        let count2 = count.clone();
        let mut c = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_millis(50))
            .on_evict(move |_k: &u32, _v: &u32| {
                count2.fetch_add(1, Ordering::Relaxed);
            })
            .build()
            .unwrap();
        c.cache_set(1u32, 10u32);
        std::thread::sleep(std::time::Duration::from_millis(100));

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

        let _ = c.cache_remove_entry(&999u32);
        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 = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(60))
            .on_evict(|_k: &u32, _v: &u32| panic!("boom"))
            .build()
            .unwrap();
        c.cache_set(1u32, 10u32);
        let r = catch_unwind(AssertUnwindSafe(|| c.cache_remove_entry(&1u32)));
        assert!(r.is_err(), "on_evict should have panicked");
        assert_eq!(c.cache_get(&1u32), None, "entry must still be removed");
        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() {
        // The predicate closure passed to the inner `retain_silent` fires `on_evict`
        // and counts the eviction before returning `false`, so a panicking callback
        // still leaves the eviction counted.
        use std::panic::{AssertUnwindSafe, catch_unwind};
        let mut c = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(60))
            .on_evict(|_k: &u32, _v: &u32| panic!("boom"))
            .build()
            .unwrap();
        c.cache_set(1u32, 10u32);
        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`'s lazy-sweep path pops the expired entry and counts the
        // eviction BEFORE `on_evict` runs, so a panicking callback must not leave
        // the swept entry uncounted.
        use std::panic::{AssertUnwindSafe, catch_unwind};
        let mut c = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_millis(20))
            .on_evict(|_k: &u32, _v: &u32| panic!("boom"))
            .build()
            .unwrap();
        c.cache_set(1u32, 10u32);
        std::thread::sleep(std::time::Duration::from_millis(80));
        let r = catch_unwind(AssertUnwindSafe(|| {
            let _ = c.cache_get(&1u32);
        }));
        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_set_over_expired_with_panicking_on_evict_still_counts_eviction() {
        // Overwriting an already-expired entry fires `on_evict` for the displaced
        // value; `set_entry` counts the eviction BEFORE notifying.
        use std::panic::{AssertUnwindSafe, catch_unwind};
        let mut c = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_millis(20))
            .on_evict(|_k: &u32, _v: &u32| panic!("boom"))
            .build()
            .unwrap();
        c.cache_set(1u32, 10u32);
        std::thread::sleep(std::time::Duration::from_millis(80));
        let r = catch_unwind(AssertUnwindSafe(|| c.cache_set(1u32, 20u32)));
        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_increments_eviction_counter() {
        let mut c = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_millis(10))
            .build()
            .unwrap();
        c.cache_set(1u32, 10u32);
        std::thread::sleep(std::time::Duration::from_millis(100));
        let before = c.cache_evictions().expect("evictions are always tracked");
        let _ = c.cache_remove_entry(&1u32); // expired but present -- must increment
        let _ = c.cache_remove_entry(&999u32); // 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"
        );
    }

    // --- custom hasher tests ---

    #[test]
    fn custom_hasher_get_set_round_trip() {
        use std::collections::hash_map::RandomState;
        let mut c = LruTtlCache::<u32, u32>::builder()
            .max_size(10)
            .ttl_secs(60)
            .hasher(RandomState::new())
            .build()
            .unwrap();
        assert_eq!(c.cache_set(1, 100), None);
        assert_eq!(c.cache_set(2, 200), None);
        assert_eq!(c.cache_get(&1), Some(&100));
        assert_eq!(c.cache_get(&2), Some(&200));
        assert_eq!(c.cache_hits(), Some(2));
        assert_eq!(c.cache_misses(), Some(0));
        assert_eq!(c.cache_get(&99), None);
        assert_eq!(c.cache_misses(), Some(1));
    }

    #[test]
    fn default_constructor_still_works() {
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::new(5, Duration::from_secs(60));
        c.cache_set(1, 10);
        assert_eq!(c.cache_get(&1), Some(&10));
    }

    #[test]
    fn custom_hasher_respects_lru_eviction_and_ttl() {
        use std::collections::hash_map::RandomState;
        // Test LRU eviction
        let mut c = LruTtlCache::<u32, u32>::builder()
            .max_size(2)
            .ttl_secs(60)
            .hasher(RandomState::new())
            .build()
            .unwrap();
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        c.cache_get(&1); // make 1 most-recently-used
        c.cache_set(3, 30); // should evict 2
        assert_eq!(c.cache_get(&1), Some(&10));
        assert_eq!(c.cache_get(&2), None); // evicted
        assert_eq!(c.cache_get(&3), Some(&30));

        // Test TTL expiry
        let mut c2 = LruTtlCache::<u32, u32>::builder()
            .max_size(10)
            .ttl(Duration::from_millis(50))
            .hasher(RandomState::new())
            .build()
            .unwrap();
        c2.cache_set(1, 10);
        assert_eq!(c2.cache_get(&1), Some(&10));
        std::thread::sleep(std::time::Duration::from_millis(100));
        assert_eq!(c2.cache_get(&1), None, "entry must expire after ttl");
    }

    // CORE-3: the sync get_or_set paths must anchor the expiry AFTER the factory
    // runs, so a factory slower than the TTL still yields a live entry.
    #[test]
    fn sync_expiry_anchored_after_factory() {
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_millis(40))
            .build()
            .unwrap();
        let v = c.cache_get_or_set_with(1, || {
            std::thread::sleep(std::time::Duration::from_millis(120));
            7
        });
        assert_eq!(*v, 7);
        assert_eq!(
            c.cache_get(&1),
            Some(&7),
            "entry must be live right after insert"
        );
    }

    // 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: LruTtlCache<TaggedKey, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_millis(20))
            .on_evict(move |k: &TaggedKey, _v: &u32| {
                evicted_tags2.lock().unwrap().push(k.tag);
            })
            .build()
            .unwrap();

        // Insert with tag "a".
        cache.cache_set(TaggedKey { id: 1, tag: "a" }, 100);
        // Let it expire.
        std::thread::sleep(std::time::Duration::from_millis(60));
        // 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" }, 200);

        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')"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_expiry_anchored_after_factory() {
        use crate::CachedGetOrSetAsync;
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_millis(40))
            .build()
            .unwrap();
        let v = CachedGetOrSetAsync::async_cache_get_or_set_with(&mut c, 1, || async {
            tokio::time::sleep(std::time::Duration::from_millis(120)).await;
            7
        })
        .await;
        assert_eq!(*v, 7);
        assert_eq!(
            c.cache_get(&1),
            Some(&7),
            "entry must be live right after insert"
        );
    }

    // =====================================================================
    // PERF-2: clock threading / eager-sweep snapshots / hash reuse.
    //
    // Every change under PERF-2 is internal-only, so the tests below pin the
    // *observable* contracts that the rewrites must not disturb:
    //   * the `now >= expires_at` expiry boundary at every converted call site,
    //   * `refresh_on_hit` extending by the FULL ttl measured from the hit,
    //   * a slow factory's expiry still anchored AFTER the factory returns,
    //   * `retain`/`evict` judging every entry against ONE pass-start snapshot,
    //   * `cache_clear_with_on_evict` firing MRU -> LRU,
    //   * the lazy expiry sweep (now reusing the probe's hash) still removing
    //     the entry it swept.
    // =====================================================================

    /// Insert an entry with an explicitly chosen `expires_at`, bypassing the ttl
    /// arithmetic, so a test can pin the exact `now >= expires_at` boundary.
    /// Writes straight into the inner `LruCache`; the outer counters are untouched.
    fn put_raw(c: &mut LruTtlCache<u32, u32>, k: u32, v: u32, expires_at: Option<Instant>) {
        c.store.cache_set(
            k,
            TimedEntry {
                expires_at,
                value: v,
            },
        );
    }

    /// Read an entry's stored `expires_at` without any read side effects
    /// (no promotion, no refresh, no metrics).
    fn stored_expiry(c: &LruTtlCache<u32, u32>, k: u32) -> Option<Instant> {
        CachedPeek::cache_peek(&c.store, &k)
            .expect("entry must be present")
            .expires_at
    }

    fn long_ttl_cache(max_size: usize) -> LruTtlCache<u32, u32> {
        LruTtlCache::builder()
            .max_size(max_size)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap()
    }

    // `entry_live_at` must preserve the exact `now >= expires_at` boundary
    // convention of `entry_live` (which reads `Instant::now()` internally):
    // at `now == expires_at` the entry is already expired.
    #[test]
    fn entry_live_at_matches_now_ge_expires_at_is_expired_convention() {
        let now = Instant::now();
        let future = now + Duration::from_millis(10);
        let past = now - Duration::from_millis(10);

        // `expires_at = None` never expires, regardless of `now`.
        assert!(LruTtlCache::<u32, u32>::entry_live_at(None, now));
        // `now < expires_at`: live.
        assert!(LruTtlCache::<u32, u32>::entry_live_at(Some(future), now));
        // `now == expires_at`: the boundary itself is NOT live.
        assert!(!LruTtlCache::<u32, u32>::entry_live_at(Some(now), now));
        // `now > expires_at`: not live.
        assert!(!LruTtlCache::<u32, u32>::entry_live_at(Some(past), now));
    }

    // --- boundary coverage at each converted call site ---------------------
    //
    // Each test crafts an entry whose `expires_at` is an `Instant` sampled just
    // before the call under test. The process clock is monotonic, so the call's
    // own internal reading is guaranteed to be `>=` that instant: this
    // deterministically exercises the "tie or later" edge without a mock clock.
    // A comfortably-future `expires_at` exercises the live side and
    // `expires_at = None` exercises "never expires".

    #[test]
    fn cache_get_boundary_matches_now_ge_expires_at_convention() {
        let mut c = long_ttl_cache(8);

        let tie = Instant::now();
        put_raw(&mut c, 1, 100, Some(tie));
        assert_eq!(
            c.cache_get(&1),
            None,
            "tie (now >= expires_at) must be a miss"
        );
        assert_eq!(c.cache_size(), 0, "expired entry must be swept on access");

        put_raw(
            &mut c,
            2,
            200,
            Some(Instant::now() + Duration::from_secs(60)),
        );
        assert_eq!(
            c.cache_get(&2),
            Some(&200),
            "now < expires_at must be a hit"
        );

        put_raw(&mut c, 3, 300, None);
        std::thread::sleep(std::time::Duration::from_millis(20));
        assert_eq!(
            c.cache_get(&3),
            Some(&300),
            "expires_at = None never expires"
        );
    }

    #[test]
    fn cache_get_mut_boundary_matches_now_ge_expires_at_convention() {
        let mut c = long_ttl_cache(8);

        let tie = Instant::now();
        put_raw(&mut c, 1, 100, Some(tie));
        assert_eq!(
            c.cache_get_mut(&1),
            None,
            "tie (now >= expires_at) must be a miss"
        );
        assert_eq!(c.cache_size(), 0, "expired entry must be swept on access");

        put_raw(
            &mut c,
            2,
            200,
            Some(Instant::now() + Duration::from_secs(60)),
        );
        assert_eq!(
            c.cache_get_mut(&2),
            Some(&mut 200),
            "now < expires_at must be a hit"
        );

        put_raw(&mut c, 3, 300, None);
        std::thread::sleep(std::time::Duration::from_millis(20));
        assert_eq!(
            c.cache_get_mut(&3),
            Some(&mut 300),
            "expires_at = None never expires"
        );
    }

    #[test]
    fn cache_set_boundary_matches_now_ge_expires_at_convention() {
        // `cache_set` samples `now` once and threads it into `set_entry`, which
        // decides whether the DISPLACED entry was still live.
        let mut c = long_ttl_cache(8);

        let tie = Instant::now();
        put_raw(&mut c, 1, 100, Some(tie));
        let before = c.cache_evictions().unwrap();
        assert_eq!(
            c.cache_set(1, 111),
            None,
            "displacing an entry at the tie (now >= expires_at) must return None"
        );
        assert_eq!(
            c.cache_evictions().unwrap(),
            before + 1,
            "the displaced expired entry must count as an eviction"
        );

        put_raw(
            &mut c,
            2,
            200,
            Some(Instant::now() + Duration::from_secs(60)),
        );
        let before = c.cache_evictions().unwrap();
        assert_eq!(
            c.cache_set(2, 222),
            Some(200),
            "displacing a live entry must return the old value"
        );
        assert_eq!(
            c.cache_evictions().unwrap(),
            before,
            "displacing a live entry must not count an eviction"
        );

        put_raw(&mut c, 3, 300, None);
        std::thread::sleep(std::time::Duration::from_millis(20));
        assert_eq!(
            c.cache_set(3, 333),
            Some(300),
            "expires_at = None never expires, so the old value is returned"
        );
    }

    #[test]
    fn cache_get_or_set_with_boundary_matches_now_ge_expires_at_convention() {
        let mut c = long_ttl_cache(8);

        let tie = Instant::now();
        put_raw(&mut c, 1, 100, Some(tie));
        assert_eq!(
            *c.cache_get_or_set_with(1, || 999),
            999,
            "tie (now >= expires_at) must be treated as expired and replaced"
        );

        put_raw(
            &mut c,
            2,
            200,
            Some(Instant::now() + Duration::from_secs(60)),
        );
        assert_eq!(
            *c.cache_get_or_set_with(2, || 999),
            200,
            "now < expires_at must be a hit, so the factory must not run"
        );

        put_raw(&mut c, 3, 300, None);
        std::thread::sleep(std::time::Duration::from_millis(20));
        assert_eq!(
            *c.cache_get_or_set_with(3, || 999),
            300,
            "expires_at = None never expires"
        );
    }

    #[test]
    fn cache_try_get_or_set_with_boundary_matches_now_ge_expires_at_convention() {
        let mut c = long_ttl_cache(8);

        let tie = Instant::now();
        put_raw(&mut c, 1, 100, Some(tie));
        assert_eq!(
            c.cache_try_get_or_set_with(1, || Ok::<u32, ()>(999))
                .copied(),
            Ok(999),
            "tie (now >= expires_at) must be treated as expired and replaced"
        );

        put_raw(
            &mut c,
            2,
            200,
            Some(Instant::now() + Duration::from_secs(60)),
        );
        assert_eq!(
            c.cache_try_get_or_set_with(2, || Ok::<u32, ()>(999))
                .copied(),
            Ok(200),
            "now < expires_at must be a hit, so the factory must not run"
        );

        put_raw(&mut c, 3, 300, None);
        std::thread::sleep(std::time::Duration::from_millis(20));
        assert_eq!(
            c.cache_try_get_or_set_with(3, || Ok::<u32, ()>(999))
                .copied(),
            Ok(300),
            "expires_at = None never expires"
        );
    }

    #[test]
    fn cache_get_with_expiry_status_boundary_matches_now_ge_expires_at_convention() {
        let mut c = long_ttl_cache(8);

        let tie = Instant::now();
        put_raw(&mut c, 1, 100, Some(tie));
        assert_eq!(
            c.cache_get_with_expiry_status(&1),
            (Some(100), true),
            "tie (now >= expires_at) must report expired"
        );

        put_raw(
            &mut c,
            2,
            200,
            Some(Instant::now() + Duration::from_secs(60)),
        );
        assert_eq!(
            c.cache_get_with_expiry_status(&2),
            (Some(200), false),
            "now < expires_at must report live"
        );

        put_raw(&mut c, 3, 300, None);
        std::thread::sleep(std::time::Duration::from_millis(20));
        assert_eq!(
            c.cache_get_with_expiry_status(&3),
            (Some(300), false),
            "expires_at = None never expires"
        );
    }

    #[test]
    fn order_collectors_boundary_matches_now_ge_expires_at_convention() {
        // `iter_order` / `key_order` / `value_order` hoist ONE clock reading for the
        // whole pass; the boundary they apply per entry must be unchanged.
        let mut c = long_ttl_cache(8);
        put_raw(&mut c, 1, 100, None); // never expires
        put_raw(
            &mut c,
            2,
            200,
            Some(Instant::now() + Duration::from_secs(60)),
        ); // live
        let tie = Instant::now();
        put_raw(&mut c, 3, 300, Some(tie)); // tie -> expired

        // MRU -> LRU is 3, 2, 1; the tie entry is filtered out of all three views.
        assert_eq!(c.key_order(), vec![2, 1]);
        assert_eq!(
            c.iter_order()
                .into_iter()
                .map(|(k, v)| (k, *v))
                .collect::<Vec<_>>(),
            vec![(2, 200), (1, 100)]
        );
        assert_eq!(
            c.value_order()
                .into_iter()
                .map(|v| v.into_value())
                .collect::<Vec<_>>(),
            vec![200, 100]
        );
        // The views are non-destructive: the expired entry is still stored.
        assert_eq!(c.cache_size(), 3);
    }

    #[test]
    fn evict_boundary_matches_now_ge_expires_at_convention() {
        let mut c = long_ttl_cache(8);
        put_raw(&mut c, 1, 100, None);
        put_raw(
            &mut c,
            2,
            200,
            Some(Instant::now() + Duration::from_secs(60)),
        );
        let tie = Instant::now();
        put_raw(&mut c, 3, 300, Some(tie));

        assert_eq!(c.evict(), 1, "only the tie entry is expired");
        assert_eq!(c.key_order(), vec![2, 1]);
    }

    #[test]
    fn retain_boundary_matches_now_ge_expires_at_convention() {
        let mut c = long_ttl_cache(8);
        put_raw(&mut c, 1, 100, None);
        put_raw(
            &mut c,
            2,
            200,
            Some(Instant::now() + Duration::from_secs(60)),
        );
        let tie = Instant::now();
        put_raw(&mut c, 3, 300, Some(tie));

        // Predicate keeps everything: only the expiry boundary decides.
        c.retain(|_k, _v| true);
        assert_eq!(
            c.key_order(),
            vec![2, 1],
            "the tie entry (now >= expires_at) must be swept regardless of the predicate"
        );
    }

    #[test]
    fn retain_returns_count_folding_expired_and_predicate_rejections() {
        // The returned count must fold together BOTH predicate-rejected entries and
        // entries removed because they had 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, Ordering};

        let fired = Arc::new(AtomicUsize::new(0));
        let fired2 = fired.clone();
        let mut c = LruTtlCache::builder()
            .max_size(10)
            .ttl(Duration::from_millis(30))
            .on_evict(move |_k: &u32, _v: &u32| {
                fired2.fetch_add(1, Ordering::Relaxed);
            })
            .build()
            .unwrap();

        // Key 1: will expire before the sweep, regardless of the predicate.
        c.cache_set(1, 10);
        std::thread::sleep(std::time::Duration::from_millis(80));
        // Keys 2-4: inserted after the sleep, still live relative to `retain`'s
        // hoisted `now`. Key 3 is rejected by the predicate, keys 2 and 4 are kept.
        c.cache_set(2, 20);
        c.cache_set(3, 31);
        c.cache_set(4, 40);

        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(&20));
        assert_eq!(c.cache_get(&3), None);
        assert_eq!(c.cache_get(&4), Some(&40));
    }

    // --- refresh_on_hit anchoring ------------------------------------------

    // With `refresh_on_hit`, a hit must extend the entry's expiry by the FULL
    // configured ttl measured from the moment of the hit -- never by
    // ttl-minus-epsilon from a stale/earlier clock reading. Bracketed by clock
    // reads taken immediately before and after the hit.
    //
    // The ttl is deliberately far longer than the pre-hit sleep so a descheduled
    // test thread can never let the entry expire mid-test (that would turn a real
    // assertion failure into a flake); the sleep only has to be long enough that
    // `before + ttl` is strictly greater than the original expiry, which is what
    // makes "the expiry actually moved" observable.
    const REFRESH_TTL: Duration = Duration::from_secs(30);
    const REFRESH_GAP: std::time::Duration = std::time::Duration::from_millis(20);

    fn refreshing_cache() -> LruTtlCache<u32, u32> {
        LruTtlCache::builder()
            .max_size(4)
            .ttl(REFRESH_TTL)
            .refresh_on_hit(true)
            .build()
            .unwrap()
    }

    /// Assert that a hit bracketed by `before`/`after` re-anchored key 1's expiry to
    /// the hit itself, extended by the full ttl.
    fn assert_refreshed_to_hit_time(
        c: &LruTtlCache<u32, u32>,
        original: Instant,
        before: Instant,
        after: Instant,
    ) {
        let expires_at = stored_expiry(c, 1).expect("finite ttl carries an expiry");
        assert!(
            expires_at > original,
            "refresh_on_hit must move the expiry forward"
        );
        assert!(
            expires_at >= before + REFRESH_TTL,
            "refresh must extend by the FULL ttl measured from the hit, not less"
        );
        assert!(
            expires_at <= after + REFRESH_TTL,
            "refresh must not anchor to a clock reading taken before the hit"
        );
    }

    #[test]
    fn refresh_on_hit_cache_get_extends_by_full_ttl_from_hit_time() {
        let mut c = refreshing_cache();
        c.cache_set(1, 100);
        let original = stored_expiry(&c, 1).expect("finite ttl carries an expiry");
        std::thread::sleep(REFRESH_GAP);

        let before = Instant::now();
        assert_eq!(c.cache_get(&1), Some(&100));
        let after = Instant::now();

        assert_refreshed_to_hit_time(&c, original, before, after);
    }

    #[test]
    fn refresh_on_hit_cache_get_mut_extends_by_full_ttl_from_hit_time() {
        let mut c = refreshing_cache();
        c.cache_set(1, 100);
        let original = stored_expiry(&c, 1).expect("finite ttl carries an expiry");
        std::thread::sleep(REFRESH_GAP);

        let before = Instant::now();
        assert_eq!(c.cache_get_mut(&1), Some(&mut 100));
        let after = Instant::now();

        assert_refreshed_to_hit_time(&c, original, before, after);
    }

    #[test]
    fn refresh_on_hit_get_or_set_extends_by_full_ttl_from_hit_time() {
        // The hit path of `cache_get_or_set_with` now reuses the clock reading taken
        // by the store's validity check; it must still be a reading from THIS call.
        let mut c = refreshing_cache();
        c.cache_set(1, 100);
        let original = stored_expiry(&c, 1).expect("finite ttl carries an expiry");
        std::thread::sleep(REFRESH_GAP);

        let before = Instant::now();
        assert_eq!(*c.cache_get_or_set_with(1, || 999), 100);
        let after = Instant::now();

        assert_refreshed_to_hit_time(&c, original, before, after);
    }

    #[test]
    fn refresh_on_hit_try_get_or_set_extends_by_full_ttl_from_hit_time() {
        let mut c = refreshing_cache();
        c.cache_set(1, 100);
        let original = stored_expiry(&c, 1).expect("finite ttl carries an expiry");
        std::thread::sleep(REFRESH_GAP);

        let before = Instant::now();
        assert_eq!(
            c.cache_try_get_or_set_with(1, || Ok::<u32, ()>(999))
                .copied(),
            Ok(100)
        );
        let after = Instant::now();

        assert_refreshed_to_hit_time(&c, original, before, after);
    }

    #[test]
    fn refresh_on_hit_get_with_expiry_status_extends_by_full_ttl_from_hit_time() {
        let mut c = refreshing_cache();
        c.cache_set(1, 100);
        let original = stored_expiry(&c, 1).expect("finite ttl carries an expiry");
        std::thread::sleep(REFRESH_GAP);

        let before = Instant::now();
        assert_eq!(c.cache_get_with_expiry_status(&1), (Some(100), false));
        let after = Instant::now();

        assert_refreshed_to_hit_time(&c, original, before, after);
    }

    #[test]
    fn refresh_on_hit_disabled_leaves_expiry_untouched() {
        // Guard the other direction: reusing one clock reading must not start
        // refreshing entries in a cache that never opted into refresh_on_hit.
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_millis(400))
            .build()
            .unwrap();
        c.cache_set(1, 100);
        let original = stored_expiry(&c, 1).expect("finite ttl carries an expiry");
        std::thread::sleep(std::time::Duration::from_millis(20));
        assert_eq!(c.cache_get(&1), Some(&100));
        assert_eq!(*c.cache_get_or_set_with(1, || 999), 100);
        assert_eq!(
            stored_expiry(&c, 1),
            Some(original),
            "without refresh_on_hit a hit must not move the expiry"
        );
    }

    // --- slow-factory anchoring ---------------------------------------------

    // The `hit_at` reading sampled for the validity check must NOT be reused as the
    // new entry's expiry anchor: the factory may run arbitrarily long, so the fresh
    // expiry has to be anchored AFTER it returns. Measured directly against the
    // stored `expires_at`, so it fails even if the factory is faster than the ttl.
    #[test]
    fn get_or_set_expiry_anchored_after_slow_factory_returns() {
        let ttl = Duration::from_millis(500);
        let mut c: LruTtlCache<u32, u32> =
            LruTtlCache::builder().max_size(4).ttl(ttl).build().unwrap();
        // Pre-seed an EXPIRED entry so the replacement path (validity check first,
        // then factory) is the one exercised.
        put_raw(&mut c, 1, 100, Some(Instant::now()));

        assert_eq!(
            *c.cache_get_or_set_with(1, || {
                std::thread::sleep(std::time::Duration::from_millis(120));
                7
            }),
            7
        );
        let factory_returned = Instant::now();
        let expires_at = stored_expiry(&c, 1).expect("finite ttl carries an expiry");
        assert!(
            expires_at + Duration::from_millis(120) > factory_returned + ttl,
            "the expiry must be anchored after the factory returned, not at lookup time"
        );
        assert_eq!(
            c.cache_get(&1),
            Some(&7),
            "entry must be live right after insert"
        );
    }

    #[test]
    fn try_get_or_set_expiry_anchored_after_slow_factory_returns() {
        let ttl = Duration::from_millis(500);
        let mut c: LruTtlCache<u32, u32> =
            LruTtlCache::builder().max_size(4).ttl(ttl).build().unwrap();
        put_raw(&mut c, 1, 100, Some(Instant::now()));

        assert_eq!(
            c.cache_try_get_or_set_with(1, || {
                std::thread::sleep(std::time::Duration::from_millis(120));
                Ok::<u32, ()>(7)
            })
            .copied(),
            Ok(7)
        );
        let factory_returned = Instant::now();
        let expires_at = stored_expiry(&c, 1).expect("finite ttl carries an expiry");
        assert!(
            expires_at + Duration::from_millis(120) > factory_returned + ttl,
            "the expiry must be anchored after the factory returned, not at lookup time"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_get_or_set_expiry_anchored_after_slow_factory_returns() {
        use crate::CachedGetOrSetAsync;
        let ttl = Duration::from_millis(500);
        let mut c: LruTtlCache<u32, u32> =
            LruTtlCache::builder().max_size(4).ttl(ttl).build().unwrap();
        put_raw(&mut c, 1, 100, Some(Instant::now()));

        let v = CachedGetOrSetAsync::async_cache_get_or_set_with(&mut c, 1, || async {
            tokio::time::sleep(std::time::Duration::from_millis(120)).await;
            7
        })
        .await;
        assert_eq!(*v, 7);
        let factory_returned = Instant::now();
        let expires_at = stored_expiry(&c, 1).expect("finite ttl carries an expiry");
        assert!(
            expires_at + Duration::from_millis(120) > factory_returned + ttl,
            "the expiry must be anchored after the factory resolved, not at lookup time"
        );
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn async_refresh_on_hit_extends_by_full_ttl_from_hit_time() {
        use crate::CachedGetOrSetAsync;
        let ttl = Duration::from_millis(200);
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl(ttl)
            .refresh_on_hit(true)
            .build()
            .unwrap();
        c.cache_set(1, 100);
        tokio::time::sleep(std::time::Duration::from_millis(60)).await;

        let before = Instant::now();
        let v = CachedGetOrSetAsync::async_cache_get_or_set_with(&mut c, 1, || async { 999 }).await;
        assert_eq!(*v, 100);
        let after = Instant::now();

        let expires_at = stored_expiry(&c, 1).expect("finite ttl carries an expiry");
        assert!(
            expires_at >= before + ttl,
            "refresh must extend by the FULL ttl measured from the hit"
        );
        assert!(
            expires_at <= after + ttl,
            "refresh must not anchor to a clock reading taken before the hit"
        );
    }

    // --- one snapshot per eager sweep ---------------------------------------

    #[test]
    fn retain_judges_every_entry_against_one_pass_start_snapshot() {
        // `retain` samples the clock ONCE at the top of the pass. An entry that is
        // live when the pass starts must survive even if it expires while the pass
        // is still running. With a per-entry clock reading the slow predicate below
        // would push the second entry past its expiry and sweep it.
        let mut c = long_ttl_cache(8);
        // MRU -> LRU order is 2, 1: entry 1 is judged AFTER the slow predicate call
        // for entry 2.
        put_raw(
            &mut c,
            1,
            100,
            Some(Instant::now() + Duration::from_millis(80)),
        );
        put_raw(&mut c, 2, 200, None);

        c.retain(|_k, _v| {
            std::thread::sleep(std::time::Duration::from_millis(200));
            true
        });

        // `cache_size` is the RAW stored count (entry 1 has expired by now, so the
        // expiry-filtering `key_order` would not show it).
        assert_eq!(
            c.cache_size(),
            2,
            "an entry live at the start of the pass must survive the whole pass"
        );
    }

    #[test]
    fn evict_judges_every_entry_against_one_pass_start_snapshot() {
        // Same guarantee for `evict`, using a slow `on_evict` callback to stretch
        // the pass past a later entry's expiry.
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(8)
            .ttl(Duration::from_secs(60))
            .on_evict(|_k: &u32, _v: &u32| {
                std::thread::sleep(std::time::Duration::from_millis(200));
            })
            .build()
            .unwrap();
        // MRU -> LRU order is 3, 2, 1: the already-expired entry 2 fires the slow
        // callback before entry 1 is judged.
        put_raw(
            &mut c,
            1,
            100,
            Some(Instant::now() + Duration::from_millis(80)),
        );
        put_raw(&mut c, 2, 200, Some(Instant::now()));
        put_raw(&mut c, 3, 300, None);

        assert_eq!(
            c.evict(),
            1,
            "only the entry already expired at the start of the pass may be swept"
        );
        assert_eq!(c.cache_size(), 2);
    }

    // --- cache_clear_with_on_evict ------------------------------------------

    #[test]
    fn cache_clear_with_on_evict_fires_mru_to_lru() {
        use std::sync::Mutex;
        let fired: Arc<Mutex<Vec<(u32, u32)>>> = Arc::new(Mutex::new(Vec::new()));
        let fired2 = fired.clone();
        let mut c = LruTtlCache::builder()
            .max_size(5)
            .ttl(Duration::from_secs(60))
            .on_evict(move |k: &u32, v: &u32| {
                fired2.lock().unwrap().push((*k, *v));
            })
            .build()
            .unwrap();
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        c.cache_set(3, 30);
        // Promote 1 so the MRU -> LRU order is 1, 3, 2 (not simply insertion order).
        assert_eq!(c.cache_get(&1), Some(&10));
        assert_eq!(c.key_order(), vec![1, 3, 2]);

        c.cache_clear_with_on_evict();

        assert_eq!(
            fired.lock().unwrap().as_slice(),
            &[(1, 10), (3, 30), (2, 20)],
            "on_evict must fire in MRU -> LRU order"
        );
        assert_eq!(c.cache_size(), 0);
    }

    #[test]
    fn cache_clear_with_on_evict_fires_for_expired_entries_too() {
        // The clear is expiry-blind: every stored entry fires the callback and is
        // counted, whether or not it had already expired.
        let count = Arc::new(AtomicUsize::new(0));
        let count2 = count.clone();
        let mut c = LruTtlCache::builder()
            .max_size(5)
            .ttl(Duration::from_secs(60))
            .on_evict(move |_k: &u32, _v: &u32| {
                count2.fetch_add(1, AtomicOrdering::Relaxed);
            })
            .build()
            .unwrap();
        c.store.cache_set(
            1,
            TimedEntry {
                expires_at: Some(Instant::now()),
                value: 10,
            },
        );
        c.store.cache_set(
            2,
            TimedEntry {
                expires_at: None,
                value: 20,
            },
        );

        c.cache_clear_with_on_evict();
        assert_eq!(count.load(AtomicOrdering::Relaxed), 2);
        assert_eq!(c.evictions.load(AtomicOrdering::Relaxed), 2);
        assert_eq!(c.cache_size(), 0);
    }

    #[test]
    fn cache_clear_with_on_evict_leaves_cache_reusable() {
        // `drain_all` resets the LRU slab's sentinels; the cache must behave
        // normally afterwards (inserts, recency order, capacity eviction).
        let mut c = LruTtlCache::builder()
            .max_size(2)
            .ttl(Duration::from_secs(60))
            .on_evict(|_k: &u32, _v: &u32| {})
            .build()
            .unwrap();
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        c.cache_clear_with_on_evict();
        assert_eq!(c.cache_size(), 0);
        assert_eq!(c.key_order(), Vec::<u32>::new());

        c.cache_set(3, 30);
        c.cache_set(4, 40);
        assert_eq!(c.key_order(), vec![4, 3]);
        assert_eq!(c.cache_get(&3), Some(&30));
        c.cache_set(5, 50); // evicts the LRU entry (4)
        assert_eq!(c.cache_size(), 2);
        assert_eq!(c.cache_get(&4), None);
        assert_eq!(c.cache_get(&3), Some(&30));
    }

    #[test]
    fn cache_clear_with_on_evict_without_callback_is_a_plain_clear() {
        let mut c = long_ttl_cache(4);
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        let before = c.cache_evictions().unwrap();
        c.cache_clear_with_on_evict();
        assert_eq!(c.cache_size(), 0);
        assert_eq!(
            c.cache_evictions().unwrap(),
            before,
            "without a callback this is a plain clear: no eviction accounting"
        );
    }

    // --- lazy expiry sweep reuses the probe's hash ---------------------------

    #[test]
    fn cache_get_lazy_sweep_removes_the_expired_entry() {
        // The expired branch pops with the hash already computed for the probe. A
        // mismatched hash would silently miss and leave the entry in the store.
        let count = Arc::new(AtomicUsize::new(0));
        let count2 = count.clone();
        let mut c = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(60))
            .on_evict(move |_k: &u32, _v: &u32| {
                count2.fetch_add(1, AtomicOrdering::Relaxed);
            })
            .build()
            .unwrap();
        c.store.cache_set(
            1,
            TimedEntry {
                expires_at: Some(Instant::now()),
                value: 10,
            },
        );
        assert_eq!(c.cache_size(), 1);
        assert_eq!(c.cache_get(&1), None);
        assert_eq!(c.cache_size(), 0, "the expired entry must be removed");
        assert_eq!(count.load(AtomicOrdering::Relaxed), 1);
        assert_eq!(c.evictions.load(AtomicOrdering::Relaxed), 1);
        // A second get is a plain absent-key miss.
        assert_eq!(c.cache_get(&1), None);
        assert_eq!(count.load(AtomicOrdering::Relaxed), 1);
    }

    #[test]
    fn cache_get_mut_lazy_sweep_removes_the_expired_entry() {
        let mut c: LruTtlCache<u32, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        c.store.cache_set(
            1,
            TimedEntry {
                expires_at: Some(Instant::now()),
                value: 10,
            },
        );
        assert_eq!(c.cache_get_mut(&1), None);
        assert_eq!(c.cache_size(), 0, "the expired entry must be removed");
    }

    #[test]
    fn cache_get_lazy_sweep_removes_borrowed_key_entry() {
        // Borrowed lookup form (`K = String`, `Q = str`): the hash reused by the
        // lazy sweep is the one computed from `&str`, which must still locate the
        // `String`-keyed entry.
        let mut c: LruTtlCache<String, u32> = LruTtlCache::builder()
            .max_size(4)
            .ttl(Duration::from_secs(60))
            .build()
            .unwrap();
        c.store.cache_set(
            "alpha".to_string(),
            TimedEntry {
                expires_at: Some(Instant::now()),
                value: 10,
            },
        );
        assert_eq!(c.cache_get("alpha"), None);
        assert_eq!(
            c.cache_size(),
            0,
            "the expired entry must be removed via the borrowed-key hash"
        );

        // The live path over the same borrowed form still works.
        c.cache_set("beta".to_string(), 20);
        assert_eq!(c.cache_get("beta"), Some(&20));
        assert_eq!(c.cache_get_mut("beta"), Some(&mut 20));
    }

    // --- recency preserved ---------------------------------------------------

    #[test]
    fn clock_threading_does_not_change_cache_set_recency() {
        // `set_entry` goes through `cache_set_returning_entry`, which promotes the
        // overwritten key to MRU. Threading `now` through must not change that.
        let mut c = long_ttl_cache(3);
        c.cache_set(1, 10);
        c.cache_set(2, 20);
        c.cache_set(3, 30);
        assert_eq!(c.key_order(), vec![3, 2, 1]);
        assert_eq!(c.cache_set(1, 11), Some(10));
        assert_eq!(
            c.key_order(),
            vec![1, 3, 2],
            "an overwrite must promote the entry to MRU"
        );
        // ... and the get paths promote too.
        assert_eq!(c.cache_get(&2), Some(&20));
        assert_eq!(c.key_order(), vec![2, 1, 3]);
        // Overwriting an EXPIRED entry (the other `set_entry` arm) promotes as well;
        // the displaced expired value is filtered from the return.
        // (`put_raw` writes through the inner store, so it promotes too; `key_order`
        // filters the now-expired key 3 out of the visible order.)
        put_raw(&mut c, 3, 33, Some(Instant::now()));
        assert_eq!(c.key_order(), vec![2, 1]);
        assert_eq!(c.cache_set(3, 333), None);
        assert_eq!(c.key_order(), vec![3, 2, 1]);
    }
}