cachekit 0.7.0

High-performance cache primitives with pluggable eviction policies (LRU, LFU, FIFO, 2Q, Clock-PRO, S3-FIFO) and optional metrics.
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
//! Two-Queue (2Q) cache replacement policy.
//!
//! Implements the 2Q algorithm, which separates recently inserted items from
//! frequently accessed items using two queues. This provides scan resistance
//! by preventing one-time accesses from polluting the main cache.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────────────┐
//! │                           TwoQCore<K, V> Layout                             │
//! │                                                                             │
//! │   ┌─────────────────────────────────────────────────────────────────────┐   │
//! │   │  index: HashMapStore<K, SlotId>    store: SlotArena<Entry<K,V>>     │   │
//! │   │                                                                     │   │
//! │   │  ┌──────────┬──────────┐           ┌────────┬──────────────────┐    │   │
//! │   │  │   Key    │  SlotId  │           │ SlotId │ Entry            │    │   │
//! │   │  ├──────────┼──────────┤           ├────────┼──────────────────┤    │   │
//! │   │  │  "page1" │   id_0   │──────────►│  id_0  │ key,val,Probation│    │   │
//! │   │  │  "page2" │   id_1   │──────────►│  id_1  │ key,val,Protected│    │   │
//! │   │  │  "page3" │   id_2   │──────────►│  id_2  │ key,val,Probation│    │   │
//! │   │  └──────────┴──────────┘           └────────┴──────────────────┘    │   │
//! │   └─────────────────────────────────────────────────────────────────────┘   │
//! │                                                                             │
//! │   ┌─────────────────────────────────────────────────────────────────────┐   │
//! │   │                        Queue Organization                           │   │
//! │   │                                                                     │   │
//! │   │   PROBATION QUEUE (A1in - FIFO)          PROTECTED QUEUE (Am - LRU) │   │
//! │   │   ┌─────────────────────────┐            ┌─────────────────────────┐│   │
//! │   │   │ front               back│            │ MRU                 LRU ││   │
//! │   │   │  ▼                    ▼ │            │  ▼                   ▼  ││   │
//! │   │   │ [id_2] ◄──► [id_0] ◄──┤ │            │ [id_1] ◄──► [...] ◄──┤  ││   │
//! │   │   │  new        older  evict│            │ hot          cold  evict││   │
//! │   │   └─────────────────────────┘            └─────────────────────────┘│   │
//! │   │                                                                     │   │
//! │   │   • New items enter probation FIFO                                  │   │
//! │   │   • Re-access promotes to protected LRU                             │   │
//! │   │   • Eviction: probation first (if over cap), then protected LRU     │   │
//! │   └─────────────────────────────────────────────────────────────────────┘   │
//! │                                                                             │
//! └─────────────────────────────────────────────────────────────────────────────┘
//!
//! Insert Flow (new key)
//! ──────────────────────
//!
//!   insert("new_key", value):
//!     1. Check index - not found
//!     2. Create Entry with QueueKind::Probation
//!     3. Insert into store → get SlotId
//!     4. Insert key→SlotId into index
//!     5. Push SlotId to back of probation queue
//!     6. Evict if over capacity
//!
//! Access Flow (existing key)
//! ──────────────────────────
//!
//!   get("existing_key"):
//!     1. Lookup SlotId in index
//!     2. Check entry's queue kind:
//!        - If Probation: promote to Protected (move to protected MRU)
//!        - If Protected: move to MRU position
//!     3. Return &value
//!
//! Eviction Flow
//! ─────────────
//!
//!   evict_if_needed():
//!     while len > protected_cap:
//!       if probation.len > probation_cap:
//!         evict from probation front (oldest)
//!       else:
//!         evict from protected back (LRU)
//! ```
//!
//! ## Key Components
//!
//! - [`TwoQCore`]: Main 2Q cache implementation
//!
//! ## Operations
//!
//! | Operation   | Time   | Notes                                      |
//! |-------------|--------|--------------------------------------------|
//! | `get`       | O(1)   | May promote from probation to protected    |
//! | `insert`    | O(1)*  | *Amortized, may trigger evictions          |
//! | `contains`  | O(1)   | Index lookup only                          |
//! | `len`       | O(1)   | Returns total entries                      |
//! | `clear`     | O(n)   | Clears all structures                      |
//!
//! ## Algorithm Properties
//!
//! - **Scan Resistance**: One-time accesses stay in probation, don't pollute protected
//! - **Frequency Awareness**: Repeated access promotes to protected LRU
//! - **Tunable**: `a1_frac` controls probation/protected size ratio
//!
//! ## Use Cases
//!
//! - Database buffer pools (scan-heavy workloads)
//! - File system caches
//! - Web caches with mixed access patterns
//!
//! ## Example Usage
//!
//! ```
//! use cachekit::policy::two_q::TwoQCore;
//!
//! // Create 2Q cache: 100 total capacity, 25% for probation
//! let mut cache = TwoQCore::new(100, 0.25);
//!
//! // Insert items (go to probation)
//! cache.insert("page1", "content1");
//! cache.insert("page2", "content2");
//!
//! // First access promotes to protected
//! assert_eq!(cache.get(&"page1"), Some(&"content1"));
//!
//! // Second access keeps in protected (MRU position)
//! assert_eq!(cache.get(&"page1"), Some(&"content1"));
//!
//! assert_eq!(cache.len(), 2);
//! ```
//!
//! ## Thread Safety
//!
//! - [`TwoQCore`]: Not thread-safe, designed for single-threaded use
//! - For concurrent access, wrap in external synchronization
//!
//! ## Implementation Notes
//!
//! - Probation uses FIFO ordering (push back, evict front)
//! - Protected uses LRU ordering (MRU at front, evict from back)
//! - Promotion from probation to protected happens on re-access
//! - Default `a1_frac` of 0.25 means 25% of capacity for probation
//!
//! ## References
//!
//! - Johnson & Shasha, "2Q: A Low Overhead High Performance Buffer Management
//!   Replacement Algorithm", VLDB 1994

use crate::ds::{IntrusiveList, SlotId};
#[cfg(feature = "metrics")]
use crate::metrics::metrics_impl::TwoQMetrics;
#[cfg(feature = "metrics")]
use crate::metrics::snapshot::TwoQMetricsSnapshot;
#[cfg(feature = "metrics")]
use crate::metrics::traits::{CoreMetricsRecorder, MetricsSnapshotProvider, TwoQMetricsRecorder};
use crate::traits::Cache;
use rustc_hash::FxHashMap;
use std::collections::VecDeque;
use std::hash::Hash;
use std::ptr::NonNull;

