cache2 0.6.0

Performance-first bounded RAM and NVMe hybrid cache
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
// Copyright 2026 ScopeDB, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Bounded shard-local eviction for the volatile RAM tier.
//!
//! Capacity accounting and key correctness stay in `memory`; this module owns
//! the optional CLOCK or S3-FIFO metadata and chooses bounded victims.

use std::io;

use crate::config::runtime::L1EvictionPolicy;
use crate::hashing::FixedPrehashedMap;

/// Maximum policy metadata inspected by one complete foreground admission.
/// Exhausting this budget means L1 bypass; it never expands with cache size or
/// the number of victims required by a mixed-size candidate.
pub const MAX_POLICY_SCAN_STEPS: usize = 64;

/// Memory slot indices are packed into `u32`; the final value is reserved as
/// the end-of-chain sentinel by `memory` and the policy queues.
pub const MAX_POLICY_SLOT_INDEX: usize = (u32::MAX - 1) as usize;

const NO_POLICY_SLOT: u32 = u32::MAX;
const RESIDENT_BIT: u8 = 1 << 0;
const CLOCK_VISITED_BIT: u8 = 1 << 1;
const S3FIFO_FREQUENCY_SHIFT: u8 = 1;
const S3FIFO_FREQUENCY_MASK: u8 = 0b11 << S3FIFO_FREQUENCY_SHIFT;
const S3FIFO_MAIN_BIT: u8 = 1 << 3;
const S3FIFO_MAX_FREQUENCY: u8 = 3;
const S3FIFO_MOVE_TO_MAIN_THRESHOLD: u8 = 2;

#[derive(Clone, Copy, Debug, Default)]
pub struct PolicySlot {
    hash: u64,
    clock_position: u32,
    flags: u8,
}

impl PolicySlot {
    pub const fn new_free(next: u32) -> Self {
        Self {
            hash: 0,
            clock_position: next,
            flags: 0,
        }
    }

    pub fn free_next(&self) -> u32 {
        debug_assert!(!self.is_resident());
        self.clock_position
    }

    fn new_clock(hash: u64, visited: bool, position: u32) -> Self {
        Self {
            hash,
            clock_position: position,
            flags: RESIDENT_BIT | (u8::from(visited) * CLOCK_VISITED_BIT),
        }
    }

    fn new_s3fifo(hash: u64, queue: QueueKind, frequency: u8) -> Self {
        debug_assert!(frequency <= S3FIFO_MAX_FREQUENCY);
        Self {
            hash,
            clock_position: 0,
            flags: RESIDENT_BIT
                | ((frequency << S3FIFO_FREQUENCY_SHIFT) & S3FIFO_FREQUENCY_MASK)
                | (u8::from(queue == QueueKind::Main) * S3FIFO_MAIN_BIT),
        }
    }

    pub const fn hash(&self) -> u64 {
        self.hash
    }

    const fn is_resident(&self) -> bool {
        self.flags & RESIDENT_BIT != 0
    }

    const fn clock_visited(&self) -> bool {
        self.flags & CLOCK_VISITED_BIT != 0
    }

    fn set_clock_visited(&mut self, visited: bool) {
        self.flags = (self.flags & !CLOCK_VISITED_BIT) | (u8::from(visited) * CLOCK_VISITED_BIT);
    }

    const fn clock_position(&self) -> u32 {
        self.clock_position
    }

    fn set_clock_position(&mut self, position: u32) {
        self.clock_position = position;
    }

    const fn s3fifo_queue(&self) -> QueueKind {
        if self.flags & S3FIFO_MAIN_BIT == 0 {
            QueueKind::Small
        } else {
            QueueKind::Main
        }
    }

    const fn s3fifo_frequency(&self) -> u8 {
        (self.flags & S3FIFO_FREQUENCY_MASK) >> S3FIFO_FREQUENCY_SHIFT
    }

    fn set_s3fifo_frequency(&mut self, frequency: u8) {
        debug_assert!(frequency <= S3FIFO_MAX_FREQUENCY);
        self.flags = (self.flags & !S3FIFO_FREQUENCY_MASK)
            | ((frequency << S3FIFO_FREQUENCY_SHIFT) & S3FIFO_FREQUENCY_MASK);
    }

    fn increment_s3fifo_frequency(&mut self) {
        let frequency = self.flags & S3FIFO_FREQUENCY_MASK;
        self.flags += u8::from(frequency != S3FIFO_FREQUENCY_MASK) << S3FIFO_FREQUENCY_SHIFT;
    }

