mx-cache 0.1.0

Shared cache utilities (local + Redis) for MultiversX Rust services.
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
//! Comprehensive test suite for mx-cache crate.
//!
//! This module contains:
//! - Extended `LocalCache` tests
//! - Mock-based `RedisCache` tests
//! - Property-based tests using proptest
//! - Concurrent access pattern tests
//! - Edge case and stress tests

use crate::{Cache, LocalCache};
use std::time::Duration;

// ============================================================================
// LocalCache Extended Tests
// ============================================================================

mod local_cache_tests {
    use super::*;
    use futures::future::join_all;

    fn create_test_cache() -> LocalCache {
        LocalCache::new(1000, Duration::from_secs(60))
    }

    // ==================== Edge Cases ====================

    #[tokio::test]
    async fn test_empty_key() {
        let cache = create_test_cache();
        let key: &[u8] = b"";
        let value = b"value_for_empty_key";

        cache
            .set(key, value, Duration::from_secs(60))
            .await
            .unwrap();
        let result = cache.get(key).await.unwrap();

        assert_eq!(result, Some(value.to_vec()));
    }

    #[tokio::test]
    async fn test_empty_value() {
        let cache = create_test_cache();
        let key = b"key_with_empty_value";
        let value: &[u8] = b"";

        cache
            .set(key, value, Duration::from_secs(60))
            .await
            .unwrap();
        let result = cache.get(key).await.unwrap();

        assert_eq!(result, Some(Vec::new()));
    }

    #[tokio::test]
    async fn test_large_value() {
        let cache = create_test_cache();
        let key = b"large_value_key";
        let value: Vec<u8> = (0..10_000).map(|i| (i % 256) as u8).collect();

        cache
            .set(key, &value, Duration::from_secs(60))
            .await
            .unwrap();
        let result = cache.get(key).await.unwrap();

        assert_eq!(result, Some(value));
    }

    #[tokio::test]
    async fn test_binary_key_and_value() {
        let cache = create_test_cache();
        // Binary data with null bytes and special characters
        let key: &[u8] = &[0x00, 0xFF, 0x01, 0xFE, 0x00];
        let value: &[u8] = &[0xDE, 0xAD, 0xBE, 0xEF, 0x00, 0x00];

        cache
            .set(key, value, Duration::from_secs(60))
            .await
            .unwrap();
        let result = cache.get(key).await.unwrap();

        assert_eq!(result, Some(value.to_vec()));
    }

    #[tokio::test]
    async fn test_unicode_bytes_in_key() {
        let cache = create_test_cache();
        // UTF-8 encoded unicode string
        let key = b"";
        let value = b"value";

        cache
            .set(key, value, Duration::from_secs(60))
            .await
            .unwrap();
        let result = cache.get(key).await.unwrap();

        assert_eq!(result, Some(value.to_vec()));
    }

    #[tokio::test]
    async fn test_set_overwrites_existing() {
        let cache = create_test_cache();
        let key = b"overwrite_key";

        cache
            .set(key, b"value1", Duration::from_secs(60))
            .await
            .unwrap();
        cache
            .set(key, b"value2", Duration::from_secs(60))
            .await
            .unwrap();

        let result = cache.get(key).await.unwrap();
        assert_eq!(result, Some(b"value2".to_vec()));
    }

    #[tokio::test]
    async fn test_del_nonexistent_key() {
        let cache = create_test_cache();
        // Should not error when deleting non-existent key
        let result = cache.del(b"nonexistent").await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_set_nx_px_after_delete() {
        let cache = create_test_cache();
        let key = b"deleted_nx_key";

        cache
            .set_nx_px(key, b"value1", Duration::from_secs(60))
            .await
            .unwrap();
        cache.del(key).await.unwrap();

        // Should succeed after deletion
        let was_set = cache
            .set_nx_px(key, b"value2", Duration::from_secs(60))
            .await
            .unwrap();
        assert!(was_set, "should succeed after deletion");

        let result = cache.get(key).await.unwrap();
        assert_eq!(result, Some(b"value2".to_vec()));
    }

    #[tokio::test]
    async fn test_contains_sync_after_delete() {
        let cache = create_test_cache();
        let key = b"contains_delete";

        cache
            .set(key, b"value", Duration::from_secs(60))
            .await
            .unwrap();
        assert!(cache.contains_sync(key));

        cache.del(key).await.unwrap();
        assert!(!cache.contains_sync(key));
    }

    // ==================== TTL Behavior ====================

    #[tokio::test]
    async fn test_zero_ttl_expires_immediately() {
        let cache = create_test_cache();
        let key = b"zero_ttl_key";

        cache.set(key, b"value", Duration::ZERO).await.unwrap();

        // Value should expire very quickly (or immediately)
        tokio::time::sleep(Duration::from_millis(10)).await;
        let result = cache.get(key).await.unwrap();
        assert!(result.is_none(), "zero TTL should expire immediately");
    }

    #[tokio::test]
    async fn test_very_long_ttl() {
        let cache = create_test_cache();
        let key = b"long_ttl_key";

        // Set with 1 hour TTL
        cache
            .set(key, b"value", Duration::from_secs(3600))
            .await
            .unwrap();

        // Should still exist
        let result = cache.get(key).await.unwrap();
        assert!(result.is_some());
    }

    // ==================== Concurrent Access ====================

    #[tokio::test]
    async fn test_concurrent_sets() {
        let cache = create_test_cache();
        let num_tasks = 100;

        let handles: Vec<_> = (0..num_tasks)
            .map(|i| {
                let cache = cache.clone();
                tokio::spawn(async move {
                    let key = format!("concurrent_key_{i}");
                    let value = format!("value_{i}");
                    cache
                        .set(key.as_bytes(), value.as_bytes(), Duration::from_secs(60))
                        .await
                        .unwrap();
                })
            })
            .collect();

        join_all(handles).await;

        // Verify all values are set
        for i in 0..num_tasks {
            let key = format!("concurrent_key_{i}");
            let expected = format!("value_{i}");
            let result = cache.get(key.as_bytes()).await.unwrap();
            assert_eq!(result, Some(expected.into_bytes()));
        }
    }

    #[tokio::test]
    async fn test_concurrent_set_nx_px_same_key() {
        let cache = create_test_cache();
        let key = b"race_key";
        let num_tasks = 100;

        let handles: Vec<_> = (0..num_tasks)
            .map(|i| {
                let cache = cache.clone();
                tokio::spawn(async move {
                    let value = format!("value_{i}");
                    cache
                        .set_nx_px(key, value.as_bytes(), Duration::from_secs(60))
                        .await
                        .unwrap()
                })
            })
            .collect();

        let results: Vec<bool> = join_all(handles)
            .await
            .into_iter()
            .map(|r| r.unwrap())
            .collect();

        // Exactly one should succeed (be true)
        let success_count = results.iter().filter(|&&x| x).count();
        assert_eq!(success_count, 1, "exactly one set_nx_px should succeed");
    }

    #[tokio::test]
    async fn test_concurrent_reads_and_writes() {
        let cache = create_test_cache();
        let key = b"rw_key";

        // Pre-populate
        cache
            .set(key, b"initial", Duration::from_secs(60))
            .await
            .unwrap();

        let mut handles = Vec::new();

        // Spawn readers
        for _ in 0..50 {
            let cache = cache.clone();
            handles.push(tokio::spawn(async move {
                let result = cache.get(key).await.unwrap();
                assert!(result.is_some());
            }));
        }

        // Spawn writers
        for i in 0..50 {
            let cache = cache.clone();
            handles.push(tokio::spawn(async move {
                let value = format!("value_{i}");
                cache
                    .set(key, value.as_bytes(), Duration::from_secs(60))
                    .await
                    .unwrap();
            }));
        }

        // All should complete without error
        for handle in join_all(handles).await {
            handle.unwrap();
        }
    }

    // ==================== Capacity ====================

    #[tokio::test]
    async fn test_capacity_limit() {
        // Create cache with small capacity
        // Note: Moka's eviction is asynchronous and may not happen immediately.
        // We use a slightly larger capacity and insert many more items to ensure
        // eviction eventually occurs.
        let cache = LocalCache::new(50, Duration::from_secs(60));

        // Insert significantly more items than capacity
        for i in 0..200 {
            let key = format!("cap_key_{i}");
            let value = format!("value_{i}");
            cache
                .set(key.as_bytes(), value.as_bytes(), Duration::from_secs(60))
                .await
                .unwrap();
        }

        // Give Moka time to run eviction - it processes evictions asynchronously
        tokio::time::sleep(Duration::from_millis(500)).await;

        // Count how many entries remain
        let mut count = 0;
        for i in 0..200 {
            let key = format!("cap_key_{i}");
            if cache.get(key.as_bytes()).await.unwrap().is_some() {
                count += 1;
            }
        }

        // Moka uses weighted eviction, so we just verify that some eviction occurred
        // We inserted 200 items into a cache with capacity 50, so we expect significant eviction
        assert!(
            count < 200,
            "cache should evict some entries when significantly over capacity, found {count} entries"
        );
    }

    // ==================== Clone Behavior ====================

    #[tokio::test]
    async fn test_clone_shares_state() {
        let cache1 = create_test_cache();
        let cache2 = cache1.clone();

        cache1
            .set(b"shared_key", b"value", Duration::from_secs(60))
            .await
            .unwrap();
        let result = cache2.get(b"shared_key").await.unwrap();

        assert_eq!(result, Some(b"value".to_vec()), "clones should share state");
    }

    #[tokio::test]
    async fn test_clone_delete_propagates() {
        let cache1 = create_test_cache();
        let cache2 = cache1.clone();

        cache1
            .set(b"shared_key", b"value", Duration::from_secs(60))
            .await
            .unwrap();
        cache2.del(b"shared_key").await.unwrap();

        let result = cache1.get(b"shared_key").await.unwrap();
        assert_eq!(result, None, "delete should propagate to clones");
    }

    // ==================== Stress Tests ====================

    #[tokio::test]
    async fn test_many_keys() {
        let cache = LocalCache::new(10_000, Duration::from_secs(60));
        let num_keys = 5000;

        // Insert many keys
        for i in 0..num_keys {
            let key = format!("key_{i:05}");
            let value = format!("value_{i:05}");
            cache
                .set(key.as_bytes(), value.as_bytes(), Duration::from_secs(60))
                .await
                .unwrap();
        }

        // Verify all keys exist
        for i in 0..num_keys {
            let key = format!("key_{i:05}");
            let expected = format!("value_{i:05}");
            let result = cache.get(key.as_bytes()).await.unwrap();
            assert_eq!(result, Some(expected.into_bytes()), "key {i} should exist");
        }
    }

    #[tokio::test]
    async fn test_rapid_set_get_cycles() {
        let cache = create_test_cache();
        let key = b"rapid_key";

        for i in 0..1000 {
            let value = format!("value_{i}");
            cache
                .set(key, value.as_bytes(), Duration::from_secs(60))
                .await
                .unwrap();
            let result = cache.get(key).await.unwrap();
            assert_eq!(result, Some(value.into_bytes()));
        }
    }
}

// ============================================================================
// RedisCache Namespace Tests (unit tests without real Redis)
// ============================================================================

mod redis_cache_namespace_tests {
    use std::borrow::Cow;