/// Indicates which queue an entry resides in.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum QueueKind {
    /// Entry is in the probation (A1in) FIFO queue.
    Probation,
    /// Entry is in the protected (Am) LRU queue.
    Protected,
}

/// Node in the optimized 2Q linked list.
///
/// Cache-line optimized layout with pointers first.
#[repr(C)]
struct Node<K, V> {
    prev: Option<NonNull<Node<K, V>>>,
    next: Option<NonNull<Node<K, V>>>,
    queue: QueueKind,
    key: K,
    value: V,
}

/// LRU queue backed by an intrusive doubly-linked list.
///
/// Provides O(1) insert, touch (move to front), and evict (pop back) operations.
/// Used for the protected queue in 2Q where access frequency matters.
#[derive(Debug)]
#[allow(dead_code)]
pub(crate) struct LruQueue<T> {
    list: IntrusiveList<T>,
}

/// Two-Queue cache with ghost list for tracking evicted keys.
///
/// Extends [`TwoQCore`] with a ghost list that remembers recently evicted keys.
/// This allows detecting when a previously evicted key is re-accessed, which
/// can be used for adaptive tuning or admission decisions.
///
/// # Type Parameters
///
/// - `K`: Key type, must be `Clone + Eq + Hash`
/// - `V`: Value type
#[allow(dead_code)]
pub(crate) struct TwoQWithGhost<K, V> {
    core: TwoQCore<K, V>,
    ghost_list: VecDeque<K>,
    ghost_list_cap: usize,
}

impl<K, V> std::fmt::Debug for TwoQWithGhost<K, V>
where
    K: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TwoQWithGhost")
            .field("core", &self.core)
            .field("ghost_list_len", &self.ghost_list.len())
            .field("ghost_list_cap", &self.ghost_list_cap)
            .finish()
    }
}

/// Core Two-Queue (2Q) cache implementation.
///
/// Implements the 2Q replacement algorithm with two queues:
/// - **Probation (A1in)**: FIFO queue for newly inserted items
/// - **Protected (Am)**: LRU queue for frequently accessed items
///
/// New items enter probation. Re-accessing an item in probation promotes it
/// to protected. This provides scan resistance by keeping one-time accesses
/// from polluting the main cache.
///
/// # Type Parameters
///
/// - `K`: Key type, must be `Clone + Eq + Hash`
/// - `V`: Value type
///
/// # Example
///
/// ```
/// use cachekit::policy::two_q::TwoQCore;
///
/// // 100 capacity, 25% probation
/// let mut cache = TwoQCore::new(100, 0.25);
///
/// // Insert goes to probation
/// cache.insert("key1", "value1");
/// assert!(cache.contains(&"key1"));
///
/// // First get promotes to protected
/// cache.get(&"key1");
///
/// // Update existing key
/// cache.insert("key1", "new_value");
/// assert_eq!(cache.get(&"key1"), Some(&"new_value"));
/// ```
///
/// # Eviction Behavior
///
/// When capacity is exceeded:
/// 1. If probation exceeds its cap, evict from probation front (oldest)
/// 2. Otherwise, evict from protected back (LRU)
///
/// # Implementation
///
/// Uses raw pointer linked lists for O(1) operations with minimal overhead.
pub struct TwoQCore<K, V> {
    /// Direct key -> node pointer mapping
    map: FxHashMap<K, NonNull<Node<K, V>>>,

    /// Probation queue (FIFO): head=newest, tail=oldest
    probation_head: Option<NonNull<Node<K, V>>>,
    probation_tail: Option<NonNull<Node<K, V>>>,
    probation_len: usize,

    /// Protected queue (LRU): head=MRU, tail=LRU
    protected_head: Option<NonNull<Node<K, V>>>,
    protected_tail: Option<NonNull<Node<K, V>>>,
    protected_len: usize,

    /// Maximum size of the probation queue.
    probation_cap: usize,
    /// Maximum total cache capacity.
    protected_cap: usize,

    #[cfg(feature = "metrics")]
    metrics: TwoQMetrics,
}

// SAFETY: The raw pointers in the linked list are owned exclusively by TwoQCore.
unsafe impl<K, V> Send for TwoQCore<K, V>
where
    K: Send,
    V: Send,
{
}

// SAFETY: The raw pointers in the linked list are owned exclusively by TwoQCore.
unsafe impl<K, V> Sync for TwoQCore<K, V>
where
    K: Sync,
    V: Sync,
{
}

impl<T> Default for LruQueue<T> {
    fn default() -> Self {
        Self::new()
    }
}

#[allow(dead_code)]
impl<T> LruQueue<T> {
    /// Creates an empty LRU queue.
    #[must_use]
    pub fn new() -> Self {
        Self {
            list: IntrusiveList::new(),
        }
    }

    /// Creates an LRU queue with pre-allocated capacity.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            list: IntrusiveList::with_capacity(capacity),
        }
    }

    /// Returns `true` if the queue is empty.
    pub fn is_empty(&self) -> bool {
        self.list.len() == 0
    }

    /// Inserts an item at the MRU position (front), returning its [`SlotId`].
    pub fn insert(&mut self, id: T) -> SlotId {
        // new item is most-recently-used
        self.list.push_front(id)
    }

    /// Moves an item to the MRU position (front).
    ///
    /// Returns `true` if the item was found and moved.
    pub fn touch(&mut self, id: SlotId) -> bool {
        // move accessed item to MRU position
        self.list.move_to_front(id)
    }

    /// Removes and returns the LRU item (from back).
    pub fn evict(&mut self) -> Option<T> {
        // remove least-recently-used
        self.list.pop_back()
    }

    /// Removes an item by its [`SlotId`].
    pub fn remove(&mut self, id: SlotId) -> Option<T> {
        self.list.remove(id)
    }

    /// Returns the number of items in the queue.
    pub fn len(&self) -> usize {
        self.list.len()
    }

    /// Alias for [`insert`](Self::insert).
    pub fn push_front(&mut self, id: T) -> SlotId {
        self.list.push_front(id)
    }

    /// Alias for [`touch`](Self::touch).
    pub fn move_to_front(&mut self, id: SlotId) -> bool {
        self.list.move_to_front(id)
    }

    /// Alias for [`evict`](Self::evict).
    pub fn pop_back(&mut self) -> Option<T> {
        self.list.pop_back()
    }
}