    fn set_s3fifo_queue(&mut self, queue: QueueKind) {
        self.flags = (self.flags & !S3FIFO_MAIN_BIT)
            | (u8::from(queue == QueueKind::Main) * S3FIFO_MAIN_BIT);
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum QueueKind {
    Small,
    Main,
}

#[derive(Clone, Copy, Debug)]
enum DetachedPolicyKind {
    Clock,
    S3Fifo { queue: QueueKind, frequency: u8 },
}

#[derive(Clone, Copy, Debug)]
pub struct DetachedPolicy {
    hash: u64,
    weight: usize,
    kind: DetachedPolicyKind,
}

impl DetachedPolicy {
    pub const fn hash(self) -> u64 {
        self.hash
    }

    pub const fn weight(self) -> usize {
        self.weight
    }
}

pub struct EvictionState {
    policy: EvictionPolicyState,
}

enum EvictionPolicyState {
    Clock(ClockState),
    S3Fifo(S3FifoState),
}

impl EvictionState {
    pub fn new(
        policy: L1EvictionPolicy,
        capacity_bytes: usize,
        maximum_entries: usize,
    ) -> io::Result<Self> {
        let policy = match policy {
            L1EvictionPolicy::Clock => {
                EvictionPolicyState::Clock(ClockState::new(maximum_entries)?)
            }
            L1EvictionPolicy::S3Fifo => {
                EvictionPolicyState::S3Fifo(S3FifoState::new(capacity_bytes, maximum_entries)?)
            }
        };
        Ok(Self { policy })
    }

    pub fn allocation_bytes(policy: L1EvictionPolicy, maximum_entries: usize) -> io::Result<usize> {
        match policy {
            L1EvictionPolicy::Clock => ClockState::allocation_bytes(maximum_entries),
            L1EvictionPolicy::S3Fifo => S3FifoState::allocation_bytes(maximum_entries),
        }
    }

    pub fn insert(&mut self, slots: &mut [PolicySlot], index: usize, hash: u64, weight: usize) {
        debug_assert!(!slots[index].is_resident());
        match &mut self.policy {
            EvictionPolicyState::Clock(state) => {
                // One-shot scans receive no free second chance. A real L1 hit
                // sets the bit before this entry reaches the hand.
                state.insert(slots, index, hash, false);
            }
            EvictionPolicyState::S3Fifo(state) => {
                state.insert(slots, index, hash, weight);
            }
        }
    }

    pub fn record_hit(&mut self, slots: &mut [PolicySlot], index: usize) {
        match &mut self.policy {
            EvictionPolicyState::Clock(_) => slots[index].set_clock_visited(true),
            EvictionPolicyState::S3Fifo(_) => slots[index].increment_s3fifo_frequency(),
        }
    }

    pub fn remove(&mut self, slots: &mut [PolicySlot], index: usize) {
        if !slots.get(index).is_some_and(PolicySlot::is_resident) {
            return;
        }
        match &mut self.policy {
            EvictionPolicyState::Clock(state) => state.remove(slots, index),
            EvictionPolicyState::S3Fifo(state) => state.remove(slots, index),
        }
    }

    /// Detaches a resident only from policy metadata while admission gathers
    /// victims. The memory directory and value remain intact so a failed
    /// admission can restore the entry without losing a cache hit.
    pub fn detach_for_admission(
        &mut self,
        slots: &mut [PolicySlot],
        index: usize,
        weight: usize,
    ) -> DetachedPolicy {
        match &mut self.policy {
            EvictionPolicyState::Clock(state) => {
                let hash = slots[index].hash();
                state.remove(slots, index);
                DetachedPolicy {
                    hash,
                    weight,
                    kind: DetachedPolicyKind::Clock,
                }
            }
            EvictionPolicyState::S3Fifo(state) => state.detach(slots, index, weight),
        }
    }

    pub fn restore_for_admission(
        &mut self,
        slots: &mut [PolicySlot],
        index: usize,
        detached: DetachedPolicy,
    ) {
        debug_assert!(!slots[index].is_resident());
        match (&mut self.policy, detached.kind) {
            (EvictionPolicyState::Clock(state), DetachedPolicyKind::Clock) => {
                // A failed admission is optional work and must not make its
                // temporarily detached victim immediately vulnerable again.
                state.insert(slots, index, detached.hash, true);
            }
            (
                EvictionPolicyState::S3Fifo(state),
                DetachedPolicyKind::S3Fifo { queue, frequency },
            ) => state.restore(
                slots,
                index,
                detached.hash,
                detached.weight,
                queue,
                frequency,
            ),
            _ => unreachable!("detached L1 policy does not match the configured policy"),
        }
    }

    /// Records policy history only after the associated memory victim commits.
    pub fn commit_eviction(&mut self, detached: DetachedPolicy) {
        match (&mut self.policy, detached.kind) {
            (EvictionPolicyState::Clock(_), DetachedPolicyKind::Clock) => {}
            (EvictionPolicyState::S3Fifo(state), DetachedPolicyKind::S3Fifo { queue, .. }) => {
                if queue == QueueKind::Small {
                    state.ghost.insert(detached.hash, detached.weight);
                }
            }
            _ => unreachable!("detached L1 policy does not match the configured policy"),
        }
    }

    pub fn select_victim<F>(
        &mut self,
        slots: &mut [PolicySlot],
        remaining_steps: &mut usize,
        can_reclaim: F,
    ) -> Option<usize>
    where
        F: Fn(usize) -> bool,
    {
        match &mut self.policy {
            EvictionPolicyState::Clock(state) => {
                state.select_victim(slots, remaining_steps, can_reclaim)
            }
            EvictionPolicyState::S3Fifo(state) => {
                state.select_victim(slots, remaining_steps, can_reclaim)
            }
        }
    }
}

struct ClockState {
    hand: usize,
    residents: Vec<u32>,
}

impl ClockState {
    fn new(maximum_entries: usize) -> io::Result<Self> {
        let mut residents = Vec::new();
        residents.try_reserve_exact(maximum_entries).map_err(|_| {
            io::Error::new(
                io::ErrorKind::OutOfMemory,
                "cannot allocate CLOCK resident positions",
            )
        })?;
        Ok(Self { hand: 0, residents })
    }

    fn allocation_bytes(maximum_entries: usize) -> io::Result<usize> {
        maximum_entries
            .checked_mul(size_of::<u32>())
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "CLOCK is too large"))
    }