    /// Test the namespacing logic without actual Redis connection.
    /// We replicate the private `namespaced` method logic here for testing.
    fn namespaced<'a>(prefix: &str, key: &[u8], stack: &'a mut [u8; 96]) -> Cow<'a, [u8]> {
        let needed = prefix.len() + key.len();
        if needed <= stack.len() {
            let mut offset = 0;
            stack[..prefix.len()].copy_from_slice(prefix.as_bytes());
            offset += prefix.len();
            stack[offset..offset + key.len()].copy_from_slice(key);
            return Cow::Borrowed(&stack[..needed]);
        }
        let mut buf = Vec::with_capacity(needed);
        buf.extend_from_slice(prefix.as_bytes());
        buf.extend_from_slice(key);
        Cow::Owned(buf)
    }

    #[test]
    fn test_namespace_short_key() {
        let prefix = "myapp:";
        let key = b"mykey";
        let mut stack = [0u8; 96];

        let result = namespaced(prefix, key, &mut stack);

        assert!(
            matches!(result, Cow::Borrowed(_)),
            "should use stack buffer"
        );
        assert_eq!(result.as_ref(), b"myapp:mykey");
    }

    #[test]
    fn test_namespace_empty_prefix() {
        let prefix = "";
        let key = b"mykey";
        let mut stack = [0u8; 96];

        let result = namespaced(prefix, key, &mut stack);

        assert_eq!(result.as_ref(), b"mykey");
    }

    #[test]
    fn test_namespace_empty_key() {
        let prefix = "myapp:";
        let key = b"";
        let mut stack = [0u8; 96];

        let result = namespaced(prefix, key, &mut stack);

        assert_eq!(result.as_ref(), b"myapp:");
    }

    #[test]
    fn test_namespace_long_key_uses_heap() {
        let prefix = "myapp:";
        // Create key longer than 96 bytes
        let key: Vec<u8> = (0..100).map(|i| (i % 256) as u8).collect();
        let mut stack = [0u8; 96];

        let result = namespaced(prefix, &key, &mut stack);

        assert!(
            matches!(result, Cow::Owned(_)),
            "should use heap for long keys"
        );
        assert_eq!(result.len(), prefix.len() + key.len());
        assert!(result.starts_with(prefix.as_bytes()));
        assert!(result.ends_with(&key));
    }

    #[test]
    fn test_namespace_exactly_96_bytes() {
        let prefix = "prefix:"; // 7 bytes
        let key = vec![b'x'; 89]; // 89 bytes = total 96
        let mut stack = [0u8; 96];

        let result = namespaced(prefix, &key, &mut stack);

        assert!(
            matches!(result, Cow::Borrowed(_)),
            "exactly 96 bytes should use stack"
        );
        assert_eq!(result.len(), 96);
    }

    #[test]
    fn test_namespace_97_bytes_uses_heap() {
        let prefix = "prefix:"; // 7 bytes
        let key = vec![b'x'; 90]; // 90 bytes = total 97
        let mut stack = [0u8; 96];

        let result = namespaced(prefix, &key, &mut stack);

        assert!(matches!(result, Cow::Owned(_)), "97 bytes should use heap");
        assert_eq!(result.len(), 97);
    }

    #[test]
    fn test_namespace_binary_key() {
        let prefix = "bin:";
        let key: &[u8] = &[0x00, 0xFF, 0xDE, 0xAD, 0xBE, 0xEF];
        let mut stack = [0u8; 96];

        let result = namespaced(prefix, key, &mut stack);

        assert_eq!(&result[..4], b"bin:");
        assert_eq!(&result[4..], key);
    }
}

// ============================================================================
// Property-Based Tests
// ============================================================================