/// Linked-list cleanup helpers — no key trait bounds needed.
/// Kept in an unbounded block so `Drop` can call them without
/// requiring `K: Clone + Eq + Hash` on the struct definition.
impl<K, V> TwoQCore<K, V> {
    #[inline(always)]
    fn pop_probation_tail(&mut self) -> Option<Box<Node<K, V>>> {
        self.probation_tail.map(|tail_ptr| unsafe {
            let node = Box::from_raw(tail_ptr.as_ptr());

            self.probation_tail = node.prev;
            match self.probation_tail {
                Some(mut t) => t.as_mut().next = None,
                None => self.probation_head = None,
            }
            self.probation_len -= 1;

            node
        })
    }

    #[inline(always)]
    fn pop_protected_tail(&mut self) -> Option<Box<Node<K, V>>> {
        self.protected_tail.map(|tail_ptr| unsafe {
            let node = Box::from_raw(tail_ptr.as_ptr());

            self.protected_tail = node.prev;
            match self.protected_tail {
                Some(mut t) => t.as_mut().next = None,
                None => self.protected_head = None,
            }
            self.protected_len -= 1;

            node
        })
    }
}

impl<K, V> TwoQCore<K, V>
where
    K: Clone + Eq + Hash,
{
    /// Creates a new 2Q cache with the specified capacity and probation fraction.
    ///
    /// - `protected_cap`: Total cache capacity (maximum number of entries)
    /// - `a1_frac`: Fraction of capacity allocated to probation queue (0.0 to 1.0)
    ///
    /// A typical value for `a1_frac` is 0.25 (25% for probation).
    ///
    /// # Panics
    ///
    /// Panics if `a1_frac` is negative, NaN, or greater than 1.0.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::two_q::TwoQCore;
    ///
    /// // 100 capacity, 25% probation (25 items max in probation)
    /// let cache: TwoQCore<String, i32> = TwoQCore::new(100, 0.25);
    /// assert_eq!(cache.capacity(), 100);
    /// assert!(cache.is_empty());
    /// ```
    #[inline]
    #[must_use]
    pub fn new(protected_cap: usize, a1_frac: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&a1_frac),
            "a1_frac must be between 0.0 and 1.0, got {a1_frac}"
        );
        let probation_cap = (protected_cap as f64 * a1_frac) as usize;
        let total_cap = protected_cap + probation_cap;

        Self {
            map: FxHashMap::with_capacity_and_hasher(total_cap, Default::default()),
            probation_head: None,
            probation_tail: None,
            probation_len: 0,
            protected_head: None,
            protected_tail: None,
            protected_len: 0,
            probation_cap,
            protected_cap,
            #[cfg(feature = "metrics")]
            metrics: TwoQMetrics::default(),
        }
    }

    /// Detach a node from its current queue.
    #[inline(always)]
    fn detach(&mut self, node_ptr: NonNull<Node<K, V>>) {
        unsafe {
            let node = node_ptr.as_ref();
            let prev = node.prev;
            let next = node.next;
            let queue = node.queue;

            let (head, tail, len) = match queue {
                QueueKind::Probation => (
                    &mut self.probation_head,
                    &mut self.probation_tail,
                    &mut self.probation_len,
                ),
                QueueKind::Protected => (
                    &mut self.protected_head,
                    &mut self.protected_tail,
                    &mut self.protected_len,
                ),
            };

            match prev {
                Some(mut p) => p.as_mut().next = next,
                None => *head = next,
            }

            match next {
                Some(mut n) => n.as_mut().prev = prev,
                None => *tail = prev,
            }

            *len -= 1;
        }
    }

    /// Attach a node at the head of probation queue (FIFO: new items at head).
    #[inline(always)]
    fn attach_probation_head(&mut self, mut node_ptr: NonNull<Node<K, V>>) {
        unsafe {
            let node = node_ptr.as_mut();
            node.prev = None;
            node.next = self.probation_head;
            node.queue = QueueKind::Probation;

            match self.probation_head {
                Some(mut h) => h.as_mut().prev = Some(node_ptr),
                None => self.probation_tail = Some(node_ptr),
            }

            self.probation_head = Some(node_ptr);
            self.probation_len += 1;
        }
    }

    /// Attach a node at the head of protected queue (LRU: MRU at head).
    #[inline(always)]
    fn attach_protected_head(&mut self, mut node_ptr: NonNull<Node<K, V>>) {
        unsafe {
            let node = node_ptr.as_mut();
            node.prev = None;
            node.next = self.protected_head;
            node.queue = QueueKind::Protected;

            match self.protected_head {
                Some(mut h) => h.as_mut().prev = Some(node_ptr),
                None => self.protected_tail = Some(node_ptr),
            }

            self.protected_head = Some(node_ptr);
            self.protected_len += 1;
        }
    }

    /// Retrieves a value by key, promoting from probation to protected if needed.
    ///
    /// If the key is in probation, accessing it promotes the entry to the
    /// protected queue (demonstrating it's not a one-time access).
    /// If already in protected, moves it to the MRU position.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::two_q::TwoQCore;
    ///
    /// let mut cache = TwoQCore::new(100, 0.25);
    /// cache.insert("key", 42);
    ///
    /// // First access: in probation, now promotes to protected
    /// assert_eq!(cache.get(&"key"), Some(&42));
    ///
    /// // Second access: already in protected, moves to MRU
    /// assert_eq!(cache.get(&"key"), Some(&42));
    ///
    /// // Missing key
    /// assert_eq!(cache.get(&"missing"), None);
    /// ```
    #[inline]
    pub fn get(&mut self, key: &K) -> Option<&V> {
        let node_ptr = match self.map.get(key) {
            Some(&ptr) => ptr,
            None => {
                #[cfg(feature = "metrics")]
                self.metrics.record_get_miss();
                return None;
            },
        };

        #[cfg(feature = "metrics")]
        self.metrics.record_get_hit();

        let queue = unsafe { node_ptr.as_ref().queue };

        match queue {
            QueueKind::Probation => {
                #[cfg(feature = "metrics")]
                self.metrics.record_a1in_to_am_promotion();

                self.detach(node_ptr);
                self.attach_protected_head(node_ptr);
            },
            QueueKind::Protected => {
                self.detach(node_ptr);
                self.attach_protected_head(node_ptr);
            },
        }

        unsafe { Some(&node_ptr.as_ref().value) }
    }

    /// Inserts or updates a key-value pair.
    ///
    /// - If the key exists, updates the value in place (no queue change)
    /// - If the key is new, inserts into the probation queue
    /// - May trigger eviction if capacity is exceeded
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::two_q::TwoQCore;
    ///
    /// let mut cache = TwoQCore::new(100, 0.25);
    ///
    /// // New insert goes to probation
    /// cache.insert("key", "initial");
    /// assert_eq!(cache.len(), 1);
    ///
    /// // Update existing key
    /// cache.insert("key", "updated");
    /// assert_eq!(cache.get(&"key"), Some(&"updated"));
    /// assert_eq!(cache.len(), 1);  // Still 1 entry
    /// ```
    #[inline]
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        #[cfg(feature = "metrics")]
        self.metrics.record_insert_call();

        if self.protected_cap == 0 {
            return None;
        }

        if let Some(&node_ptr) = self.map.get(&key) {
            #[cfg(feature = "metrics")]
            self.metrics.record_insert_update();

            let old = unsafe { std::mem::replace(&mut (*node_ptr.as_ptr()).value, value) };
            return Some(old);
        }

        #[cfg(feature = "metrics")]
        self.metrics.record_insert_new();

        self.evict_if_needed();

        let node = Box::new(Node {
            prev: None,
            next: None,
            queue: QueueKind::Probation,
            key: key.clone(),
            value,
        });
        let node_ptr = NonNull::new(Box::into_raw(node)).unwrap();

        self.map.insert(key, node_ptr);
        self.attach_probation_head(node_ptr);
        None
    }

    /// Evicts entries until there is room for a new entry.
    #[inline]
    fn evict_if_needed(&mut self) {
        if self.len() >= self.protected_cap {
            #[cfg(feature = "metrics")]
            self.metrics.record_evict_call();
        }

        while self.len() >= self.protected_cap {
            if self.probation_len > self.probation_cap {
                if let Some(node) = self.pop_probation_tail() {
                    self.map.remove(&node.key);
                    #[cfg(feature = "metrics")]
                    self.metrics.record_evicted_entry();
                    continue;
                }
            }
            if let Some(node) = self.pop_protected_tail() {
                self.map.remove(&node.key);
                #[cfg(feature = "metrics")]
                self.metrics.record_evicted_entry();
                continue;
            }
            if let Some(node) = self.pop_probation_tail() {
                self.map.remove(&node.key);
                #[cfg(feature = "metrics")]
                self.metrics.record_evicted_entry();
                continue;
            }
            break;
        }
    }

    /// Returns the number of entries in the cache.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::two_q::TwoQCore;
    ///
    /// let mut cache = TwoQCore::new(100, 0.25);
    /// assert_eq!(cache.len(), 0);
    ///
    /// cache.insert("a", 1);
    /// cache.insert("b", 2);
    /// assert_eq!(cache.len(), 2);
    /// ```
    #[inline]
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Returns `true` if the cache is empty.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::two_q::TwoQCore;
    ///
    /// let mut cache: TwoQCore<&str, i32> = TwoQCore::new(100, 0.25);
    /// assert!(cache.is_empty());
    ///
    /// cache.insert("key", 42);
    /// assert!(!cache.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Returns the total cache capacity.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::two_q::TwoQCore;
    ///
    /// let cache: TwoQCore<String, i32> = TwoQCore::new(500, 0.25);
    /// assert_eq!(cache.capacity(), 500);
    /// ```
    #[inline]
    pub fn capacity(&self) -> usize {
        self.protected_cap
    }

    /// Returns `true` if the key exists in the cache.
    ///
    /// Does not affect queue positions (no promotion on contains).
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::two_q::TwoQCore;
    ///
    /// let mut cache = TwoQCore::new(100, 0.25);
    /// cache.insert("key", 42);
    ///
    /// assert!(cache.contains(&"key"));
    /// assert!(!cache.contains(&"missing"));
    /// ```
    #[inline]
    pub fn contains(&self, key: &K) -> bool {
        self.map.contains_key(key)
    }

    /// Clears all entries from the cache.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::two_q::TwoQCore;
    ///
    /// let mut cache = TwoQCore::new(100, 0.25);
    /// cache.insert("a", 1);
    /// cache.insert("b", 2);
    ///
    /// cache.clear();
    /// assert!(cache.is_empty());
    /// assert!(!cache.contains(&"a"));
    /// ```
    pub fn clear(&mut self) {
        #[cfg(feature = "metrics")]
        self.metrics.record_clear();

        while self.pop_probation_tail().is_some() {}
        while self.pop_protected_tail().is_some() {}
        self.map.clear();
    }

    /// Side-effect-free lookup by key.
    ///
    /// Does not promote entries between queues or update MRU position.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::two_q::TwoQCore;
    ///
    /// let mut cache = TwoQCore::new(100, 0.25);
    /// cache.insert("key", 42);
    /// assert_eq!(cache.peek(&"key"), Some(&42));
    /// assert_eq!(cache.peek(&"missing"), None);
    /// ```
    #[inline]
    pub fn peek(&self, key: &K) -> Option<&V> {
        self.map.get(key).map(|&ptr| unsafe { &ptr.as_ref().value })
    }

    /// Removes a specific key-value pair, returning the value if it existed.
    ///
    /// Detaches the entry from its queue (probation or protected) and
    /// adjusts the queue counters.
    ///
    /// # Example
    ///
    /// ```
    /// use cachekit::policy::two_q::TwoQCore;
    ///
    /// let mut cache = TwoQCore::new(100, 0.25);
    /// cache.insert("key", 42);
    /// assert_eq!(cache.remove(&"key"), Some(42));
    /// assert!(!cache.contains(&"key"));
    /// ```
    pub fn remove(&mut self, key: &K) -> Option<V> {
        let node_ptr = self.map.remove(key)?;
        self.detach(node_ptr);
        unsafe {
            let node = Box::from_raw(node_ptr.as_ptr());
            Some(node.value)
        }
    }
}