    fn insert(&mut self, slots: &mut [PolicySlot], index: usize, hash: u64, visited: bool) {
        assert!(
            self.residents.len() < slots.len() && self.residents.len() < self.residents.capacity(),
            "CLOCK resident capacity exhausted"
        );
        let position = u32::try_from(self.residents.len())
            .expect("validated CLOCK resident position exceeds u32");
        let packed_index =
            u32::try_from(index).expect("validated CLOCK resident index exceeds u32");
        slots[index] = PolicySlot::new_clock(hash, visited, position);
        self.residents.push(packed_index);
    }

    fn remove(&mut self, slots: &mut [PolicySlot], index: usize) {
        let position = usize::try_from(slots[index].clock_position())
            .expect("CLOCK resident position exceeds usize");
        let removed = self.residents.swap_remove(position);
        debug_assert_eq!(usize::try_from(removed).ok(), Some(index));
        if position < self.residents.len() {
            let moved = usize::try_from(self.residents[position])
                .expect("CLOCK resident index exceeds usize");
            slots[moved].set_clock_position(
                u32::try_from(position).expect("CLOCK resident position exceeds u32"),
            );
        }
        slots[index] = PolicySlot::default();

        if self.hand >= self.residents.len() {
            self.hand = 0;
        }
    }

    fn select_victim<F>(
        &mut self,
        slots: &mut [PolicySlot],
        remaining_steps: &mut usize,
        can_reclaim: F,
    ) -> Option<usize>
    where
        F: Fn(usize) -> bool,
    {
        for _ in 0..maximum_scan_steps(self.residents.len()) {
            if self.residents.is_empty() || !take_scan_step(remaining_steps) {
                break;
            }
            let position = if self.hand < self.residents.len() {
                self.hand
            } else {
                0
            };
            self.hand = if position + 1 == self.residents.len() {
                0
            } else {
                position + 1
            };
            let index = usize::try_from(self.residents[position])
                .expect("CLOCK resident index exceeds usize");
            let slot = &mut slots[index];
            debug_assert!(slot.is_resident());
            if slot.clock_visited() {
                slot.set_clock_visited(false);
                continue;
            }
            if can_reclaim(index) {
                return Some(index);
            }
        }
        None
    }
}

#[derive(Clone, Copy)]
struct S3FifoLink {
    previous: u32,
    next: u32,
    weight: u32,
}

impl Default for S3FifoLink {
    fn default() -> Self {
        Self {
            previous: NO_POLICY_SLOT,
            next: NO_POLICY_SLOT,
            weight: 0,
        }
    }
}

struct PolicyQueue {
    head: u32,
    tail: u32,
    bytes: usize,
}

impl PolicyQueue {
    const fn empty() -> Self {
        Self {
            head: NO_POLICY_SLOT,
            tail: NO_POLICY_SLOT,
            bytes: 0,
        }
    }

    fn is_empty(&self) -> bool {
        self.head == NO_POLICY_SLOT
    }

    fn front(&self) -> Option<usize> {
        (self.head != NO_POLICY_SLOT)
            .then(|| usize::try_from(self.head).expect("policy slot index exceeds usize"))
    }