mod proptest_tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        /// Test that set followed by get always returns the same value
        #[test]
        fn prop_set_get_roundtrip(
            key in prop::collection::vec(any::<u8>(), 0..100),
            value in prop::collection::vec(any::<u8>(), 0..1000)
        ) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                let cache = LocalCache::new(1000, Duration::from_secs(60));

                cache.set(&key, &value, Duration::from_secs(60)).await.unwrap();
                let result = cache.get(&key).await.unwrap();

                prop_assert_eq!(result, Some(value));
                Ok(())
            })?;
        }

        /// Test that set_nx_px returns false on second call with same key
        #[test]
        fn prop_set_nx_px_idempotent(
            key in prop::collection::vec(any::<u8>(), 1..50),
            value1 in prop::collection::vec(any::<u8>(), 0..100),
            value2 in prop::collection::vec(any::<u8>(), 0..100)
        ) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                let cache = LocalCache::new(1000, Duration::from_secs(60));

                let first = cache.set_nx_px(&key, &value1, Duration::from_secs(60)).await.unwrap();
                let second = cache.set_nx_px(&key, &value2, Duration::from_secs(60)).await.unwrap();

                prop_assert!(first, "first set_nx_px should succeed");
                prop_assert!(!second, "second set_nx_px should fail");

                // Value should be the first one
                let result = cache.get(&key).await.unwrap();
                prop_assert_eq!(result, Some(value1));
                Ok(())
            })?;
        }

        /// Test that delete makes key unavailable
        #[test]
        fn prop_delete_removes_key(
            key in prop::collection::vec(any::<u8>(), 1..50),
            value in prop::collection::vec(any::<u8>(), 0..100)
        ) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                let cache = LocalCache::new(1000, Duration::from_secs(60));

                cache.set(&key, &value, Duration::from_secs(60)).await.unwrap();
                cache.del(&key).await.unwrap();
                let result = cache.get(&key).await.unwrap();

                prop_assert_eq!(result, None);
                Ok(())
            })?;
        }

        /// Test that contains_sync is consistent with get
        #[test]
        fn prop_contains_sync_consistent_with_get(
            key in prop::collection::vec(any::<u8>(), 1..50),
            value in prop::collection::vec(any::<u8>(), 0..100),
            should_set in any::<bool>()
        ) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                let cache = LocalCache::new(1000, Duration::from_secs(60));

                if should_set {
                    cache.set(&key, &value, Duration::from_secs(60)).await.unwrap();
                }

                let contains = cache.contains_sync(&key);
                let get_result = cache.get(&key).await.unwrap();

                prop_assert_eq!(contains, get_result.is_some());
                Ok(())
            })?;
        }

        /// Test that set overwrites previous value
        #[test]
        fn prop_set_overwrites(
            key in prop::collection::vec(any::<u8>(), 1..50),
            value1 in prop::collection::vec(any::<u8>(), 0..100),
            value2 in prop::collection::vec(any::<u8>(), 0..100)
        ) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                let cache = LocalCache::new(1000, Duration::from_secs(60));

                cache.set(&key, &value1, Duration::from_secs(60)).await.unwrap();
                cache.set(&key, &value2, Duration::from_secs(60)).await.unwrap();
                let result = cache.get(&key).await.unwrap();

                prop_assert_eq!(result, Some(value2));
                Ok(())
            })?;
        }

        /// Test that get on non-existent key returns None
        #[test]
        fn prop_get_nonexistent_returns_none(
            key in prop::collection::vec(any::<u8>(), 1..50)
        ) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                let cache = LocalCache::new(1000, Duration::from_secs(60));
                let result = cache.get(&key).await.unwrap();
                prop_assert_eq!(result, None);
                Ok(())
            })?;
        }

        /// Test namespace concatenation (unit test for the logic)
        #[test]
        fn prop_namespace_concatenation(
            prefix in "[a-z]{0,10}:",
            key in prop::collection::vec(any::<u8>(), 0..50)
        ) {
            let mut stack = [0u8; 96];
            let needed = prefix.len() + key.len();

            // Replicate namespaced logic
            let result: std::borrow::Cow<'_, [u8]> = if needed <= stack.len() {
                stack[..prefix.len()].copy_from_slice(prefix.as_bytes());
                stack[prefix.len()..needed].copy_from_slice(&key);
                std::borrow::Cow::Borrowed(&stack[..needed])
            } else {
                let mut buf = Vec::with_capacity(needed);
                buf.extend_from_slice(prefix.as_bytes());
                buf.extend_from_slice(&key);
                std::borrow::Cow::Owned(buf)
            };

            // Verify result is correct concatenation
            prop_assert_eq!(result.len(), needed);
            prop_assert!(result.starts_with(prefix.as_bytes()));
            prop_assert!(result.ends_with(&key));
        }
    }
}

// ============================================================================
// Cache Trait Invariant Tests
// ============================================================================

mod cache_trait_invariants {
    use super::*;

    /// Test that all Cache trait implementations behave consistently
    async fn test_cache_invariants<C: Cache>(cache: &C, prefix: &str) {
        let key = format!("{prefix}invariant_key").into_bytes();
        let value = b"invariant_value";

        // Invariant 1: get on non-existent key returns None
        let result = cache.get(&key).await.unwrap();
        assert_eq!(result, None, "{prefix}: get on new key should be None");

        // Invariant 2: set followed by get returns value
        cache
            .set(&key, value, Duration::from_secs(60))
            .await
            .unwrap();
        let result = cache.get(&key).await.unwrap();
        assert_eq!(
            result,
            Some(value.to_vec()),
            "{prefix}: set then get should return value"
        );

        // Invariant 3: del removes value
        cache.del(&key).await.unwrap();
        let result = cache.get(&key).await.unwrap();
        assert_eq!(result, None, "{prefix}: del should remove value");

        // Invariant 4: set_nx_px on new key succeeds
        let key2 = format!("{prefix}nx_key").into_bytes();
        let was_set = cache
            .set_nx_px(&key2, value, Duration::from_secs(60))
            .await
            .unwrap();
        assert!(was_set, "{prefix}: set_nx_px on new key should succeed");

        // Invariant 5: set_nx_px on existing key fails
        let was_set_again = cache
            .set_nx_px(&key2, b"other", Duration::from_secs(60))
            .await
            .unwrap();
        assert!(
            !was_set_again,
            "{prefix}: set_nx_px on existing key should fail"
        );

        // Invariant 6: value unchanged after failed set_nx_px
        let result = cache.get(&key2).await.unwrap();
        assert_eq!(
            result,
            Some(value.to_vec()),
            "{prefix}: value should be unchanged after failed set_nx_px"
        );
    }

    #[tokio::test]
    async fn test_local_cache_invariants() {
        let cache = LocalCache::new(1000, Duration::from_secs(60));
        test_cache_invariants(&cache, "local:").await;
    }
}

// ============================================================================
// Deduplication Pattern Tests
// ============================================================================

// ============================================================================
// Additional Coverage Tests (10 new tests for 80% coverage)
// ============================================================================

mod additional_coverage_tests {
    use super::*;
    use futures::future::join_all;

    // ==================== Test 1: test_contains_sync_direct ====================

    /// Direct sync check returns correct value for existing and non-existing keys
    #[tokio::test]
    async fn test_contains_sync_direct() {
        let cache = LocalCache::new(1000, Duration::from_secs(60));

        // Test on completely fresh cache - no key exists
        assert!(
            !cache.contains_sync(b"never_set_key"),
            "contains_sync should return false for never-set key"
        );

        // Set a key and verify contains_sync returns true
        cache
            .set(b"existing_key", b"value", Duration::from_secs(60))
            .await
            .unwrap();
        assert!(
            cache.contains_sync(b"existing_key"),
            "contains_sync should return true for existing key"
        );

        // Verify it still returns false for other keys
        assert!(
            !cache.contains_sync(b"other_key"),
            "contains_sync should return false for different key"
        );

        // Test with empty key
        cache
            .set(b"", b"empty_key_value", Duration::from_secs(60))
            .await
            .unwrap();
        assert!(
            cache.contains_sync(b""),
            "contains_sync should work with empty key"
        );
    }

    // ==================== Test 2: test_ttl_zero_immediate_expiry ====================

    /// TTL=0 expires immediately - entry should not be retrievable
    #[tokio::test]
    async fn test_ttl_zero_immediate_expiry() {
        let cache = LocalCache::new(1000, Duration::from_secs(60));
        let key = b"zero_ttl_immediate";

        // Set with Duration::ZERO
        cache.set(key, b"value", Duration::ZERO).await.unwrap();

        // Give minimal time for Moka to process expiry
        tokio::time::sleep(Duration::from_millis(5)).await;

        // Value should be expired
        let result = cache.get(key).await.unwrap();
        assert!(result.is_none(), "TTL=0 should cause immediate expiration");

        // contains_sync should also return false
        assert!(
            !cache.contains_sync(key),
            "contains_sync should return false after zero TTL expiry"
        );
    }

    // ==================== Test 3: test_ttl_max_value ====================