impl<K, V> Drop for TwoQCore<K, V> {
    fn drop(&mut self) {
        while self.pop_probation_tail().is_some() {}
        while self.pop_protected_tail().is_some() {}
    }
}

impl<K, V> std::fmt::Debug for TwoQCore<K, V>
where
    K: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TwoQCore")
            .field("capacity", &self.protected_cap)
            .field("probation_cap", &self.probation_cap)
            .field("len", &self.map.len())
            .field("probation_len", &self.probation_len)
            .field("protected_len", &self.protected_len)
            .finish_non_exhaustive()
    }
}

/// Implementation of the [`Cache`] trait for 2Q.
///
/// Allows `TwoQCore` to be used through the unified cache interface.
///
/// # Example
///
/// ```
/// use cachekit::traits::Cache;
/// use cachekit::policy::two_q::TwoQCore;
///
/// let mut cache: TwoQCore<&str, i32> = TwoQCore::new(100, 0.25);
///
/// // Use via Cache trait
/// cache.insert("key", 42);
/// assert_eq!(cache.get(&"key"), Some(&42));
/// assert!(cache.contains(&"key"));
/// ```
impl<K, V> Cache<K, V> for TwoQCore<K, V>
where
    K: Clone + Eq + Hash,
{
    #[inline]
    fn contains(&self, key: &K) -> bool {
        TwoQCore::contains(self, key)
    }

    #[inline]
    fn len(&self) -> usize {
        TwoQCore::len(self)
    }

    #[inline]
    fn capacity(&self) -> usize {
        TwoQCore::capacity(self)
    }

    #[inline]
    fn peek(&self, key: &K) -> Option<&V> {
        TwoQCore::peek(self, key)
    }

    #[inline]
    fn get(&mut self, key: &K) -> Option<&V> {
        TwoQCore::get(self, key)
    }

    #[inline]
    fn insert(&mut self, key: K, value: V) -> Option<V> {
        TwoQCore::insert(self, key, value)
    }

    #[inline]
    fn remove(&mut self, key: &K) -> Option<V> {
        TwoQCore::remove(self, key)
    }

    fn clear(&mut self) {
        TwoQCore::clear(self);
    }
}