    fn push_back(&mut self, links: &mut [S3FifoLink], index: usize, weight: usize) {
        let packed = u32::try_from(index).expect("policy slot index exceeds u32");
        let packed_weight = u32::try_from(weight).expect("L1 entry weight exceeds u32");
        debug_assert_eq!(links[index].weight, 0);
        links[index] = S3FifoLink {
            previous: self.tail,
            next: NO_POLICY_SLOT,
            weight: packed_weight,
        };
        if self.tail == NO_POLICY_SLOT {
            self.head = packed;
        } else {
            let tail = usize::try_from(self.tail).expect("policy slot index exceeds usize");
            links[tail].next = packed;
        }
        self.tail = packed;
        self.bytes = self.bytes.saturating_add(weight);
    }

    fn remove(&mut self, links: &mut [S3FifoLink], index: usize) -> usize {
        let packed = u32::try_from(index).expect("policy slot index exceeds u32");
        let link = links[index];
        debug_assert_ne!(link.weight, 0);
        if link.previous == NO_POLICY_SLOT {
            debug_assert_eq!(self.head, packed);
            self.head = link.next;
        } else {
            let previous = usize::try_from(link.previous).expect("policy slot index exceeds usize");
            links[previous].next = link.next;
        }
        if link.next == NO_POLICY_SLOT {
            debug_assert_eq!(self.tail, packed);
            self.tail = link.previous;
        } else {
            let next = usize::try_from(link.next).expect("policy slot index exceeds usize");
            links[next].previous = link.previous;
        }
        links[index] = S3FifoLink::default();
        let weight = link.weight as usize;
        self.bytes = self.bytes.saturating_sub(weight);
        weight
    }

    fn move_to_back(&mut self, links: &mut [S3FifoLink], index: usize) {
        let packed = u32::try_from(index).expect("policy slot index exceeds u32");
        if self.tail == packed {
            return;
        }
        let weight = self.remove(links, index);
        self.push_back(links, index, weight);
    }
}

struct S3FifoState {
    links: Box<[S3FifoLink]>,
    small: PolicyQueue,
    main: PolicyQueue,
    main_capacity_bytes: usize,
    ghost: GhostQueue,
}

impl S3FifoState {
    fn new(capacity_bytes: usize, maximum_entries: usize) -> io::Result<Self> {
        let mut links = Vec::new();
        links.try_reserve_exact(maximum_entries).map_err(|_| {
            io::Error::new(
                io::ErrorKind::OutOfMemory,
                "cannot allocate S3-FIFO resident links",
            )
        })?;
        links.resize(maximum_entries, S3FifoLink::default());
        let small_capacity_bytes = capacity_bytes / 10;
        let main_capacity_bytes = capacity_bytes.saturating_sub(small_capacity_bytes);
        Ok(Self {
            links: links.into_boxed_slice(),
            small: PolicyQueue::empty(),
            main: PolicyQueue::empty(),
            main_capacity_bytes,
            ghost: GhostQueue::new(maximum_entries, main_capacity_bytes)?,
        })
    }