    /// Very long TTL values work correctly without causing issues
    #[tokio::test]
    async fn test_ttl_max_value() {
        let cache = LocalCache::new(1000, Duration::from_secs(86400 * 365 * 10)); // 10 years default
        let key = b"max_ttl_key";

        // Set with 1 year TTL - a very long but reasonable value
        // This tests that we handle long-lived cache entries properly
        let one_year = Duration::from_secs(86400 * 365);
        cache.set(key, b"long_lived_value", one_year).await.unwrap();

        // Value should exist
        let result = cache.get(key).await.unwrap();
        assert_eq!(
            result,
            Some(b"long_lived_value".to_vec()),
            "large TTL should not cause issues"
        );

        // Also test set_nx_px with large TTL
        let key2 = b"max_ttl_nx_key";
        let was_set = cache.set_nx_px(key2, b"value", one_year).await.unwrap();
        assert!(was_set, "set_nx_px with large TTL should succeed");

        let result2 = cache.get(key2).await.unwrap();
        assert!(result2.is_some(), "value should be retrievable");

        // Test with maximum safe TTL (100 years - still within Instant bounds)
        let key3 = b"century_ttl_key";
        let hundred_years = Duration::from_secs(86400 * 365 * 100);
        cache
            .set(key3, b"century_value", hundred_years)
            .await
            .unwrap();

        let result3 = cache.get(key3).await.unwrap();
        assert_eq!(
            result3,
            Some(b"century_value".to_vec()),
            "100 year TTL should work"
        );
    }

    // ==================== Test 4: test_very_long_key ====================

    /// Key >1KB works correctly
    #[tokio::test]
    async fn test_very_long_key() {
        let cache = LocalCache::new(1000, Duration::from_secs(60));

        // Create a key >1KB (1500 bytes)
        let long_key: Vec<u8> = (0..1500).map(|i| (i % 256) as u8).collect();
        let value = b"value_for_long_key";

        // Set and retrieve
        cache
            .set(&long_key, value, Duration::from_secs(60))
            .await
            .unwrap();

        let result = cache.get(&long_key).await.unwrap();
        assert_eq!(
            result,
            Some(value.to_vec()),
            "long key (>1KB) should work correctly"
        );

        // Test contains_sync with long key
        assert!(
            cache.contains_sync(&long_key),
            "contains_sync should work with long key"
        );

        // Test set_nx_px with long key
        let long_key2: Vec<u8> = (0..2000).map(|i| ((i + 100) % 256) as u8).collect();
        let was_set = cache
            .set_nx_px(&long_key2, b"nx_value", Duration::from_secs(60))
            .await
            .unwrap();
        assert!(was_set, "set_nx_px should work with long key");

        // Delete long key
        cache.del(&long_key).await.unwrap();
        assert!(
            !cache.contains_sync(&long_key),
            "delete should work with long key"
        );
    }

    // ==================== Test 5: test_concurrent_ttl_expiry ====================

    /// Race condition handling with multiple keys expiring concurrently
    #[tokio::test]
    async fn test_concurrent_ttl_expiry() {
        let cache = LocalCache::new(1000, Duration::from_secs(60));
        let num_keys = 100;
        let short_ttl = Duration::from_millis(50);

        // Set many keys with short TTL concurrently
        let handles: Vec<_> = (0..num_keys)
            .map(|i| {
                let cache = cache.clone();
                tokio::spawn(async move {
                    let key = format!("expiring_key_{i}");
                    let value = format!("value_{i}");
                    cache
                        .set(key.as_bytes(), value.as_bytes(), short_ttl)
                        .await
                        .unwrap();
                })
            })
            .collect();

        join_all(handles).await;

        // Verify all keys exist initially
        let mut initial_count = 0;
        for i in 0..num_keys {
            let key = format!("expiring_key_{i}");
            if cache.get(key.as_bytes()).await.unwrap().is_some() {
                initial_count += 1;
            }
        }
        assert!(initial_count > 0, "some keys should exist before expiry");

        // Wait for TTL expiration
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Concurrent reads after expiry
        let read_handles: Vec<_> = (0..num_keys)
            .map(|i| {
                let cache = cache.clone();
                tokio::spawn(async move {
                    let key = format!("expiring_key_{i}");
                    cache.get(key.as_bytes()).await.unwrap()
                })
            })
            .collect();

        let results: Vec<Option<Vec<u8>>> = join_all(read_handles)
            .await
            .into_iter()
            .map(|r| r.unwrap())
            .collect();

        // All should be expired
        let remaining = results.iter().filter(|r| r.is_some()).count();
        assert_eq!(
            remaining, 0,
            "all keys should be expired after TTL, found {remaining} remaining"
        );
    }

    // ==================== Test 6: test_cache_clone_drop ====================

    /// Behavior after clone drop - shared state persists
    #[tokio::test]
    async fn test_cache_clone_drop() {
        let cache1 = LocalCache::new(1000, Duration::from_secs(60));

        // Set value using cache1
        cache1
            .set(b"shared_key", b"shared_value", Duration::from_secs(60))
            .await
            .unwrap();

        // Create clone and drop it
        {
            let cache2 = cache1.clone();

            // Verify clone can read
            let result = cache2.get(b"shared_key").await.unwrap();
            assert_eq!(result, Some(b"shared_value".to_vec()));

            // Set another key via clone
            cache2
                .set(b"clone_key", b"clone_value", Duration::from_secs(60))
                .await
                .unwrap();

            // cache2 is dropped here
        }

        // Original cache should still work and see all data
        let result1 = cache1.get(b"shared_key").await.unwrap();
        assert_eq!(
            result1,
            Some(b"shared_value".to_vec()),
            "original key should persist after clone drop"
        );

        let result2 = cache1.get(b"clone_key").await.unwrap();
        assert_eq!(
            result2,
            Some(b"clone_value".to_vec()),
            "key set by dropped clone should persist"
        );

        // Create another clone and verify it sees all data
        let cache3 = cache1.clone();
        assert!(
            cache3.contains_sync(b"shared_key"),
            "new clone should see shared_key"
        );
        assert!(
            cache3.contains_sync(b"clone_key"),
            "new clone should see clone_key"
        );
    }

    // ==================== Test 7: test_set_nx_px_ttl_race ====================

    /// Concurrent `set_nx_px` with TTL - verify atomic behavior
    #[tokio::test]
    async fn test_set_nx_px_ttl_race() {
        let cache = LocalCache::new(1000, Duration::from_secs(60));
        let key = b"race_nx_ttl_key";
        let num_workers = 50;
        let short_ttl = Duration::from_millis(30);

        // First wave: concurrent set_nx_px
        let handles1: Vec<_> = (0..num_workers)
            .map(|i| {
                let cache = cache.clone();
                tokio::spawn(async move {
                    let value = format!("value_{i}");
                    cache
                        .set_nx_px(key, value.as_bytes(), short_ttl)
                        .await
                        .unwrap()
                })
            })
            .collect();

        let results1: Vec<bool> = join_all(handles1)
            .await
            .into_iter()
            .map(|r| r.unwrap())
            .collect();

        // Exactly one winner
        let winners1 = results1.iter().filter(|&&x| x).count();
        assert_eq!(
            winners1, 1,
            "exactly one set_nx_px should succeed in first wave"
        );

        // Wait for TTL to expire
        tokio::time::sleep(Duration::from_millis(60)).await;

        // Second wave: should be able to set again
        let handles2: Vec<_> = (0..num_workers)
            .map(|i| {
                let cache = cache.clone();
                tokio::spawn(async move {
                    let value = format!("new_value_{i}");
                    cache
                        .set_nx_px(key, value.as_bytes(), short_ttl)
                        .await
                        .unwrap()
                })
            })
            .collect();

        let results2: Vec<bool> = join_all(handles2)
            .await
            .into_iter()
            .map(|r| r.unwrap())
            .collect();

        // Again exactly one winner
        let winners2 = results2.iter().filter(|&&x| x).count();
        assert_eq!(
            winners2, 1,
            "exactly one set_nx_px should succeed in second wave after TTL expiry"
        );
    }