#[cfg(feature = "metrics")]
impl<K, V> TwoQCore<K, V>
where
    K: Clone + Eq + Hash,
{
    /// Returns a snapshot of cache metrics.
    pub fn metrics_snapshot(&self) -> TwoQMetricsSnapshot {
        TwoQMetricsSnapshot {
            get_calls: self.metrics.get_calls,
            get_hits: self.metrics.get_hits,
            get_misses: self.metrics.get_misses,
            insert_calls: self.metrics.insert_calls,
            insert_updates: self.metrics.insert_updates,
            insert_new: self.metrics.insert_new,
            evict_calls: self.metrics.evict_calls,
            evicted_entries: self.metrics.evicted_entries,
            a1in_to_am_promotions: self.metrics.a1in_to_am_promotions,
            a1out_ghost_hits: self.metrics.a1out_ghost_hits,
            cache_len: self.len(),
            capacity: self.protected_cap,
        }
    }
}

#[cfg(feature = "metrics")]
impl<K, V> MetricsSnapshotProvider<TwoQMetricsSnapshot> for TwoQCore<K, V>
where
    K: Clone + Eq + Hash,
{
    fn snapshot(&self) -> TwoQMetricsSnapshot {
        self.metrics_snapshot()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ==============================================
    // LruQueue Tests
    // ==============================================

    mod lru_queue_tests {
        use super::*;

        #[test]
        fn new_queue_is_empty() {
            let lru: LruQueue<i32> = LruQueue::new();
            assert!(lru.is_empty());
            assert_eq!(lru.len(), 0);
        }

        #[test]
        fn default_creates_empty_queue() {
            let lru: LruQueue<&str> = LruQueue::default();
            assert!(lru.is_empty());
        }

        #[test]
        fn insert_increases_length() {
            let mut lru = LruQueue::new();
            lru.insert(1);
            assert_eq!(lru.len(), 1);
            assert!(!lru.is_empty());

            lru.insert(2);
            lru.insert(3);
            assert_eq!(lru.len(), 3);
        }

        #[test]
        fn evict_returns_lru_item() {
            let mut lru = LruQueue::new();
            lru.insert("first");
            lru.insert("second");
            lru.insert("third");

            // "first" is the LRU (inserted first, never touched)
            assert_eq!(lru.evict(), Some("first"));
            assert_eq!(lru.evict(), Some("second"));
            assert_eq!(lru.evict(), Some("third"));
            assert_eq!(lru.evict(), None);
        }

        #[test]
        fn touch_moves_to_mru() {
            let mut lru = LruQueue::new();
            let first = lru.insert("first");
            lru.insert("second");
            lru.insert("third");

            // Touch "first" - moves it to MRU
            assert!(lru.touch(first));

            // Now "second" is LRU
            assert_eq!(lru.evict(), Some("second"));
            assert_eq!(lru.evict(), Some("third"));
            assert_eq!(lru.evict(), Some("first")); // "first" is now MRU, evicted last
        }

        #[test]
        fn remove_returns_item() {
            let mut lru = LruQueue::new();
            let id = lru.insert("item");
            assert_eq!(lru.len(), 1);

            assert_eq!(lru.remove(id), Some("item"));
            assert!(lru.is_empty());
        }

        #[test]
        fn remove_from_middle() {
            let mut lru = LruQueue::new();
            lru.insert("first");
            let middle = lru.insert("middle");
            lru.insert("last");

            assert_eq!(lru.remove(middle), Some("middle"));
            assert_eq!(lru.len(), 2);

            // Remaining items evict in LRU order
            assert_eq!(lru.evict(), Some("first"));
            assert_eq!(lru.evict(), Some("last"));
        }

        #[test]
        fn evict_from_empty_returns_none() {
            let mut lru: LruQueue<i32> = LruQueue::new();
            assert_eq!(lru.evict(), None);
        }

        #[test]
        fn push_front_alias_works() {
            let mut lru = LruQueue::new();
            lru.push_front("a");
            lru.push_front("b");
            assert_eq!(lru.len(), 2);
            // "a" is LRU since "b" was pushed front after
            assert_eq!(lru.pop_back(), Some("a"));
        }

        #[test]
        fn move_to_front_alias_works() {
            let mut lru = LruQueue::new();
            let a = lru.insert("a");
            lru.insert("b");

            assert!(lru.move_to_front(a));
            // Now "b" is LRU
            assert_eq!(lru.pop_back(), Some("b"));
        }
    }

    // ==============================================
    // TwoQCore Basic Operations
    // ==============================================

    mod basic_operations {
        use super::*;

        #[test]
        fn new_cache_is_empty() {
            let cache: TwoQCore<&str, i32> = TwoQCore::new(100, 0.25);
            assert!(cache.is_empty());
            assert_eq!(cache.len(), 0);
            assert_eq!(cache.capacity(), 100);
        }

        #[test]
        fn insert_and_get() {
            let mut cache = TwoQCore::new(100, 0.25);
            cache.insert("key1", "value1");

            assert_eq!(cache.len(), 1);
            assert_eq!(cache.get(&"key1"), Some(&"value1"));
        }

        #[test]
        fn insert_multiple_items() {
            let mut cache = TwoQCore::new(100, 0.25);
            cache.insert("a", 1);
            cache.insert("b", 2);
            cache.insert("c", 3);

            assert_eq!(cache.len(), 3);
            assert_eq!(cache.get(&"a"), Some(&1));
            assert_eq!(cache.get(&"b"), Some(&2));
            assert_eq!(cache.get(&"c"), Some(&3));
        }

        #[test]
        fn get_missing_key_returns_none() {
            let mut cache: TwoQCore<&str, i32> = TwoQCore::new(100, 0.25);
            cache.insert("exists", 42);

            assert_eq!(cache.get(&"missing"), None);
        }

        #[test]
        fn update_existing_key() {
            let mut cache = TwoQCore::new(100, 0.25);
            cache.insert("key", "initial");
            cache.insert("key", "updated");

            assert_eq!(cache.len(), 1);
            assert_eq!(cache.get(&"key"), Some(&"updated"));
        }

        #[test]
        fn contains_returns_correct_result() {
            let mut cache = TwoQCore::new(100, 0.25);
            cache.insert("exists", 1);

            assert!(cache.contains(&"exists"));
            assert!(!cache.contains(&"missing"));
        }

        #[test]
        fn contains_does_not_promote() {
            let mut cache: TwoQCore<String, i32> = TwoQCore::new(10, 0.3);
            cache.insert("a".to_string(), 1);
            cache.insert("b".to_string(), 2);
            cache.insert("c".to_string(), 3);

            // Contains check should not promote
            assert!(cache.contains(&"a".to_string()));
            assert!(cache.contains(&"b".to_string()));
            assert!(cache.contains(&"c".to_string()));

            // Fill up to trigger eviction
            for i in 0..10 {
                cache.insert(format!("new{}", i), i);
            }

            // Original items should be evicted (they were only in probation)
            assert!(!cache.contains(&"a".to_string()));
            assert!(!cache.contains(&"b".to_string()));
            assert!(!cache.contains(&"c".to_string()));
        }

        #[test]
        fn clear_removes_all_entries() {
            let mut cache = TwoQCore::new(100, 0.25);
            cache.insert("a", 1);
            cache.insert("b", 2);
            cache.get(&"a"); // Promote "a" to protected

            cache.clear();

            assert!(cache.is_empty());
            assert_eq!(cache.len(), 0);
            assert!(!cache.contains(&"a"));
            assert!(!cache.contains(&"b"));
        }

        #[test]
        fn capacity_returns_correct_value() {
            let cache: TwoQCore<i32, i32> = TwoQCore::new(500, 0.25);
            assert_eq!(cache.capacity(), 500);
        }
    }

    // ==============================================
    // Queue Behavior (Probation vs Protected)
    // ==============================================

    mod queue_behavior {
        use super::*;

        #[test]
        fn new_insert_goes_to_probation() {
            let mut cache = TwoQCore::new(10, 0.3);
            cache.insert("key", "value");

            assert!(cache.contains(&"key"));
            assert_eq!(cache.len(), 1);
        }

        #[test]
        fn get_promotes_from_probation_to_protected() {
            let mut cache: TwoQCore<String, i32> = TwoQCore::new(10, 0.3);
            cache.insert("key".to_string(), 0);

            // First get promotes to protected
            let _ = cache.get(&"key".to_string());

            // Insert enough items to fill probation and exceed capacity
            for i in 0..12 {
                cache.insert(format!("new{}", i), i);
            }

            // "key" should still exist because it was promoted to protected
            assert!(cache.contains(&"key".to_string()));
        }

        #[test]
        fn item_in_protected_stays_in_protected() {
            let mut cache = TwoQCore::new(10, 0.3);
            cache.insert("key", "value");

            // Promote to protected
            cache.get(&"key");

            // Access again - should stay in protected, move to MRU
            cache.get(&"key");
            cache.get(&"key");

            assert_eq!(cache.get(&"key"), Some(&"value"));
        }

        #[test]
        fn multiple_accesses_keep_item_alive() {
            let mut cache: TwoQCore<String, i32> = TwoQCore::new(10, 0.3);

            cache.insert("hot".to_string(), 0);
            cache.get(&"hot".to_string());

            for i in 0..15 {
                cache.insert(format!("cold{}", i), i);
                cache.get(&"hot".to_string());
            }

            assert!(cache.contains(&"hot".to_string()));
        }
    }

    // ==============================================
    // Eviction Behavior
    // ==============================================

    mod eviction_behavior {
        use super::*;

        #[test]
        fn eviction_occurs_when_over_capacity() {
            let mut cache = TwoQCore::new(5, 0.2);

            for i in 0..10 {
                cache.insert(i, i * 10);
            }

            assert_eq!(cache.len(), 5);
        }

        #[test]
        fn probation_evicts_fifo_order() {
            let mut cache = TwoQCore::new(5, 0.4);

            cache.insert("first", 1);
            cache.insert("second", 2);
            cache.insert("third", 3);
            cache.insert("fourth", 4);
            cache.insert("fifth", 5);
            cache.insert("sixth", 6);

            assert!(!cache.contains(&"first"));
            assert_eq!(cache.len(), 5);
        }

        #[test]
        fn protected_evicts_lru_when_probation_under_cap() {
            let mut cache = TwoQCore::new(5, 0.4);

            cache.insert("p1", 1);
            cache.get(&"p1");
            cache.insert("p2", 2);
            cache.get(&"p2");
            cache.insert("p3", 3);
            cache.get(&"p3");

            cache.insert("new1", 10);
            cache.insert("new2", 20);
            cache.insert("new3", 30);

            assert!(!cache.contains(&"p1"));
            assert_eq!(cache.len(), 5);
        }

        #[test]
        fn scan_items_evicted_before_hot_items() {
            let mut cache: TwoQCore<String, i32> = TwoQCore::new(10, 0.3);

            cache.insert("hot1".to_string(), 1);
            cache.get(&"hot1".to_string());
            cache.insert("hot2".to_string(), 2);
            cache.get(&"hot2".to_string());

            for i in 0..20 {
                cache.insert(format!("scan{}", i), i);
            }

            assert!(cache.contains(&"hot1".to_string()));
            assert!(cache.contains(&"hot2".to_string()));
            assert_eq!(cache.len(), 10);
        }

        #[test]
        fn eviction_removes_from_index() {
            let mut cache = TwoQCore::new(3, 0.33);

            cache.insert("a", 1);
            cache.insert("b", 2);
            cache.insert("c", 3);

            assert!(cache.contains(&"a"));

            cache.insert("d", 4);

            assert!(!cache.contains(&"a"));
            assert_eq!(cache.get(&"a"), None);
        }
    }

    // ==============================================
    // Scan Resistance
    // ==============================================

    mod scan_resistance {
        use super::*;

        #[test]
        fn scan_does_not_pollute_protected() {
            let mut cache = TwoQCore::new(100, 0.25);

            for i in 0..50 {
                let key = format!("working{}", i);
                cache.insert(key.clone(), i);
                cache.get(&key);
            }

            for i in 0..200 {
                cache.insert(format!("scan{}", i), i);
            }

            let mut working_set_hits = 0;
            for i in 0..50 {
                if cache.contains(&format!("working{}", i)) {
                    working_set_hits += 1;
                }
            }

            assert!(
                working_set_hits >= 40,
                "Working set should survive scan, but only {} items remained",
                working_set_hits
            );
        }

        #[test]
        fn one_time_access_stays_in_probation() {
            let mut cache: TwoQCore<String, i32> = TwoQCore::new(10, 0.3);

            cache.insert("once".to_string(), 1);

            for i in 0..5 {
                cache.insert(format!("other{}", i), i);
            }

            cache.get(&"once".to_string());

            for i in 0..10 {
                cache.insert(format!("new{}", i), i);
            }

            assert!(cache.contains(&"once".to_string()));
        }

        #[test]
        fn repeated_scans_dont_evict_hot_items() {
            let mut cache = TwoQCore::new(20, 0.25);

            for i in 0..10 {
                let key = format!("hot{}", i);
                cache.insert(key.clone(), i);
                cache.get(&key);
                cache.get(&key);
                cache.get(&key);
            }

            for scan in 0..3 {
                for i in 0..30 {
                    cache.insert(format!("scan{}_{}", scan, i), i);
                }
            }

            let mut hot_survivors = 0;
            for i in 0..10 {
                if cache.contains(&format!("hot{}", i)) {
                    hot_survivors += 1;
                }
            }

            assert!(
                hot_survivors >= 8,
                "Hot items should survive scans, but only {} survived",
                hot_survivors
            );
        }
    }

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

    mod edge_cases {
        use super::*;

        #[test]
        fn single_capacity_cache() {
            let mut cache = TwoQCore::new(1, 0.5);

            cache.insert("a", 1);
            assert_eq!(cache.get(&"a"), Some(&1));

            cache.insert("b", 2);
            assert!(!cache.contains(&"a"));
            assert_eq!(cache.get(&"b"), Some(&2));
        }

        #[test]
        fn zero_probation_fraction() {
            let mut cache = TwoQCore::new(10, 0.0);

            for i in 0..10 {
                cache.insert(i, i * 10);
            }

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

            cache.insert(100, 1000);
            assert_eq!(cache.len(), 10);
        }

        #[test]
        fn one_hundred_percent_probation() {
            let mut cache = TwoQCore::new(10, 1.0);

            for i in 0..10 {
                cache.insert(i, i * 10);
            }

            for i in 0..10 {
                cache.get(&i);
            }

            assert_eq!(cache.len(), 10);
        }

        #[test]
        fn get_after_update() {
            let mut cache = TwoQCore::new(100, 0.25);

            cache.insert("key", "v1");
            assert_eq!(cache.get(&"key"), Some(&"v1"));

            cache.insert("key", "v2");
            assert_eq!(cache.get(&"key"), Some(&"v2"));

            cache.insert("key", "v3");
            cache.insert("key", "v4");
            assert_eq!(cache.get(&"key"), Some(&"v4"));
        }

        #[test]
        fn large_capacity() {
            let mut cache = TwoQCore::new(10000, 0.25);

            for i in 0..10000 {
                cache.insert(i, i * 2);
            }

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

            assert_eq!(cache.get(&5000), Some(&10000));
            assert_eq!(cache.get(&9999), Some(&19998));
        }

        #[test]
        fn empty_cache_operations() {
            let mut cache: TwoQCore<i32, i32> = TwoQCore::new(100, 0.25);

            assert!(cache.is_empty());
            assert_eq!(cache.get(&1), None);
            assert!(!cache.contains(&1));

            cache.clear();
            assert!(cache.is_empty());
        }

        #[test]
        fn small_fractions() {
            let mut cache = TwoQCore::new(100, 0.01);

            for i in 0..10 {
                cache.insert(i, i);
            }

            assert_eq!(cache.len(), 10);
        }

        #[test]
        fn string_keys_and_values() {
            let mut cache = TwoQCore::new(100, 0.25);

            cache.insert(String::from("hello"), String::from("world"));
            cache.insert(String::from("foo"), String::from("bar"));

            assert_eq!(
                cache.get(&String::from("hello")),
                Some(&String::from("world"))
            );
            assert_eq!(cache.get(&String::from("foo")), Some(&String::from("bar")));
        }

        #[test]
        fn integer_keys() {
            let mut cache = TwoQCore::new(100, 0.25);

            for i in 0..50 {
                cache.insert(i, format!("value_{}", i));
            }

            assert_eq!(cache.get(&25), Some(&String::from("value_25")));
            assert_eq!(cache.get(&49), Some(&String::from("value_49")));
        }
    }

    // ==============================================
    // Capacity and Eviction Boundary Tests
    // ==============================================

    mod boundary_tests {
        use super::*;

        #[test]
        fn exact_capacity_no_eviction() {
            let mut cache = TwoQCore::new(10, 0.3);

            for i in 0..10 {
                cache.insert(i, i);
            }

            assert_eq!(cache.len(), 10);
            for i in 0..10 {
                assert!(cache.contains(&i));
            }
        }

        #[test]
        fn one_over_capacity_triggers_eviction() {
            let mut cache = TwoQCore::new(10, 0.3);

            for i in 0..10 {
                cache.insert(i, i);
            }

            cache.insert(10, 10);

            assert_eq!(cache.len(), 10);
            assert!(!cache.contains(&0));
            assert!(cache.contains(&10));
        }

        #[test]
        fn probation_cap_boundary() {
            let mut cache = TwoQCore::new(10, 0.3);

            cache.insert("a", 1);
            cache.insert("b", 2);
            cache.insert("c", 3);

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

            cache.insert("d", 4);
            assert_eq!(cache.len(), 4);

            for key in &["a", "b", "c", "d"] {
                assert!(cache.contains(key));
            }
        }

        #[test]
        fn promotion_fills_protected() {
            let mut cache = TwoQCore::new(10, 0.3);

            for i in 0..5 {
                cache.insert(i, i);
            }

            for i in 0..5 {
                cache.get(&i);
            }

            for i in 5..10 {
                cache.insert(i, i);
            }

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

            cache.insert(10, 10);
            assert_eq!(cache.len(), 10);
        }
    }

    // ==============================================
    // Regression Tests
    // ==============================================

    mod regression_tests {
        use super::*;

        #[test]
        fn promotion_actually_moves_to_protected_queue() {
            let mut cache: TwoQCore<String, i32> = TwoQCore::new(5, 0.4);

            cache.insert("key".to_string(), 0);
            cache.get(&"key".to_string());

            cache.insert("p1".to_string(), 1);
            cache.insert("p2".to_string(), 2);
            cache.insert("p3".to_string(), 3);
            cache.insert("p4".to_string(), 4);

            assert!(
                cache.contains(&"key".to_string()),
                "Promoted item should be in protected queue and survive probation eviction"
            );
        }

        #[test]
        fn update_preserves_queue_position() {
            let mut cache: TwoQCore<String, i32> = TwoQCore::new(10, 0.3);

            cache.insert("key".to_string(), 1);
            cache.get(&"key".to_string());

            cache.insert("key".to_string(), 2);

            assert_eq!(cache.get(&"key".to_string()), Some(&2));

            for i in 0..15 {
                cache.insert(format!("other{}", i), i);
            }

            assert!(cache.contains(&"key".to_string()));
        }

        #[test]
        fn eviction_order_consistency() {
            for _ in 0..10 {
                let mut cache = TwoQCore::new(5, 0.4);

                cache.insert("a", 1);
                cache.insert("b", 2);
                cache.insert("c", 3);
                cache.insert("d", 4);
                cache.insert("e", 5);
                cache.insert("f", 6);

                assert!(!cache.contains(&"a"), "First item should be evicted");
                assert!(cache.contains(&"f"), "New item should exist");
            }
        }
    }

    // ==============================================
    // Workload Simulation
    // ==============================================

    mod workload_simulation {
        use super::*;

        #[test]
        fn database_buffer_pool_workload() {
            let mut cache = TwoQCore::new(100, 0.25);

            for i in 0..10 {
                let key = format!("index_page_{}", i);
                cache.insert(key.clone(), format!("index_data_{}", i));
                cache.get(&key);
                cache.get(&key);
            }

            for i in 0..200 {
                cache.insert(format!("table_page_{}", i), format!("row_data_{}", i));
            }

            let mut index_hits = 0;
            for i in 0..10 {
                if cache.contains(&format!("index_page_{}", i)) {
                    index_hits += 1;
                }
            }

            assert!(
                index_hits >= 8,
                "Index pages should survive table scan, got {} hits",
                index_hits
            );
        }

        #[test]
        fn web_cache_simulation() {
            let mut cache: TwoQCore<String, String> = TwoQCore::new(50, 0.3);

            let popular = vec!["home", "about", "products", "contact"];
            for page in &popular {
                cache.insert(page.to_string(), format!("{}_content", page));
                cache.get(&page.to_string());
                cache.get(&page.to_string());
            }

            for i in 0..100 {
                cache.insert(format!("blog_post_{}", i), format!("content_{}", i));
            }

            for page in &popular {
                assert!(
                    cache.contains(&page.to_string()),
                    "Popular page '{}' should survive",
                    page
                );
            }
        }

        #[test]
        fn mixed_workload() {
            let mut cache = TwoQCore::new(100, 0.25);

            for i in 0..30 {
                let key = format!("working_{}", i);
                cache.insert(key.clone(), i);
                cache.get(&key);
            }

            for round in 0..5 {
                for i in (0..30).step_by(3) {
                    cache.get(&format!("working_{}", i));
                }

                for i in 0..20 {
                    cache.insert(format!("round_{}_{}", round, i), i);
                }
            }

            let mut working_set_hits = 0;
            for i in (0..30).step_by(3) {
                if cache.contains(&format!("working_{}", i)) {
                    working_set_hits += 1;
                }
            }

            assert!(
                working_set_hits >= 8,
                "Frequently accessed working set should survive, got {} hits",
                working_set_hits
            );
        }
    }

    // ==============================================
    // Regression Tests
    // ==============================================

    #[test]
    fn zero_capacity_rejects_inserts() {
        let mut cache: TwoQCore<&str, i32> = TwoQCore::new(0, 0.25);
        assert_eq!(cache.capacity(), 0);

        cache.insert("key", 42);

        assert_eq!(
            cache.len(),
            0,
            "TwoQCore with capacity=0 should reject inserts"
        );
    }

    #[test]
    fn trait_insert_returns_old_value() {
        let mut cache: TwoQCore<&str, i32> = TwoQCore::new(10, 0.25);

        let first = Cache::insert(&mut cache, "key", 1);
        assert_eq!(first, None, "First insert of new key should return None");

        let second = Cache::insert(&mut cache, "key", 2);
        assert_eq!(second, Some(1), "Second insert should return old value");
    }

    #[test]
    fn inherent_insert_updates_value() {
        let mut cache: TwoQCore<&str, i32> = TwoQCore::new(10, 0.25);

        cache.insert("key", 1);
        cache.insert("key", 2);

        assert_eq!(cache.get(&"key"), Some(&2), "Value should be updated to 2");
    }
}