    fn allocation_bytes(maximum_entries: usize) -> io::Result<usize> {
        let links = maximum_entries
            .checked_mul(size_of::<S3FifoLink>())
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "S3-FIFO is too large"))?;
        links
            .checked_add(GhostQueue::allocation_bytes(maximum_entries)?)
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "S3-FIFO is too large"))
    }

    fn insert(&mut self, slots: &mut [PolicySlot], index: usize, hash: u64, weight: usize) {
        let queue = if self.ghost.take(hash) {
            QueueKind::Main
        } else {
            QueueKind::Small
        };
        slots[index] = PolicySlot::new_s3fifo(hash, queue, 0);
        self.push_back(queue, index, weight);
    }

    fn remove(&mut self, slots: &mut [PolicySlot], index: usize) {
        let queue = slots[index].s3fifo_queue();
        self.remove_from(queue, index);
        slots[index] = PolicySlot::default();
    }

    fn detach(
        &mut self,
        slots: &mut [PolicySlot],
        index: usize,
        expected_weight: usize,
    ) -> DetachedPolicy {
        let slot = slots[index];
        let queue = slot.s3fifo_queue();
        let frequency = slot.s3fifo_frequency();
        let weight = self.remove_from(queue, index);
        debug_assert_eq!(weight, expected_weight);
        slots[index] = PolicySlot::default();
        DetachedPolicy {
            hash: slot.hash(),
            weight,
            kind: DetachedPolicyKind::S3Fifo { queue, frequency },
        }
    }

    fn restore(
        &mut self,
        slots: &mut [PolicySlot],
        index: usize,
        hash: u64,
        weight: usize,
        queue: QueueKind,
        frequency: u8,
    ) {
        slots[index] = PolicySlot::new_s3fifo(hash, queue, frequency);
        self.push_back(queue, index, weight);
    }

    fn select_victim<F>(
        &mut self,
        slots: &mut [PolicySlot],
        remaining_steps: &mut usize,
        can_reclaim: F,
    ) -> Option<usize>
    where
        F: Fn(usize) -> bool,
    {
        let mut prefer_small = false;
        for _ in 0..maximum_scan_steps(slots.len()) {
            if !take_scan_step(remaining_steps) {
                break;
            }
            let queue = if prefer_small && !self.small.is_empty() {
                prefer_small = false;
                QueueKind::Small
            } else if self.main.bytes > self.main_capacity_bytes || self.small.is_empty() {
                QueueKind::Main
            } else {
                QueueKind::Small
            };
            let index = self.queue(queue).front()?;
            let frequency = slots[index].s3fifo_frequency();
            match queue {
                QueueKind::Small if frequency >= S3FIFO_MOVE_TO_MAIN_THRESHOLD => {
                    let weight = self.small.remove(&mut self.links, index);
                    slots[index].set_s3fifo_queue(QueueKind::Main);
                    self.main.push_back(&mut self.links, index, weight);
                }
                QueueKind::Main if frequency > 0 => {
                    slots[index].set_s3fifo_frequency(frequency - 1);
                    self.main.move_to_back(&mut self.links, index);
                }
                _ if can_reclaim(index) => return Some(index),
                QueueKind::Small => {
                    // A caller-retained value cannot release its memory charge.
                    // Move it out of the probationary head so one retained
                    // entry cannot consume the complete admission budget.
                    let weight = self.small.remove(&mut self.links, index);
                    slots[index].set_s3fifo_queue(QueueKind::Main);
                    self.main.push_back(&mut self.links, index, weight);
                }
                QueueKind::Main => {
                    self.main.move_to_back(&mut self.links, index);
                    prefer_small = true;
                }
            }
        }
        None
    }

    fn queue(&self, queue: QueueKind) -> &PolicyQueue {
        match queue {
            QueueKind::Small => &self.small,
            QueueKind::Main => &self.main,
        }
    }

    fn push_back(&mut self, queue: QueueKind, index: usize, weight: usize) {
        let links = &mut self.links;
        match queue {
            QueueKind::Small => self.small.push_back(links, index, weight),
            QueueKind::Main => self.main.push_back(links, index, weight),
        }
    }

    fn remove_from(&mut self, queue: QueueKind, index: usize) -> usize {
        let links = &mut self.links;
        match queue {
            QueueKind::Small => self.small.remove(links, index),
            QueueKind::Main => self.main.remove(links, index),
        }
    }
}

struct GhostQueue {
    directory: FixedPrehashedMap,
    hashes: Box<[u64]>,
    links: Box<[S3FifoLink]>,
    free_head: u32,
    free_count: usize,
    head: u32,
    tail: u32,
    bytes: usize,
    capacity_bytes: usize,
}

impl GhostQueue {
    fn new(maximum_entries: usize, capacity_bytes: usize) -> io::Result<Self> {
        let directory = FixedPrehashedMap::try_new(maximum_entries)?;
        let mut hashes = Vec::new();
        hashes.try_reserve_exact(maximum_entries).map_err(|_| {
            io::Error::new(
                io::ErrorKind::OutOfMemory,
                "cannot allocate S3-FIFO ghost hashes",
            )
        })?;
        hashes.resize(maximum_entries, 0);
        let mut links = Vec::new();
        links.try_reserve_exact(maximum_entries).map_err(|_| {
            io::Error::new(
                io::ErrorKind::OutOfMemory,
                "cannot allocate S3-FIFO ghost links",
            )
        })?;
        links.resize(maximum_entries, S3FifoLink::default());
        for (index, link) in links.iter_mut().enumerate() {
            link.next = if index + 1 == maximum_entries {
                NO_POLICY_SLOT
            } else {
                u32::try_from(index + 1).expect("validated L1 entry capacity exceeds u32")
            };
        }
        Ok(Self {
            directory,
            hashes: hashes.into_boxed_slice(),
            links: links.into_boxed_slice(),
            free_head: if maximum_entries == 0 {
                NO_POLICY_SLOT
            } else {
                0
            },
            free_count: maximum_entries,
            head: NO_POLICY_SLOT,
            tail: NO_POLICY_SLOT,
            bytes: 0,
            capacity_bytes,
        })
    }