    // ==================== Test 8: test_local_cache_moka_eviction ====================

    /// Capacity eviction when cache is full
    #[tokio::test]
    async fn test_local_cache_moka_eviction() {
        // Create very small capacity cache
        let cache = LocalCache::new(10, Duration::from_secs(60));

        // Insert many more items than capacity
        for i in 0..100 {
            let key = format!("evict_key_{i:03}");
            let value = format!("value_{i:03}");
            cache
                .set(key.as_bytes(), value.as_bytes(), Duration::from_secs(60))
                .await
                .unwrap();
        }

        // Give Moka time to process evictions asynchronously
        tokio::time::sleep(Duration::from_millis(200)).await;

        // Count remaining entries
        let mut count = 0;
        for i in 0..100 {
            let key = format!("evict_key_{i:03}");
            if cache.get(key.as_bytes()).await.unwrap().is_some() {
                count += 1;
            }
        }

        // With capacity 10 and 100 inserts, significant eviction should occur
        // Moka may keep slightly more due to async eviction, but should be well under 100
        assert!(
            count <= 50,
            "cache should evict entries when over capacity, found {count} entries (expected <= 50)"
        );

        // Most recent entries should more likely be present (LRU-like behavior)
        // Check that at least some recent entries exist
        let mut recent_count = 0;
        for i in 90..100 {
            let key = format!("evict_key_{i:03}");
            if cache.get(key.as_bytes()).await.unwrap().is_some() {
                recent_count += 1;
            }
        }
        // Recent entries should have higher likelihood of being present
        // (though Moka uses TinyLFU, not pure LRU, so this is a soft check)
        assert!(
            recent_count > 0 || count > 0,
            "cache should have some entries present"
        );
    }

    // ==================== Test 9: test_redis_namespace_special_chars ====================

    /// Special characters in namespace are handled correctly
    #[test]
    fn test_redis_namespace_special_chars() {
        use std::borrow::Cow;

        // Replicate the namespaced logic for testing
        fn namespaced<'a>(prefix: &str, key: &[u8], stack: &'a mut [u8; 96]) -> Cow<'a, [u8]> {
            let needed = prefix.len() + key.len();
            if needed <= stack.len() {
                let mut offset = 0;
                stack[..prefix.len()].copy_from_slice(prefix.as_bytes());
                offset += prefix.len();
                stack[offset..offset + key.len()].copy_from_slice(key);
                return Cow::Borrowed(&stack[..needed]);
            }
            let mut buf = Vec::with_capacity(needed);
            buf.extend_from_slice(prefix.as_bytes());
            buf.extend_from_slice(key);
            Cow::Owned(buf)
        }

        // Test with colons (common in Redis)
        let mut stack = [0u8; 96];
        let result = namespaced("app:env:cache:", b"user:123", &mut stack);
        assert_eq!(result.as_ref(), b"app:env:cache:user:123");

        // Test with special characters
        let mut stack = [0u8; 96];
        let result = namespaced("ns-with-dashes_and_underscores:", b"key", &mut stack);
        assert_eq!(result.as_ref(), b"ns-with-dashes_and_underscores:key");

        // Test with unicode in prefix
        let mut stack = [0u8; 96];
        let result = namespaced("cache:", b"key", &mut stack);
        assert_eq!(result.as_ref(), b"cache:key");

        // Test with dots and slashes
        let mut stack = [0u8; 96];
        let result = namespaced("v1.0/api:", b"endpoint/resource", &mut stack);
        assert_eq!(result.as_ref(), b"v1.0/api:endpoint/resource");

        // Test with curly braces (Redis cluster hash tags)
        let mut stack = [0u8; 96];
        let result = namespaced("{hashtag}:", b"key", &mut stack);
        assert_eq!(result.as_ref(), b"{hashtag}:key");

        // Test with spaces (unusual but valid)
        let mut stack = [0u8; 96];
        let result = namespaced("my app: ", b"my key", &mut stack);
        assert_eq!(result.as_ref(), b"my app: my key");
    }

    // ==================== Test 10: test_redis_namespace_binary ====================

    /// Binary key data handling in namespace concatenation
    #[test]
    fn test_redis_namespace_binary() {
        use std::borrow::Cow;

        // Replicate the namespaced logic for testing
        fn namespaced<'a>(prefix: &str, key: &[u8], stack: &'a mut [u8; 96]) -> Cow<'a, [u8]> {
            let needed = prefix.len() + key.len();
            if needed <= stack.len() {
                let mut offset = 0;
                stack[..prefix.len()].copy_from_slice(prefix.as_bytes());
                offset += prefix.len();
                stack[offset..offset + key.len()].copy_from_slice(key);
                return Cow::Borrowed(&stack[..needed]);
            }
            let mut buf = Vec::with_capacity(needed);
            buf.extend_from_slice(prefix.as_bytes());
            buf.extend_from_slice(key);
            Cow::Owned(buf)
        }

        // Test with null bytes in key
        let mut stack = [0u8; 96];
        let binary_key: &[u8] = &[0x00, 0x01, 0x02, 0x00, 0xFF];
        let result = namespaced("bin:", binary_key, &mut stack);
        assert_eq!(&result[..4], b"bin:");
        assert_eq!(&result[4..], binary_key);
        assert_eq!(result.len(), 4 + binary_key.len());

        // Test with high bytes (0x80-0xFF)
        let mut stack = [0u8; 96];
        let high_bytes: &[u8] = &[0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0xFF];
        let result = namespaced("high:", high_bytes, &mut stack);
        assert_eq!(&result[..5], b"high:");
        assert_eq!(&result[5..], high_bytes);

        // Test with all zero bytes
        let mut stack = [0u8; 96];
        let zeros: &[u8] = &[0x00, 0x00, 0x00, 0x00];
        let result = namespaced("zeros:", zeros, &mut stack);
        assert_eq!(&result[..6], b"zeros:");
        assert_eq!(&result[6..], zeros);

        // Test with mixed ASCII and binary
        let mut stack = [0u8; 96];
        let mixed: &[u8] = &[b'a', 0x00, b'b', 0xFF, b'c'];
        let result = namespaced("mix:", mixed, &mut stack);
        assert_eq!(&result[..4], b"mix:");
        assert_eq!(&result[4..], mixed);

        // Test binary key that exceeds stack buffer (forces heap allocation)
        let mut stack = [0u8; 96];
        let long_binary: Vec<u8> = (0..100).map(|i| i as u8).collect();
        let result = namespaced("long:", &long_binary, &mut stack);
        assert!(
            matches!(result, Cow::Owned(_)),
            "should use heap for long binary key"
        );
        assert_eq!(&result[..5], b"long:");
        assert_eq!(&result[5..], long_binary.as_slice());

        // Verify binary data is preserved exactly
        let mut stack = [0u8; 96];
        let exact_binary: &[u8] = &[0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xBA, 0xBE];
        let result = namespaced("magic:", exact_binary, &mut stack);
        let expected: Vec<u8> = b"magic:"
            .iter()
            .chain(exact_binary.iter())
            .copied()
            .collect();
        assert_eq!(result.as_ref(), expected.as_slice());
    }
}

mod deduplication_tests {
    use super::*;
    use futures::future::join_all;

    /// Simulates the deduplication pattern used in mx-notifier
    #[tokio::test]
    async fn test_deduplication_pattern() {
        let cache = LocalCache::new(10_000, Duration::from_secs(300));

        // Simulate processing events with deduplication
        let event_ids: Vec<Vec<u8>> = (0..100)
            .map(|i| format!("event_{i}").into_bytes())
            .collect();

        let mut processed = Vec::new();

        for event_id in &event_ids {
            // Check if already processed using set_nx_px
            let is_new = cache
                .set_nx_px(event_id, b"1", Duration::from_secs(300))
                .await
                .unwrap();

            if is_new {
                processed.push(event_id.clone());
            }
        }

        // All events should be processed exactly once
        assert_eq!(processed.len(), 100);

        // Processing same events again should result in no new processing
        let mut reprocessed = Vec::new();
        for event_id in &event_ids {
            let is_new = cache
                .set_nx_px(event_id, b"1", Duration::from_secs(300))
                .await
                .unwrap();

            if is_new {
                reprocessed.push(event_id.clone());
            }
        }

        assert_eq!(reprocessed.len(), 0, "no events should be reprocessed");
    }

