-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlazy_heap.rs
More file actions
2142 lines (1941 loc) · 72 KB
/
lazy_heap.rs
File metadata and controls
2142 lines (1941 loc) · 72 KB
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
//! Lazy min-heap with stale entry skipping.
//!
//! A priority queue that supports O(1) updates by deferring cleanup. Instead
//! of modifying heap entries in place, updates push new entries and mark old
//! ones as stale. The [`pop_best`](LazyMinHeap::pop_best) operation skips
//! stale entries automatically.
//!
//! ## Architecture
//!
//! ```text
//! ┌────────────────────────────────────────────────────────────────────────────┐
//! │ LazyMinHeap Layout │
//! │ │
//! │ ┌───────────────────────────────────────────────────────────────────┐ │
//! │ │ scores: HashMap<K, S> (authoritative source of truth) │ │
//! │ │ │ │
//! │ │ ┌─────────┬─────────┐ │ │
//! │ │ │ key │ score │ │ │
//! │ │ ├─────────┼─────────┤ │ │
//! │ │ │ "A" │ 10 │ │ │
//! │ │ │ "B" │ 3 │ │ │
//! │ │ │ "C" │ 7 │ │ │
//! │ │ └─────────┴─────────┘ │ │
//! │ │ │ │
//! │ │ len() = 3 (live entries) │ │
//! │ └───────────────────────────────────────────────────────────────────┘ │
//! │ │
//! │ ┌───────────────────────────────────────────────────────────────────┐ │
//! │ │ heap: BinaryHeap<Reverse<HeapEntry>> (may have stale entries) │ │
//! │ │ │ │
//! │ │ Min-heap order (smallest score first): │ │
//! │ │ │ │
//! │ │ ┌────────────────────────────────────────────────────────┐ │ │
//! │ │ │ ("B", 3, seq=5) ← current min, matches scores["B"] │ │ │
//! │ │ │ ("C", 7, seq=4) ← valid │ │ │
//! │ │ │ ("A", 10, seq=3) ← valid │ │ │
//! │ │ │ ("A", 15, seq=1) ← STALE: scores["A"]=10, not 15 │ │ │
//! │ │ │ ("B", 8, seq=2) ← STALE: scores["B"]=3, not 8 │ │ │
//! │ │ └────────────────────────────────────────────────────────┘ │ │
//! │ │ │ │
//! │ │ heap_len() = 5 (includes stale entries) │ │
//! │ └───────────────────────────────────────────────────────────────────┘ │
//! │ │
//! │ seq: 6 (monotonic counter for tie-breaking) │
//! └────────────────────────────────────────────────────────────────────────────┘
//!
//! Update Flow
//! ───────────
//! update("A", 10):
//! 1. scores["A"] = 10 (authoritative update)
//! 2. heap.push(("A", 10, seq)) (new entry, old entries become stale)
//! 3. seq += 1
//!
//! Pop Flow
//! ────────
//! pop_best():
//! loop:
//! entry = heap.pop() → ("A", 15, seq=1)
//! if scores["A"] == 15? → No! scores["A"]=10
//! skip (stale)
//! ...
//! entry = heap.pop() → ("B", 3, seq=5)
//! if scores["B"] == 3? → Yes!
//! scores.remove("B")
//! return ("B", 3)
//!
//! Rebuild
//! ───────
//! When heap_len >> len(), call rebuild() to clear stale entries:
//! heap.clear()
//! for (key, score) in scores:
//! heap.push((key, score, seq++))
//! ```
//!
//! ## Key Concepts
//!
//! - **Lazy deletion**: Old heap entries aren't removed; they're skipped when
//! their score doesn't match the authoritative `scores` map
//! - **Sequence numbers**: Break ties for equal scores (FIFO order)
//! - **Periodic rebuild**: When stale entries accumulate, `rebuild()` or
//! `maybe_rebuild()` cleans up the heap
//!
//! ## Operations
//!
//! | Operation | Description | Complexity |
//! |----------------|---------------------------------------|--------------------|
//! | `update` | Set/update score, push heap entry | O(log n) |
//! | `remove` | Remove from scores map only | O(1) |
//! | `pop_best` | Pop min, skipping stale entries | Amortized O(log n) |
//! | `score_of` | Get current score for key | O(1) |
//! | `rebuild` | Rebuild heap from scores map | O(n log n) |
//! | `maybe_rebuild`| Rebuild if heap too stale | O(1) or O(n log n) |
//!
//! ## Use Cases
//!
//! - **LFU eviction**: Track access frequencies, pop least-frequently-used
//! - **Priority scheduling**: Tasks with changing priorities
//! - **Expiration tracking**: Items with updatable TTLs
//!
//! ## Example Usage
//!
//! ```
//! use cachekit::ds::LazyMinHeap;
//!
//! let mut heap: LazyMinHeap<&str, u32> = LazyMinHeap::new();
//!
//! // Insert items with scores (lower = higher priority)
//! heap.update("task_a", 5);
//! heap.update("task_b", 2);
//! heap.update("task_c", 8);
//!
//! // Update a score (creates stale entry, doesn't remove old one)
//! heap.update("task_a", 1); // task_a now has priority 1
//!
//! // Pop returns minimum score, skipping stale entries
//! assert_eq!(heap.pop_best(), Some(("task_a", 1)));
//! assert_eq!(heap.pop_best(), Some(("task_b", 2)));
//! assert_eq!(heap.pop_best(), Some(("task_c", 8)));
//! assert_eq!(heap.pop_best(), None);
//! ```
//!
//! ## Performance Trade-offs
//!
//! - **Fast updates**: O(log n) push, no removal needed
//! - **Memory overhead**: Stale entries consume space until rebuilt
//! - **Rebuild cost**: O(n log n) but only when heap grows too stale
//!
//! ## Thread Safety
//!
//! `LazyMinHeap` is not thread-safe. Wrap in a mutex for concurrent access.
//!
//! ## Security Considerations
//!
//! `LazyMinHeap` is intended for internal bookkeeping inside eviction
//! policies and similar trusted subsystems. Calls are assumed to come
//! from in-process code, **not** directly from adversary-controlled
//! input. The hardening below addresses the exposure paths that remain
//! when the key set or the call volume is influenced by untrusted
//! input.
//!
//! - **Unbounded memory growth via stale entries.** [`update`] pushes a
//! new heap entry on every call; the old entry is not removed, it is
//! skipped by [`pop_best`]. An attacker that can drive
//! [`update`] on the same (small) key set faster than the caller
//! drains via [`pop_best`] or
//! [`rebuild`] can grow the heap without bound even though
//! [`len`](LazyMinHeap::len) stays tiny. Pair the heap with a bounded
//! rebuild cadence — either call [`maybe_rebuild`] on a schedule, or
//! construct the heap with
//! [`LazyMinHeap::with_auto_rebuild`] /
//! [`LazyMinHeap::set_auto_rebuild`] so every [`update`] runs a
//! [`maybe_rebuild`] with the configured factor.
//! - **Constructor DoS via oversized capacity.** [`with_capacity`],
//! [`reserve`], and [`from_iter`] forward their argument straight
//! into `HashMap` / `BinaryHeap` allocation. A capacity close to
//! `usize::MAX` would abort the process inside the allocator. Both
//! public constructors now reject capacities above
//! [`MAX_CAPACITY`]. For attacker-influenced capacity, prefer the
//! fallible [`try_with_capacity`] /
//! [`try_reserve`] variants, which surface the error as a
//! [`LazyMinHeapError`] instead of aborting.
//! - **Sequence-number wraparound.** The [`pop_best`] staleness check
//! relies on `(score, seq)` being unique across live and stale heap
//! entries for the same key. The counter is `u64`, so wrap is only
//! reachable after ≈ 2⁶⁴ `update` calls, but a wrap would let a
//! stale heap entry satisfy the equality check and be popped as if
//! live. The counter is now guarded by `checked_add`; on imminent
//! overflow the heap renumbers every live entry with fresh
//! sequential seqs and resets the counter, preserving FIFO
//! tie-breaking order.
//! - **`approx_bytes` overflow.** The old formula `capacity *
//! size_of::<…>()` could overflow `usize` for pathologically large
//! capacities. `approx_bytes` now uses `saturating_mul` /
//! `saturating_add` and returns `usize::MAX` in the saturating case
//! rather than panicking in debug or wrapping silently in release.
//! - **`Debug` output leaks keys and scores.** The derived `Debug`
//! recursed through every `(key, score)` pair and every stale heap
//! entry, turning `tracing::debug!`, `dbg!`, and panic-unwind
//! backtraces into a disclosure channel for caches keyed on session
//! tokens / API keys. The impl is now hand-written and redacts every
//! stored key and score, reporting only `len`, `heap_len`, and
//! whether auto-rebuild is configured. Callers that need full
//! contents can iterate via [`iter`](LazyMinHeap::iter) or
//! [`into_iter`](LazyMinHeap#impl-IntoIterator) and log entries they
//! have vetted.
//!
//! Thread-safety, timing side channels from the backing `HashMap`, and
//! the lack of bytes-level budgeting mirror
//! [`ClockRing`](crate::ds::ClockRing); consult its module docs for
//! the same set of caveats.
//!
//! ## Implementation Notes
//!
//! - Uses `BinaryHeap<Reverse<_>>` for min-heap behavior
//! - Tie-breaking uses sequence numbers for FIFO among equal scores
//!
//! [`update`]: LazyMinHeap::update
//! [`pop_best`]: LazyMinHeap::pop_best
//! [`rebuild`]: LazyMinHeap::rebuild
//! [`maybe_rebuild`]: LazyMinHeap::maybe_rebuild
//! [`len`]: LazyMinHeap::len
//! [`with_capacity`]: LazyMinHeap::with_capacity
//! [`reserve`]: LazyMinHeap::reserve
//! [`try_with_capacity`]: LazyMinHeap::try_with_capacity
//! [`try_reserve`]: LazyMinHeap::try_reserve
//! [`from_iter`]: LazyMinHeap#impl-FromIterator%3C(K,+S)%3E
use std::borrow::Borrow;
use std::cmp::{Ordering, Reverse};
use std::collections::{BinaryHeap, HashMap};
use std::fmt;
use std::hash::Hash;
use std::iter::FusedIterator;
/// Coarse upper bound on `capacity` accepted by
/// [`LazyMinHeap::with_capacity`] / [`LazyMinHeap::try_with_capacity`]
/// and [`LazyMinHeap::reserve`] / [`LazyMinHeap::try_reserve`].
///
/// This is a *first* guard that rejects obviously pathological values
/// cheaply. It is intentionally permissive: for any key/score size
/// larger than a few bytes, allocating `MAX_CAPACITY` entries would
/// still exhaust memory. The fallible constructors defend against
/// that separately by using `HashMap::try_reserve` / `Vec::try_reserve`,
/// so out-of-memory conditions surface as
/// [`LazyMinHeapError::AllocationFailed`] rather than aborting the
/// process.
pub const MAX_CAPACITY: usize = isize::MAX as usize / 64;
/// Error returned by [`LazyMinHeap::try_with_capacity`],
/// [`LazyMinHeap::try_reserve`], and [`LazyMinHeap::try_rebuild`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LazyMinHeapError {
/// The requested capacity exceeds [`MAX_CAPACITY`].
CapacityTooLarge {
/// The capacity that was requested.
requested: usize,
/// The configured upper bound.
max: usize,
},
/// The allocator could not satisfy the reservation for the
/// requested capacity.
///
/// Returned instead of aborting the process when `capacity *
/// size_of::<_>()` exceeds what the allocator can provide
/// (including the case where the byte count overflows
/// `isize::MAX`).
AllocationFailed {
/// The capacity whose allocation failed.
requested: usize,
},
}
impl fmt::Display for LazyMinHeapError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LazyMinHeapError::CapacityTooLarge { requested, max } => {
write!(f, "LazyMinHeap capacity {requested} exceeds maximum {max}")
},
LazyMinHeapError::AllocationFailed { requested } => {
write!(
f,
"LazyMinHeap failed to allocate backing storage for capacity {requested}"
)
},
}
}
}
impl std::error::Error for LazyMinHeapError {}
#[derive(Debug, Clone)]
struct HeapEntry<K, S> {
score: S,
seq: u64,
key: K,
}
impl<K, S> PartialEq for HeapEntry<K, S>
where
S: Ord,
{
fn eq(&self, other: &Self) -> bool {
self.score == other.score && self.seq == other.seq
}
}
impl<K, S> Eq for HeapEntry<K, S> where S: Ord {}
impl<K, S> PartialOrd for HeapEntry<K, S>
where
S: Ord,
{
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<K, S> Ord for HeapEntry<K, S>
where
S: Ord,
{
fn cmp(&self, other: &Self) -> Ordering {
match self.score.cmp(&other.score) {
Ordering::Equal => self.seq.cmp(&other.seq),
ordering => ordering,
}
}
}
/// Min-heap with O(1) score updates via lazy deletion.
///
/// Maintains an authoritative `scores` map and a heap that may contain stale
/// entries. Updates modify the map and push new heap entries; old entries
/// are skipped during [`pop_best`](Self::pop_best).
///
/// # Type Parameters
///
/// - `K`: Key type (must be `Eq + Hash + Clone`)
/// - `S`: Score type (must be `Ord + Clone`)
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::new();
///
/// // Track item priorities
/// heap.update("low", 10);
/// heap.update("high", 1);
/// heap.update("medium", 5);
///
/// // Pop in priority order (lowest score first)
/// assert_eq!(heap.pop_best(), Some(("high", 1)));
/// assert_eq!(heap.pop_best(), Some(("medium", 5)));
/// assert_eq!(heap.pop_best(), Some(("low", 10)));
/// ```
///
/// # Use Case: LFU Cache Eviction
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// // Track access counts (lower = less frequently used)
/// let mut freq: LazyMinHeap<&str, u32> = LazyMinHeap::new();
///
/// // Record accesses
/// freq.update("page_a", 1);
/// freq.update("page_b", 1);
/// freq.update("page_a", 2); // accessed again
/// freq.update("page_c", 1);
/// freq.update("page_a", 3); // accessed again
///
/// // Evict least frequently used
/// if let Some((victim, _count)) = freq.pop_best() {
/// assert!(victim == "page_b" || victim == "page_c"); // Both have count 1
/// }
/// ```
#[derive(Clone)]
pub struct LazyMinHeap<K, S> {
scores: HashMap<K, ScoreEntry<S>>,
heap: BinaryHeap<Reverse<HeapEntry<K, S>>>,
seq: u64,
/// When `Some(factor)`, every [`update`](Self::update) finishes
/// with a [`maybe_rebuild`](Self::maybe_rebuild) call at the
/// configured factor, bounding stale heap growth at roughly
/// `len() * factor` entries.
auto_rebuild: Option<usize>,
}
impl<K, S> fmt::Debug for LazyMinHeap<K, S> {
/// Redacted `Debug` output.
///
/// Historical derived `Debug` recursed through every `(key,
/// score)` pair and every stale heap entry, which exposed all
/// cache keys via `tracing::debug!`, `dbg!`, and panic
/// backtraces. This impl deliberately does **not** require
/// `K: Debug` / `S: Debug` and reports only aggregate counters.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LazyMinHeap")
.field("len", &self.scores.len())
.field("heap_len", &self.heap.len())
.field("seq", &self.seq)
.field("auto_rebuild_factor", &self.auto_rebuild)
.finish_non_exhaustive()
}
}
impl<K, S> LazyMinHeap<K, S>
where
K: Eq + Hash + Clone,
S: Ord + Clone,
{
/// Creates an empty heap.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let heap: LazyMinHeap<String, u32> = LazyMinHeap::new();
/// assert!(heap.is_empty());
/// ```
pub fn new() -> Self {
Self {
scores: HashMap::new(),
heap: BinaryHeap::new(),
seq: 0,
auto_rebuild: None,
}
}
/// Creates an empty heap with pre-allocated capacity.
///
/// # Panics
///
/// Panics if `capacity > MAX_CAPACITY`. Use
/// [`try_with_capacity`](Self::try_with_capacity) for a fallible
/// variant that surfaces allocator failure as a
/// [`LazyMinHeapError`].
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let heap: LazyMinHeap<i32, i32> = LazyMinHeap::with_capacity(1000);
/// assert!(heap.is_empty());
/// ```
#[track_caller]
pub fn with_capacity(capacity: usize) -> Self {
Self::try_with_capacity(capacity)
.expect("LazyMinHeap::with_capacity: capacity exceeds MAX_CAPACITY")
}
/// Fallible [`with_capacity`](Self::with_capacity).
///
/// Returns [`LazyMinHeapError::CapacityTooLarge`] when `capacity`
/// exceeds [`MAX_CAPACITY`], or
/// [`LazyMinHeapError::AllocationFailed`] when the allocator
/// cannot satisfy the reservation.
///
/// # Example
///
/// ```
/// use cachekit::ds::{LazyMinHeap, MAX_CAPACITY};
///
/// let heap: LazyMinHeap<i32, i32> =
/// LazyMinHeap::try_with_capacity(1000).unwrap();
/// assert!(heap.is_empty());
///
/// assert!(LazyMinHeap::<u32, u32>::try_with_capacity(MAX_CAPACITY + 1).is_err());
/// ```
pub fn try_with_capacity(capacity: usize) -> Result<Self, LazyMinHeapError> {
if capacity > MAX_CAPACITY {
return Err(LazyMinHeapError::CapacityTooLarge {
requested: capacity,
max: MAX_CAPACITY,
});
}
let mut scores: HashMap<K, ScoreEntry<S>> = HashMap::new();
scores
.try_reserve(capacity)
.map_err(|_| LazyMinHeapError::AllocationFailed {
requested: capacity,
})?;
let mut heap_vec: Vec<Reverse<HeapEntry<K, S>>> = Vec::new();
heap_vec
.try_reserve_exact(capacity)
.map_err(|_| LazyMinHeapError::AllocationFailed {
requested: capacity,
})?;
Ok(Self {
scores,
heap: BinaryHeap::from(heap_vec),
seq: 0,
auto_rebuild: None,
})
}
/// Reserves capacity for at least `additional` more entries.
///
/// # Panics
///
/// Panics if the post-reservation capacity would exceed
/// [`MAX_CAPACITY`] or if the allocator aborts. Use
/// [`try_reserve`](Self::try_reserve) for a fallible variant.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<i32, i32> = LazyMinHeap::new();
/// heap.reserve(100);
/// ```
#[track_caller]
pub fn reserve(&mut self, additional: usize) {
self.try_reserve(additional)
.expect("LazyMinHeap::reserve: capacity exceeds MAX_CAPACITY");
}
/// Fallible [`reserve`](Self::reserve).
///
/// Returns [`LazyMinHeapError::CapacityTooLarge`] when the
/// requested total would exceed [`MAX_CAPACITY`], or
/// [`LazyMinHeapError::AllocationFailed`] when the allocator
/// cannot satisfy the reservation.
pub fn try_reserve(&mut self, additional: usize) -> Result<(), LazyMinHeapError> {
let projected = self.scores.len().checked_add(additional).ok_or(
LazyMinHeapError::CapacityTooLarge {
requested: additional,
max: MAX_CAPACITY,
},
)?;
if projected > MAX_CAPACITY {
return Err(LazyMinHeapError::CapacityTooLarge {
requested: projected,
max: MAX_CAPACITY,
});
}
self.scores
.try_reserve(additional)
.map_err(|_| LazyMinHeapError::AllocationFailed {
requested: additional,
})?;
// `BinaryHeap::try_reserve` is not stable. Reserve the
// backing `Vec` indirectly by swapping the heap out into a
// `Vec`, calling `try_reserve` on that, then swapping the
// heap back in. Crucially, we swap the heap back even on
// reservation failure so that partial allocator pressure
// does not silently wipe the heap's contents.
let mut vec: Vec<Reverse<HeapEntry<K, S>>> = std::mem::take(&mut self.heap).into_vec();
let reserve_result = vec.try_reserve(additional);
self.heap = BinaryHeap::from(vec);
reserve_result.map_err(|_| LazyMinHeapError::AllocationFailed {
requested: additional,
})
}
/// Enables automatic [`maybe_rebuild`](Self::maybe_rebuild) on
/// every [`update`](Self::update), bounding stale heap growth.
///
/// `factor` follows the same convention as
/// [`maybe_rebuild`](Self::maybe_rebuild): a rebuild triggers
/// when `heap_len() > len() * factor`. Values below `1` are
/// clamped to `1`. Pass this value to the builder to mitigate the
/// unbounded-growth DoS described in the module-level **Security
/// Considerations** section.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, u32> =
/// LazyMinHeap::with_auto_rebuild(4);
/// for i in 0..1_000 {
/// heap.update("hot", i);
/// }
/// // heap_len stays bounded rather than growing to 1_000.
/// assert!(heap.heap_len() <= 4);
/// ```
pub fn with_auto_rebuild(factor: usize) -> Self {
let mut heap = Self::new();
heap.set_auto_rebuild(Some(factor));
heap
}
/// Configures automatic rebuild on [`update`](Self::update).
///
/// Passing `None` disables auto-rebuild (the default). Passing
/// `Some(factor)` mirrors [`with_auto_rebuild`](Self::with_auto_rebuild).
pub fn set_auto_rebuild(&mut self, factor: Option<usize>) {
self.auto_rebuild = factor.map(|f| f.max(1));
}
/// Returns the currently configured auto-rebuild factor, if any.
pub fn auto_rebuild_factor(&self) -> Option<usize> {
self.auto_rebuild
}
/// Shrinks internal storage to fit current contents.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<i32, i32> = LazyMinHeap::with_capacity(1000);
/// heap.update(1, 10);
/// heap.shrink_to_fit();
/// ```
pub fn shrink_to_fit(&mut self) {
self.scores.shrink_to_fit();
self.heap.shrink_to_fit();
}
/// Clears all entries, retaining allocated capacity.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::with_capacity(100);
/// heap.update("a", 1);
/// heap.update("b", 2);
///
/// heap.clear();
/// assert!(heap.is_empty());
/// ```
pub fn clear(&mut self) {
self.scores.clear();
self.heap.clear();
}
/// Clears all entries and shrinks internal storage.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::new();
/// heap.update("a", 1);
/// heap.update("b", 2);
///
/// heap.clear_shrink();
/// assert!(heap.is_empty());
/// ```
pub fn clear_shrink(&mut self) {
self.clear();
self.scores.shrink_to_fit();
self.heap.shrink_to_fit();
}
/// Returns the number of live keys.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::new();
/// assert_eq!(heap.len(), 0);
///
/// heap.update("a", 1);
/// heap.update("b", 2);
/// assert_eq!(heap.len(), 2);
/// ```
pub fn len(&self) -> usize {
self.scores.len()
}
/// Returns `true` if there are no live keys.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<i32, i32> = LazyMinHeap::new();
/// assert!(heap.is_empty());
///
/// heap.update(1, 10);
/// assert!(!heap.is_empty());
/// ```
pub fn is_empty(&self) -> bool {
self.scores.is_empty()
}
/// Returns the underlying heap length (may exceed `len()` due to stale entries).
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::new();
/// heap.update("a", 5);
/// heap.update("a", 3); // Creates stale entry
/// heap.update("a", 1); // Creates another stale entry
///
/// assert_eq!(heap.len(), 1); // 1 live key
/// assert_eq!(heap.heap_len(), 3); // 3 heap entries (2 stale)
/// ```
pub fn heap_len(&self) -> usize {
self.heap.len()
}
/// Iterates over live `(key, score)` pairs in arbitrary order.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::new();
/// heap.update("a", 1);
/// heap.update("b", 2);
///
/// let mut entries: Vec<_> = heap.iter().collect();
/// entries.sort();
/// assert_eq!(entries, vec![(&"a", &1), (&"b", &2)]);
/// ```
pub fn iter(&self) -> Iter<'_, K, S> {
Iter {
inner: self.scores.iter(),
}
}
/// Returns the current score for `key`, if present.
///
/// Accepts any borrowed form of the key type.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::new();
/// heap.update("task", 5);
///
/// assert_eq!(heap.score_of(&"task"), Some(&5));
/// assert_eq!(heap.score_of(&"missing"), None);
/// ```
pub fn score_of<Q>(&self, key: &Q) -> Option<&S>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.scores.get(key).map(|entry| &entry.score)
}
/// Updates `key`'s score and returns the previous score, if any.
///
/// Pushes a new heap entry; old entries become stale and are skipped
/// by [`pop_best`](Self::pop_best).
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::new();
///
/// // First insert
/// assert_eq!(heap.update("item", 10), None);
///
/// // Update returns old score
/// assert_eq!(heap.update("item", 5), Some(10));
/// assert_eq!(heap.score_of(&"item"), Some(&5));
/// ```
pub fn update(&mut self, key: K, score: S) -> Option<S> {
// Guard against sequence-number wraparound. After ~2^64
// updates the counter would otherwise wrap and a stale heap
// entry could satisfy the `(score, seq)` equality check in
// `pop_best`. Renumbering at the overflow boundary keeps the
// check sound.
if self.seq == u64::MAX {
self.renumber_seqs();
}
let seq = self.seq;
self.seq = self
.seq
.checked_add(1)
.expect("LazyMinHeap::update: seq overflow after renumber (unreachable)");
let previous = self.scores.insert(
key.clone(),
ScoreEntry {
score: score.clone(),
seq,
},
);
self.push_entry_with_seq(key, score, seq);
if let Some(factor) = self.auto_rebuild {
self.maybe_rebuild(factor);
}
previous.map(|entry| entry.score)
}
/// Renumbers all live entries with fresh sequential seqs and
/// resets the counter to `len()`.
///
/// Preserves FIFO tie-breaking order by sorting live entries by
/// their existing seq before renumbering. Called automatically on
/// [`update`](Self::update) at the overflow boundary; exposed here
/// so callers that retain heaps across extremely long-running
/// processes can force the renumber explicitly.
pub fn renumber_seqs(&mut self) {
// Drain live entries preserving original seq order so that
// equal-score keys keep their FIFO position post-renumber.
let mut live: Vec<(K, S, u64)> = self
.scores
.iter()
.map(|(k, entry)| (k.clone(), entry.score.clone(), entry.seq))
.collect();
live.sort_by_key(|(_, _, seq)| *seq);
self.scores.clear();
self.heap.clear();
self.seq = 0;
for (key, score, _) in live {
let seq = self.seq;
self.seq += 1;
self.scores.insert(
key.clone(),
ScoreEntry {
score: score.clone(),
seq,
},
);
self.push_entry_with_seq(key, score, seq);
}
}
/// Removes `key` and returns its score, if present.
///
/// Accepts any borrowed form of the key type. This only removes from
/// the authoritative map; stale heap entries will be skipped by
/// [`pop_best`](Self::pop_best).
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::new();
/// heap.update("a", 1);
/// heap.update("b", 2);
///
/// assert_eq!(heap.remove(&"a"), Some(1));
/// assert_eq!(heap.remove(&"a"), None); // Already removed
///
/// // "b" is still there
/// assert_eq!(heap.pop_best(), Some(("b", 2)));
/// ```
pub fn remove<Q>(&mut self, key: &Q) -> Option<S>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.scores.remove(key).map(|entry| entry.score)
}
/// Pops and returns the minimum `(key, score)`, skipping stale entries.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::new();
/// heap.update("high", 1);
/// heap.update("low", 10);
///
/// // Returns minimum score first
/// assert_eq!(heap.pop_best(), Some(("high", 1)));
/// assert_eq!(heap.pop_best(), Some(("low", 10)));
/// assert_eq!(heap.pop_best(), None);
/// ```
pub fn pop_best(&mut self) -> Option<(K, S)> {
loop {
let Reverse(entry) = self.heap.pop()?;
match self.scores.get(&entry.key) {
Some(current) if current.score == entry.score && current.seq == entry.seq => {
self.scores.remove(&entry.key);
return Some((entry.key, entry.score));
},
_ => continue,
}
}
}
/// Returns references to the minimum `(key, score)` without removing it.
///
/// Stale heap roots are discarded in place so the returned reference always
/// points at a live entry. Takes `&mut self` for that reason — repeated
/// calls without intervening updates are O(1).
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::new();
/// heap.update("high", 1);
/// heap.update("low", 10);
///
/// // peek does not consume.
/// assert_eq!(heap.peek_best(), Some((&"high", &1)));
/// assert_eq!(heap.peek_best(), Some((&"high", &1)));
/// assert_eq!(heap.len(), 2);
///
/// // pop_best returns the same entry peek_best showed.
/// assert_eq!(heap.pop_best(), Some(("high", 1)));
/// assert_eq!(heap.peek_best(), Some((&"low", &10)));
/// ```
pub fn peek_best(&mut self) -> Option<(&K, &S)> {
loop {
match self.heap.peek() {
Some(Reverse(top)) => {
let live = self.scores.get(&top.key).is_some_and(|current| {
current.score == top.score && current.seq == top.seq
});
if live {
break;
}
},
None => return None,
}
self.heap.pop();
}
let Reverse(top) = self.heap.peek()?;
self.scores
.get_key_value(&top.key)
.map(|(k, entry)| (k, &entry.score))
}
/// Rebuilds the heap from the authoritative `scores` map.
///
/// Removes all stale entries. Call this periodically or when
/// `heap_len()` greatly exceeds `len()`.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::new();
///
/// // Create many stale entries
/// for i in 0..10 {
/// heap.update("key", i);
/// }
/// assert_eq!(heap.len(), 1);
/// assert_eq!(heap.heap_len(), 10); // 9 stale entries
///
/// heap.rebuild();
/// assert_eq!(heap.heap_len(), 1); // Stale entries removed
/// ```
pub fn rebuild(&mut self) {
self.heap.clear();
let entries: Vec<(K, ScoreEntry<S>)> = self
.scores
.iter()
.map(|(key, entry)| (key.clone(), entry.clone()))
.collect();
for (key, entry) in entries {
self.push_entry_with_seq(key, entry.score, entry.seq);
}
}
/// Fallible [`rebuild`](Self::rebuild) that routes backing
/// allocations through `Vec::try_reserve_exact`.
///
/// Returns [`LazyMinHeapError::AllocationFailed`] without mutating
/// the heap when the allocator cannot satisfy the new heap
/// buffer. Prefer this over [`rebuild`](Self::rebuild) when the
/// population size is attacker-influenced.
pub fn try_rebuild(&mut self) -> Result<(), LazyMinHeapError> {
let n = self.scores.len();
let mut new_vec: Vec<Reverse<HeapEntry<K, S>>> = Vec::new();
new_vec
.try_reserve_exact(n)
.map_err(|_| LazyMinHeapError::AllocationFailed { requested: n })?;
for (key, entry) in self.scores.iter() {
new_vec.push(Reverse(HeapEntry {
score: entry.score.clone(),
seq: entry.seq,
key: key.clone(),
}));
}
self.heap = BinaryHeap::from(new_vec);
Ok(())
}
/// Rebuilds if the heap has grown too stale relative to map size.
///
/// Triggers rebuild when `heap_len() > len() * factor`. Values of
/// `factor` below 1 are clamped to 1.
///
/// # Example
///
/// ```
/// use cachekit::ds::LazyMinHeap;
///
/// let mut heap: LazyMinHeap<&str, i32> = LazyMinHeap::new();
/// heap.update("a", 1);
/// heap.update("a", 2);
/// heap.update("a", 3); // heap_len=3, len=1
///
/// // Rebuild if heap_len > len * 2
/// heap.maybe_rebuild(2);
/// assert_eq!(heap.heap_len(), 1);
/// ```
pub fn maybe_rebuild(&mut self, factor: usize) {