    fn allocation_bytes(maximum_entries: usize) -> io::Result<usize> {
        let hashes = maximum_entries
            .checked_mul(size_of::<u64>())
            .ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidInput, "ghost queue is too large")
            })?;
        let links = maximum_entries
            .checked_mul(size_of::<S3FifoLink>())
            .ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidInput, "ghost queue is too large")
            })?;
        FixedPrehashedMap::allocation_bytes(maximum_entries)?
            .checked_add(hashes)
            .and_then(|bytes| bytes.checked_add(links))
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "ghost queue is too large"))
    }

    fn take(&mut self, hash: u64) -> bool {
        let Some(packed) = self.directory.remove(hash) else {
            return false;
        };
        let index = usize::try_from(packed).expect("ghost slot index exceeds usize");
        // Ghost history is optional: a fingerprint collision may discard one
        // old hint, but it must never turn into a false ghost hit.
        let matched = self.hashes[index] == hash;
        self.unlink(index);
        matched
    }

    fn insert(&mut self, hash: u64, weight: usize) {
        let Ok(packed_weight) = u32::try_from(weight) else {
            return;
        };
        if packed_weight == 0
            || weight > self.capacity_bytes
            || self.links.is_empty()
            || self.capacity_bytes == 0
        {
            return;
        }
        if self.free_head == NO_POLICY_SLOT
            || self.bytes.saturating_add(weight) > self.capacity_bytes
        {
            let Some(head) = self.head_index() else {
                return;
            };
            let head_weight = self.links[head].weight as usize;
            if self
                .bytes
                .saturating_sub(head_weight)
                .saturating_add(weight)
                > self.capacity_bytes
            {
                // Mixed sizes can require many tiny ghost removals for one
                // large record. Preserve the existing history and skip the
                // optional insert instead of adding a cleanup loop.
                return;
            }
            let removed = self.remove_head();
            debug_assert!(removed);
        }
        let packed = self.free_head;
        debug_assert_ne!(packed, NO_POLICY_SLOT);
        let index = usize::try_from(packed).expect("ghost slot index exceeds usize");
        self.free_head = self.links[index].next;
        debug_assert_ne!(self.free_count, 0);
        self.free_count -= 1;
        self.hashes[index] = hash;
        self.links[index] = S3FifoLink {
            previous: self.tail,
            next: NO_POLICY_SLOT,
            weight: packed_weight,
        };
        if self.tail == NO_POLICY_SLOT {
            self.head = packed;
        } else {
            let tail = usize::try_from(self.tail).expect("ghost slot index exceeds usize");
            self.links[tail].next = packed;
        }
        self.tail = packed;
        self.bytes = self.bytes.saturating_add(weight);
        match self.directory.insert(hash, packed) {
            Some(Some(previous)) => {
                let previous = usize::try_from(previous).expect("ghost slot index exceeds usize");
                self.unlink(previous);
            }
            Some(None) => {}
            None => self.unlink(index),
        }
    }

    fn remove_head(&mut self) -> bool {
        let Some(index) = self.head_index() else {
            return false;
        };
        let removed = self.directory.remove(self.hashes[index]);
        debug_assert_eq!(removed, Some(self.head));
        self.unlink(index);
        true
    }

    fn head_index(&self) -> Option<usize> {
        (self.head != NO_POLICY_SLOT)
            .then(|| usize::try_from(self.head).expect("ghost slot index exceeds usize"))
    }

    fn unlink(&mut self, index: usize) {
        let packed = u32::try_from(index).expect("ghost slot index exceeds u32");
        let link = self.links[index];
        debug_assert_ne!(link.weight, 0);
        if link.previous == NO_POLICY_SLOT {
            debug_assert_eq!(self.head, packed);
            self.head = link.next;
        } else {
            let previous = usize::try_from(link.previous).expect("ghost slot index exceeds usize");
            self.links[previous].next = link.next;
        }
        if link.next == NO_POLICY_SLOT {
            debug_assert_eq!(self.tail, packed);
            self.tail = link.previous;
        } else {
            let next = usize::try_from(link.next).expect("ghost slot index exceeds usize");
            self.links[next].previous = link.previous;
        }
        self.bytes = self.bytes.saturating_sub(link.weight as usize);
        self.hashes[index] = 0;
        self.links[index] = S3FifoLink {
            next: self.free_head,
            ..S3FifoLink::default()
        };
        self.free_head = packed;
        debug_assert!(self.free_count < self.links.len());
        self.free_count += 1;
    }
}

fn maximum_scan_steps(slot_count: usize) -> usize {
    slot_count
        .saturating_mul(2)
        .saturating_add(1)
        .min(MAX_POLICY_SCAN_STEPS)
}