    /// Test concurrent deduplication (race condition handling)
    #[tokio::test]
    async fn test_concurrent_deduplication() {
        let cache = LocalCache::new(10_000, Duration::from_secs(300));

        // Same event ID processed by multiple concurrent tasks
        let event_id = b"duplicate_event";
        let num_workers = 50;

        let handles: Vec<_> = (0..num_workers)
            .map(|_| {
                let cache = cache.clone();
                tokio::spawn(async move {
                    cache
                        .set_nx_px(event_id, b"1", Duration::from_secs(300))
                        .await
                        .unwrap()
                })
            })
            .collect();

        let results: Vec<bool> = join_all(handles)
            .await
            .into_iter()
            .map(|r| r.unwrap())
            .collect();

        // Exactly one worker should successfully process
        let success_count = results.iter().filter(|&&x| x).count();
        assert_eq!(success_count, 1, "exactly one worker should win the race");
    }

    /// Test deduplication with TTL expiration
    #[tokio::test]
    async fn test_deduplication_with_expiration() {
        let cache = LocalCache::new(10_000, Duration::from_secs(60));
        let event_id = b"expiring_event";

        // Process with short TTL
        let first = cache
            .set_nx_px(event_id, b"1", Duration::from_millis(50))
            .await
            .unwrap();
        assert!(first, "first processing should succeed");

        // Wait for TTL to expire
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Should be able to process again after expiration
        let second = cache
            .set_nx_px(event_id, b"1", Duration::from_millis(50))
            .await
            .unwrap();
        assert!(second, "should be able to reprocess after expiration");
    }
}

// ============================================================================
// Mock Cache Tests - Testing Cache trait implementations
// ============================================================================

mod mock_cache_tests {
    use super::*;
    use crate::mock::MockCache;

    #[tokio::test]
    async fn test_mock_cache_trait_compliance() {
        let cache = MockCache::new();

        // Test all Cache trait methods
        cache
            .set(b"key1", b"value1", Duration::from_secs(60))
            .await
            .unwrap();

        let result = cache.get(b"key1").await.unwrap();
        assert_eq!(result, Some(b"value1".to_vec()));

        let was_set = cache
            .set_nx_px(b"key2", b"value2", Duration::from_secs(60))
            .await
            .unwrap();
        assert!(was_set);

        let was_set = cache
            .set_nx_px(b"key2", b"other", Duration::from_secs(60))
            .await
            .unwrap();
        assert!(!was_set);

        cache.del(b"key1").await.unwrap();
        let result = cache.get(b"key1").await.unwrap();
        assert_eq!(result, None);
    }

    #[tokio::test]
    async fn test_mock_cache_error_injection() {
        let cache = MockCache::new();

        // Set value before enabling error mode
        cache
            .set(b"key1", b"value1", Duration::from_secs(60))
            .await
            .unwrap();

        // Enable error mode
        cache.enable_error_mode("Simulated Redis failure");

        // All operations should fail
        let get_err = cache.get(b"key1").await;
        assert!(get_err.is_err());
        assert!(
            get_err
                .unwrap_err()
                .to_string()
                .contains("Simulated Redis failure")
        );

        let set_err = cache.set(b"key2", b"value2", Duration::from_secs(60)).await;
        assert!(set_err.is_err());

        let set_nx_err = cache
            .set_nx_px(b"key3", b"value3", Duration::from_secs(60))
            .await;
        assert!(set_nx_err.is_err());

        let del_err = cache.del(b"key1").await;
        assert!(del_err.is_err());

        // Disable error mode
        cache.disable_error_mode();

        // Operations should succeed again
        let result = cache.get(b"key1").await.unwrap();
        assert_eq!(result, Some(b"value1".to_vec()));
    }

    #[tokio::test]
    async fn test_mock_cache_operation_counting() {
        let cache = MockCache::new();

        cache
            .set(b"k1", b"v1", Duration::from_secs(60))
            .await
            .unwrap();
        cache
            .set(b"k2", b"v2", Duration::from_secs(60))
            .await
            .unwrap();
        cache.get(b"k1").await.unwrap();
        cache.get(b"k2").await.unwrap();
        cache.get(b"k3").await.unwrap();
        cache
            .set_nx_px(b"k4", b"v4", Duration::from_secs(60))
            .await
            .unwrap();
        cache
            .set_nx_px(b"k4", b"v5", Duration::from_secs(60))
            .await
            .unwrap();
        cache.del(b"k1").await.unwrap();

        let counts = cache.operation_counts();
        assert_eq!(counts.sets, 2, "should count 2 set operations");
        assert_eq!(counts.gets, 3, "should count 3 get operations");
        assert_eq!(counts.set_nx_px, 2, "should count 2 set_nx_px operations");
        assert_eq!(counts.deletes, 1, "should count 1 delete operation");

        // Reset and verify
        cache.reset_counts();
        let counts = cache.operation_counts();
        assert_eq!(counts.sets, 0);
        assert_eq!(counts.gets, 0);
        assert_eq!(counts.set_nx_px, 0);
        assert_eq!(counts.deletes, 0);
    }

    #[tokio::test]
    async fn test_mock_cache_ttl_behavior() {
        let cache = MockCache::new();

        // Set with short TTL
        cache
            .set(b"expiring", b"value", Duration::from_millis(50))
            .await
            .unwrap();

        // Should exist immediately
        let result = cache.get(b"expiring").await.unwrap();
        assert_eq!(result, Some(b"value".to_vec()));

        // Wait for expiration
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Should be expired
        let result = cache.get(b"expiring").await.unwrap();
        assert_eq!(result, None);
    }

    #[tokio::test]
    async fn test_mock_cache_force_expire() {
        let cache = MockCache::new();

        cache
            .set(b"key1", b"value1", Duration::from_secs(60))
            .await
            .unwrap();

        // Value exists
        assert!(cache.get(b"key1").await.unwrap().is_some());

        // Force expire
        cache.force_expire(b"key1");

        // Value should be gone
        assert!(cache.get(b"key1").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_mock_cache_with_preloaded_data() {
        let cache = MockCache::with_data([
            (b"preload1".as_slice(), b"value1".as_slice()),
            (b"preload2", b"value2"),
            (b"preload3", b"value3"),
        ]);

        assert_eq!(cache.len(), 3);

        let v1 = cache.get(b"preload1").await.unwrap();
        assert_eq!(v1, Some(b"value1".to_vec()));

        let v2 = cache.get(b"preload2").await.unwrap();
        assert_eq!(v2, Some(b"value2".to_vec()));

        let v3 = cache.get(b"preload3").await.unwrap();
        assert_eq!(v3, Some(b"value3".to_vec()));
    }

    #[tokio::test]
    async fn test_mock_cache_len_is_empty_clear() {
        let cache = MockCache::new();

        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);

        cache
            .set(b"k1", b"v1", Duration::from_secs(60))
            .await
            .unwrap();
        cache
            .set(b"k2", b"v2", Duration::from_secs(60))
            .await
            .unwrap();

        assert!(!cache.is_empty());
        assert_eq!(cache.len(), 2);

        cache.clear();

        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
    }

    #[tokio::test]
    async fn test_mock_cache_set_nx_px_on_expired_key() {
        let cache = MockCache::new();

        // Set with short TTL
        cache
            .set_nx_px(b"key", b"value1", Duration::from_millis(50))
            .await
            .unwrap();

        // Wait for expiration
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Should be able to set again since key expired
        let was_set = cache
            .set_nx_px(b"key", b"value2", Duration::from_secs(60))
            .await
            .unwrap();
        assert!(was_set, "should succeed on expired key");

        let result = cache.get(b"key").await.unwrap();
        assert_eq!(result, Some(b"value2".to_vec()));
    }
}

// ============================================================================
// Mock Set Tests
// ============================================================================

mod mock_set_tests {
    use crate::mock::MockSet;

    #[tokio::test]
    async fn test_mock_set_add_and_contains() {
        let set = MockSet::new();

        assert!(set.is_empty());
        assert!(!set.contains("item1"));

        set.add_item("item1").await.unwrap();
        set.add_item("item2").await.unwrap();

        assert_eq!(set.len(), 2);
        assert!(set.contains("item1"));
        assert!(set.contains("item2"));
        assert!(!set.contains("item3"));
    }

    #[tokio::test]
    async fn test_mock_set_remove() {
        let set = MockSet::new();

        set.add_item("item1").await.unwrap();
        set.add_item("item2").await.unwrap();

        assert_eq!(set.len(), 2);

        set.remove_item("item1").await.unwrap();

        assert_eq!(set.len(), 1);
        assert!(!set.contains("item1"));
        assert!(set.contains("item2"));
    }

    #[tokio::test]
    async fn test_mock_set_batch_operations() {
        let set = MockSet::new();

        set.add_items(&[
            "a".to_owned(),
            "b".to_owned(),
            "c".to_owned(),
            "d".to_owned(),
        ])
        .await
        .unwrap();

        assert_eq!(set.len(), 4);

        set.remove_items(&["a".to_owned(), "c".to_owned()])
            .await
            .unwrap();

        assert_eq!(set.len(), 2);
        assert!(!set.contains("a"));
        assert!(set.contains("b"));
        assert!(!set.contains("c"));
        assert!(set.contains("d"));
    }

    #[tokio::test]
    async fn test_mock_set_load_items() {
        let set = MockSet::new();

        set.add_items(&["x".to_owned(), "y".to_owned(), "z".to_owned()])
            .await
            .unwrap();

        let items = set.load_items().await.unwrap();
        assert_eq!(items.len(), 3);
        assert!(items.contains(&"x".to_owned()));
        assert!(items.contains(&"y".to_owned()));
        assert!(items.contains(&"z".to_owned()));
    }

    #[tokio::test]
    async fn test_mock_set_trim_to() {
        let set = MockSet::new();

        for i in 0..20 {
            set.add_item(&format!("item{i}")).await.unwrap();
        }

        assert_eq!(set.len(), 20);

        set.trim_to(10).await.unwrap();
        assert_eq!(set.len(), 10);

        set.trim_to(5).await.unwrap();
        assert_eq!(set.len(), 5);

        // trim_to(0) should do nothing
        set.trim_to(0).await.unwrap();
        assert_eq!(set.len(), 5);
    }

    #[tokio::test]
    async fn test_mock_set_error_mode() {
        let set = MockSet::new();

        set.add_item("item1").await.unwrap();

        set.enable_error_mode("Set operation failed");

        assert!(set.add_item("item2").await.is_err());
        assert!(set.remove_item("item1").await.is_err());
        assert!(set.load_items().await.is_err());
        assert!(set.trim_to(1).await.is_err());
        assert!(set.add_items(&["x".to_owned()]).await.is_err());
        assert!(set.remove_items(&["item1".to_owned()]).await.is_err());

        set.disable_error_mode();

        // Operations should work again
        let items = set.load_items().await.unwrap();
        assert!(items.contains(&"item1".to_owned()));
    }

    #[tokio::test]
    async fn test_mock_set_empty_operations() {
        let set = MockSet::new();

        // Empty batch operations should not error
        set.add_items(&[]).await.unwrap();
        set.remove_items(&[]).await.unwrap();

        assert!(set.is_empty());
    }

    #[tokio::test]
    async fn test_mock_set_clear() {
        let set = MockSet::new();

        set.add_items(&["a".to_owned(), "b".to_owned(), "c".to_owned()])
            .await
            .unwrap();

        assert_eq!(set.len(), 3);

        set.clear();

        assert!(set.is_empty());
        assert_eq!(set.len(), 0);
    }

    #[tokio::test]
    async fn test_mock_set_duplicate_add() {
        let set = MockSet::new();

        set.add_item("dup").await.unwrap();
        set.add_item("dup").await.unwrap();
        set.add_item("dup").await.unwrap();

        // Set should only have one entry (deduplication)
        assert_eq!(set.len(), 1);
    }
}

// ============================================================================
// Cache Trait Generic Tests with Mock
// ============================================================================

mod cache_trait_tests_with_mock {
    use super::*;
    use crate::mock::MockCache;

    /// Generic test function that can test any Cache implementation
    async fn verify_cache_contract<C: Cache>(cache: &C, test_name: &str) {
        let key1 = format!("{test_name}_key1").into_bytes();
        let key2 = format!("{test_name}_key2").into_bytes();
        let value1 = b"test_value_1";
        let value2 = b"test_value_2";

        // 1. Get on empty cache returns None
        let result = cache.get(&key1).await.unwrap();
        assert_eq!(result, None, "{test_name}: empty cache get should be None");

        // 2. Set then get returns value
        cache
            .set(&key1, value1, Duration::from_secs(60))
            .await
            .unwrap();
        let result = cache.get(&key1).await.unwrap();
        assert_eq!(
            result,
            Some(value1.to_vec()),
            "{test_name}: set-get roundtrip"
        );

        // 3. Set overwrites
        cache
            .set(&key1, value2, Duration::from_secs(60))
            .await
            .unwrap();
        let result = cache.get(&key1).await.unwrap();
        assert_eq!(
            result,
            Some(value2.to_vec()),
            "{test_name}: set should overwrite"
        );

        // 4. Delete removes key
        cache.del(&key1).await.unwrap();
        let result = cache.get(&key1).await.unwrap();
        assert_eq!(result, None, "{test_name}: del should remove key");

        // 5. set_nx_px on new key succeeds
        let was_set = cache
            .set_nx_px(&key2, value1, Duration::from_secs(60))
            .await
            .unwrap();
        assert!(was_set, "{test_name}: set_nx_px on new key should succeed");

        // 6. set_nx_px on existing key fails
        let was_set = cache
            .set_nx_px(&key2, value2, Duration::from_secs(60))
            .await
            .unwrap();
        assert!(
            !was_set,
            "{test_name}: set_nx_px on existing key should fail"
        );

        // 7. Value unchanged after failed set_nx_px
        let result = cache.get(&key2).await.unwrap();
        assert_eq!(
            result,
            Some(value1.to_vec()),
            "{test_name}: value should be unchanged after failed set_nx_px"
        );
    }

    #[tokio::test]
    async fn test_local_cache_contract() {
        let cache = LocalCache::new(1000, Duration::from_secs(60));
        verify_cache_contract(&cache, "local").await;
    }

    #[tokio::test]
    async fn test_mock_cache_contract() {
        let cache = MockCache::new();
        verify_cache_contract(&cache, "mock").await;
    }

    #[tokio::test]
    async fn test_both_caches_same_behavior() {
        let local = LocalCache::new(1000, Duration::from_secs(60));
        let mock = MockCache::new();

        // Test identical sequences
        let test_keys: Vec<&[u8]> = vec![b"k1", b"k2", b"k3"];
        let test_values: Vec<&[u8]> = vec![b"v1", b"v2", b"v3"];

        for (key, value) in test_keys.iter().zip(test_values.iter()) {
            local
                .set(key, value, Duration::from_secs(60))
                .await
                .unwrap();
            mock.set(key, value, Duration::from_secs(60)).await.unwrap();

            let local_result = local.get(key).await.unwrap();
            let mock_result = mock.get(key).await.unwrap();

            assert_eq!(
                local_result, mock_result,
                "Local and Mock should behave identically"
            );
        }
    }
}

// ============================================================================
// LocalCache Debug Implementation Test
// ============================================================================

mod local_cache_debug_tests {
    use super::*;

    #[test]
    fn test_local_cache_debug() {
        let cache = LocalCache::new(100, Duration::from_secs(60));
        let debug_str = format!("{cache:?}");

        assert!(debug_str.contains("LocalCache"));
        assert!(debug_str.contains("inner"));
    }