fn take_scan_step(remaining_steps: &mut usize) -> bool {
    if *remaining_steps == 0 {
        false
    } else {
        *remaining_steps -= 1;
        true
    }
}

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

    fn policy(kind: L1EvictionPolicy, capacity: usize, entries: usize) -> EvictionState {
        EvictionState::new(kind, capacity, entries).unwrap()
    }

    fn install(
        policy: &mut EvictionState,
        slots: &mut Vec<PolicySlot>,
        hash: u64,
        weight: usize,
    ) -> usize {
        let index = slots.len();
        slots.push(PolicySlot::default());
        policy.insert(slots, index, hash, weight);
        index
    }

    #[test]
    fn clock_new_entries_are_immediately_evictable() {
        let mut policy = policy(L1EvictionPolicy::Clock, 1024, 2);
        let mut slots = Vec::new();
        let first = install(&mut policy, &mut slots, 1, 1);
        let second = install(&mut policy, &mut slots, 2, 1);
        let mut remaining_steps = MAX_POLICY_SCAN_STEPS;

        assert_eq!(
            policy.select_victim(&mut slots, &mut remaining_steps, |_| true),
            Some(first)
        );
        assert_eq!(
            policy.select_victim(&mut slots, &mut remaining_steps, |_| true),
            Some(second)
        );
    }

    #[test]
    fn clock_scans_residents_in_sparse_slot_arrays() {
        let mut policy = policy(L1EvictionPolicy::Clock, 1024, 128);
        let mut slots = vec![PolicySlot::default(); 128];
        policy.insert(&mut slots, 96, 7, 1);
        let mut remaining_steps = MAX_POLICY_SCAN_STEPS;

        assert_eq!(
            policy.select_victim(&mut slots, &mut remaining_steps, |_| true),
            Some(96)
        );
    }

    #[test]
    fn clock_removal_updates_a_moved_resident_position() {
        let mut policy = policy(L1EvictionPolicy::Clock, 1024, 8);
        let mut slots = vec![PolicySlot::default(); 8];
        policy.insert(&mut slots, 1, 1, 1);
        policy.insert(&mut slots, 4, 4, 1);
        policy.insert(&mut slots, 7, 7, 1);

        policy.remove(&mut slots, 4);
        policy.remove(&mut slots, 7);
        let mut remaining_steps = MAX_POLICY_SCAN_STEPS;

        assert_eq!(
            policy.select_victim(&mut slots, &mut remaining_steps, |_| true),
            Some(1)
        );
    }

    #[test]
    fn one_clock_admission_has_one_fixed_scan_budget() {
        let mut policy = policy(L1EvictionPolicy::Clock, 1024, 100);
        let mut slots = Vec::new();
        for hash in 0..100 {
            let index = install(&mut policy, &mut slots, hash, 1);
            policy.record_hit(&mut slots, index);
        }
        let mut remaining_steps = MAX_POLICY_SCAN_STEPS;

        assert_eq!(
            policy.select_victim(&mut slots, &mut remaining_steps, |_| true),
            None
        );
        assert_eq!(remaining_steps, 0);
    }

    #[test]
    fn failed_clock_plan_restores_a_detached_entry() {
        let mut policy = policy(L1EvictionPolicy::Clock, 1024, 1);
        let mut slots = Vec::new();
        let index = install(&mut policy, &mut slots, 7, 11);
        let detached = policy.detach_for_admission(&mut slots, index, 11);
        policy.restore_for_admission(&mut slots, index, detached);

        assert_eq!(slots[index].hash(), 7);
        assert!(slots[index].clock_visited());
    }

    #[test]
    fn clock_prefers_a_hit_over_a_cold_one_shot_entry() {
        let mut policy = policy(L1EvictionPolicy::Clock, 1024, 2);
        let mut slots = Vec::new();
        let hot = install(&mut policy, &mut slots, 1, 1);
        let cold = install(&mut policy, &mut slots, 2, 1);
        policy.record_hit(&mut slots, hot);
        let mut remaining_steps = MAX_POLICY_SCAN_STEPS;

        assert_eq!(
            policy.select_victim(&mut slots, &mut remaining_steps, |_| true),
            Some(cold)
        );
    }

    #[test]
    fn s3fifo_promotes_reused_small_entries_and_ghost_hits_enter_main() {
        let mut policy = policy(L1EvictionPolicy::S3Fifo, 1000, 10);
        let mut slots = Vec::new();
        for hash in 1..=10 {
            install(&mut policy, &mut slots, hash, 100);
        }
        policy.record_hit(&mut slots, 0);
        policy.record_hit(&mut slots, 0);
        let mut remaining_steps = MAX_POLICY_SCAN_STEPS;

        let victim = policy
            .select_victim(&mut slots, &mut remaining_steps, |_| true)
            .unwrap();
        assert_eq!(victim, 1);
        assert_eq!(slots[0].s3fifo_queue(), QueueKind::Main);
        let detached = policy.detach_for_admission(&mut slots, victim, 100);
        policy.commit_eviction(detached);

        policy.insert(&mut slots, victim, 2, 100);
        assert_eq!(slots[victim].s3fifo_queue(), QueueKind::Main);
    }

    #[test]
    fn s3fifo_main_frequency_is_consumed_with_a_fixed_budget() {
        let mut policy = policy(L1EvictionPolicy::S3Fifo, 100, 1);
        let mut slots = Vec::new();
        let hot = install(&mut policy, &mut slots, 7, 100);
        policy.record_hit(&mut slots, hot);
        policy.record_hit(&mut slots, hot);
        let mut remaining_steps = MAX_POLICY_SCAN_STEPS;

        assert_eq!(
            policy.select_victim(&mut slots, &mut remaining_steps, |_| true),
            None
        );
        assert_eq!(slots[hot].s3fifo_queue(), QueueKind::Main);
        assert_eq!(slots[hot].s3fifo_frequency(), 0);
        assert_eq!(
            policy.select_victim(&mut slots, &mut remaining_steps, |_| true),
            Some(hot)
        );
    }

    #[test]
    fn failed_s3fifo_plan_restores_queue_and_frequency() {
        let mut policy = policy(L1EvictionPolicy::S3Fifo, 1000, 1);
        let mut slots = Vec::new();
        let index = install(&mut policy, &mut slots, 7, 100);
        policy.record_hit(&mut slots, index);
        let detached = policy.detach_for_admission(&mut slots, index, 100);
        policy.restore_for_admission(&mut slots, index, detached);

        assert_eq!(slots[index].hash(), 7);
        assert_eq!(slots[index].s3fifo_queue(), QueueKind::Small);
        assert_eq!(slots[index].s3fifo_frequency(), 1);
    }

    #[test]
    fn retained_small_entry_does_not_block_a_reclaimable_follower() {
        let mut policy = policy(L1EvictionPolicy::S3Fifo, 1000, 2);
        let mut slots = Vec::new();
        let retained = install(&mut policy, &mut slots, 7, 100);
        let reclaimable = install(&mut policy, &mut slots, 8, 100);
        let mut remaining_steps = MAX_POLICY_SCAN_STEPS;

        assert_eq!(
            policy.select_victim(&mut slots, &mut remaining_steps, |index| index != retained),
            Some(reclaimable)
        );
        assert_eq!(slots[retained].s3fifo_queue(), QueueKind::Main);
    }

    #[test]
    fn mixed_size_ghost_insert_never_runs_a_multi_entry_cleanup() {
        let mut ghost = GhostQueue::new(3, 100).unwrap();
        ghost.insert(1, 10);
        ghost.insert(2, 10);
        ghost.insert(3, 80);

        // Removing the 10-byte head would still not fit this entry. Optional
        // history is skipped without gradually erasing the existing queue.
        ghost.insert(4, 80);

        assert_eq!(ghost.bytes, 100);
        assert_eq!(ghost.free_count, 0);
        assert_eq!(ghost.directory.get(1), Some(0));
        assert_eq!(ghost.directory.get(2), Some(1));
        assert_eq!(ghost.directory.get(3), Some(2));
        assert_eq!(ghost.directory.get(4), None);
    }

    #[test]
    fn ghost_storage_uses_twenty_bytes_per_entry() {
        const ENTRIES: usize = 5;
        assert_eq!(size_of::<S3FifoLink>(), 12);
        assert_eq!(
            GhostQueue::allocation_bytes(ENTRIES).unwrap()
                - FixedPrehashedMap::allocation_bytes(ENTRIES).unwrap(),
            ENTRIES * 20
        );
    }

    #[test]
    fn ghost_fingerprint_collision_is_not_a_false_hit() {
        let mut ghost = GhostQueue::new(2, 100).unwrap();
        let first = 1_u64;
        let colliding = 1_u64 << 45;
        ghost.insert(first, 10);

        assert!(!ghost.take(colliding));
        assert_eq!(ghost.bytes, 0);
        assert!(!ghost.take(first));
    }

    #[test]
    fn ghost_reuses_an_unlinked_slot() {
        let mut ghost = GhostQueue::new(2, 100).unwrap();
        ghost.insert(1, 10);
        ghost.insert(2, 10);
        assert!(ghost.take(1));

        ghost.insert(3, 10);

        assert_eq!(ghost.free_count, 0);
        assert_eq!(ghost.directory.get(3), Some(0));
    }
}