    #[tokio::test]
    async fn test_local_cache_clone_is_debug() {
        let cache1 = LocalCache::new(100, Duration::from_secs(60));
        cache1
            .set(b"key", b"value", Duration::from_secs(60))
            .await
            .unwrap();

        let cache2 = cache1.clone();
        let debug1 = format!("{cache1:?}");
        let debug2 = format!("{cache2:?}");

        // Both should be debuggable
        assert!(debug1.contains("LocalCache"));
        assert!(debug2.contains("LocalCache"));
    }
}

// ============================================================================
// PerEntryExpiry Tests - Testing internal expiry behavior
// ============================================================================

mod per_entry_expiry_tests {
    use super::*;

    /// Test that TTL update changes expiration time
    #[tokio::test]
    async fn test_ttl_update_on_overwrite() {
        let cache = LocalCache::new(1000, Duration::from_secs(60));
        let key = b"ttl_update_key";

        // Set with short TTL
        cache
            .set(key, b"value1", Duration::from_millis(50))
            .await
            .unwrap();

        // Immediately overwrite with longer TTL
        cache
            .set(key, b"value2", Duration::from_secs(60))
            .await
            .unwrap();

        // Wait past original TTL
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Should still exist because TTL was updated
        let result = cache.get(key).await.unwrap();
        assert_eq!(
            result,
            Some(b"value2".to_vec()),
            "TTL should be updated on overwrite"
        );
    }

    /// Test multiple TTL updates
    #[tokio::test]
    async fn test_multiple_ttl_updates() {
        let cache = LocalCache::new(1000, Duration::from_secs(60));
        let key = b"multi_ttl_key";

        // Chain of sets with different TTLs
        cache
            .set(key, b"v1", Duration::from_millis(10))
            .await
            .unwrap();
        cache
            .set(key, b"v2", Duration::from_millis(20))
            .await
            .unwrap();
        cache
            .set(key, b"v3", Duration::from_millis(30))
            .await
            .unwrap();
        cache
            .set(key, b"v4", Duration::from_secs(60))
            .await
            .unwrap();

        // Wait past all short TTLs
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Should still exist with latest TTL
        let result = cache.get(key).await.unwrap();
        assert_eq!(result, Some(b"v4".to_vec()));
    }

    /// Test that reads don't extend TTL
    #[tokio::test]
    async fn test_read_does_not_extend_ttl() {
        let cache = LocalCache::new(1000, Duration::from_secs(60));
        let key = b"no_extend_key";

        cache
            .set(key, b"value", Duration::from_millis(100))
            .await
            .unwrap();

        // Read multiple times
        for _ in 0..10 {
            let _ = cache.get(key).await.unwrap();
            tokio::time::sleep(Duration::from_millis(10)).await;
        }

        // Should expire after ~100ms regardless of reads
        tokio::time::sleep(Duration::from_millis(50)).await;

        let result = cache.get(key).await.unwrap();
        assert_eq!(result, None, "reads should not extend TTL");
    }

    /// Test expiry behavior with very short TTLs
    #[tokio::test]
    async fn test_very_short_ttl_variations() {
        let cache = LocalCache::new(1000, Duration::from_secs(60));

        // Test 1ms TTL
        cache
            .set(b"1ms", b"value", Duration::from_millis(1))
            .await
            .unwrap();

        // Test 5ms TTL
        cache
            .set(b"5ms", b"value", Duration::from_millis(5))
            .await
            .unwrap();

        // Test 10ms TTL
        cache
            .set(b"10ms", b"value", Duration::from_millis(10))
            .await
            .unwrap();

        // Wait 20ms - all should be expired
        tokio::time::sleep(Duration::from_millis(20)).await;

        assert!(cache.get(b"1ms").await.unwrap().is_none());
        assert!(cache.get(b"5ms").await.unwrap().is_none());
        assert!(cache.get(b"10ms").await.unwrap().is_none());
    }
}

// ============================================================================
// Minimum Capacity Tests
// ============================================================================

mod minimum_capacity_tests {
    use super::*;

    #[tokio::test]
    async fn test_capacity_zero_becomes_one() {
        // LocalCache::new uses max(1, capacity), so capacity 0 becomes 1
        let cache = LocalCache::new(0, Duration::from_secs(60));

        // Should still work
        cache
            .set(b"key", b"value", Duration::from_secs(60))
            .await
            .unwrap();
        let result = cache.get(b"key").await.unwrap();
        assert_eq!(result, Some(b"value".to_vec()));
    }

    #[tokio::test]
    async fn test_capacity_one() {
        let cache = LocalCache::new(1, Duration::from_secs(60));

        cache
            .set(b"k1", b"v1", Duration::from_secs(60))
            .await
            .unwrap();

        // Moka's eviction is async, so we might briefly have both
        // But eventually one should be evicted
        cache
            .set(b"k2", b"v2", Duration::from_secs(60))
            .await
            .unwrap();

        // Give time for eviction
        tokio::time::sleep(Duration::from_millis(100)).await;

        // At least k2 should exist
        let k2_result = cache.get(b"k2").await.unwrap();
        assert_eq!(k2_result, Some(b"v2".to_vec()));
    }
}

// ============================================================================
// Default TTL Boundary Tests
// ============================================================================

mod default_ttl_tests {
    use super::*;

    #[tokio::test]
    async fn test_per_entry_ttl_shorter_than_default() {
        // Cache with 10 second default TTL
        let cache = LocalCache::new(1000, Duration::from_secs(10));

        // Set with 50ms TTL (shorter than default)
        cache
            .set(b"short", b"value", Duration::from_millis(50))
            .await
            .unwrap();

        // Should exist immediately
        assert!(cache.get(b"short").await.unwrap().is_some());

        // Wait for per-entry TTL to expire
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Should be expired (per-entry TTL takes precedence)
        assert!(cache.get(b"short").await.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_per_entry_ttl_longer_than_default() {
        // Cache with very short default TTL (but Moka also respects per-entry expiry)
        let cache = LocalCache::new(1000, Duration::from_millis(50));

        // Set with longer per-entry TTL
        cache
            .set(b"long", b"value", Duration::from_secs(60))
            .await
            .unwrap();

        // Wait past default TTL
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Per-entry TTL should still be honored
        // Note: Moka's behavior here depends on configuration
        // The time_to_live sets an upper bound
        let result = cache.get(b"long").await.unwrap();

        // This might be None or Some depending on how Moka handles the conflict
        // The important thing is it doesn't crash
        if result.is_none() {
            // Default TTL took precedence - this is acceptable behavior
        } else {
            // Per-entry TTL took precedence - also acceptable
            assert_eq!(result, Some(b"value".to_vec()));
        }
    }
}

// ============================================================================
// Error Message Tests
// ============================================================================

mod error_message_tests {
    use crate::Cache;
    use crate::mock::MockCache;
    use std::time::Duration;

    #[tokio::test]
    async fn test_error_message_preservation() {
        let cache = MockCache::new();

        let custom_error = "Custom error: connection refused (host: localhost:6379)";
        cache.enable_error_mode(custom_error);

        let err = cache.get(b"key").await.unwrap_err();
        let err_msg = err.to_string();

        assert!(err_msg.contains("connection refused"));
        assert!(err_msg.contains("localhost:6379"));
    }

    #[tokio::test]
    async fn test_multiple_error_mode_switches() {
        let cache = MockCache::new();

        // Start with no error
        cache
            .set(b"k1", b"v1", Duration::from_secs(60))
            .await
            .unwrap();

        // Enable error
        cache.enable_error_mode("error 1");
        assert!(cache.get(b"k1").await.is_err());

        // Disable
        cache.disable_error_mode();
        assert!(cache.get(b"k1").await.is_ok());

        // Enable different error
        cache.enable_error_mode("error 2");
        let err = cache.get(b"k1").await.unwrap_err();
        assert!(err.to_string().contains("error 2"));

        // Disable again
        cache.disable_error_mode();
        assert_eq!(cache.get(b"k1").await.unwrap(), Some(b"v1".to_vec()));
    }
}