diff --git a/src/lib.rs b/src/lib.rs index 583d9a4..38a704d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,6 +56,8 @@ //! //! The `1.5` value in the formula above results from `1 + G`, where `G` is the configured ghost allocation specified //! in [`OptionsBuilder::ghost_allocation`], which is `0.5` by default. +//! The estimate assumes the ghost limit reflects the current resident count. A cache without +//! an item capacity estimate samples resident counts periodically as it adds ghosts. //! //! # Hasher //! @@ -383,7 +385,7 @@ mod tests { #[test] fn test_change_get_mut_change_weight() { - let mut cache = unsync::Cache::with_weighter(100, 100_000, StringWeighter); + let mut cache = unsync::Cache::with_weighter(100_000, StringWeighter); cache.insert(1, "1".to_string()); assert_eq!(cache.get(&1).unwrap(), "1"); assert_eq!(cache.weight(), 1); diff --git a/src/options.rs b/src/options.rs index ad527ae..17ef476 100644 --- a/src/options.rs +++ b/src/options.rs @@ -7,7 +7,7 @@ pub struct Options { pub(crate) shards: usize, pub(crate) hot_allocation: f64, pub(crate) ghost_allocation: f64, - pub(crate) estimated_items_capacity: usize, + pub(crate) estimated_items_capacity: Option, pub(crate) weight_capacity: u64, } @@ -20,7 +20,6 @@ pub struct Options { /// /// Cache::::with_options( /// OptionsBuilder::new() -/// .estimated_items_capacity(10000) /// .weight_capacity(10000) /// .build() /// .unwrap(), @@ -61,9 +60,8 @@ impl OptionsBuilder { /// /// Defaults to: `number of detected cores * 4` /// - /// Note that this number isn't enforced and will be adjusted internally to - /// the next power of two. Too small shards (depending on estimated capacity) - /// may also cause the actual shard count to decrease. + /// The cache rounds this count up to a power of two, then applies the + /// [minimum shard size check](Self::estimated_items_capacity). #[inline] pub fn shards(&mut self, shards: usize) -> &mut Self { self.shards = Some(shards); @@ -74,8 +72,13 @@ impl OptionsBuilder { /// roughly equivalent to `weight_capacity / average item weight`. /// An estimation within one or even two orders of magnitude of the real value is often good enough. /// - /// This is used to estimate the maximum number of shards (to avoid shards that are too small) - /// and to estimate space required to track items recently evicted from the cache. + /// The sync cache uses `estimated_items_capacity` to avoid creating more shards than its + /// estimated item count can support. It halves the shard count until it estimates at least + /// 32 items per shard or reaches one shard. If you omit the estimate, it uses + /// `weight_capacity` as the estimated item count for this calculation. + /// + /// A heavy entry can exceed its shard's admission limit even when it fits the total weight + /// budget. Supply an item estimate or use fewer [`shards`](Self::shards) if this happens. #[inline] pub fn estimated_items_capacity(&mut self, estimated_items_capacity: usize) -> &mut Self { self.estimated_items_capacity = Some(estimated_items_capacity); @@ -105,11 +108,13 @@ impl OptionsBuilder { self } - /// The cache optimistically tracks recently seen keys that are not resident - /// in the cache. These keys are called ghost keys. If a ghost key is seen - /// again items it will be admitted as "hot". - /// The ghost allocation percentage defines how much space to allocate for - /// the ghost keys considering the `estimated_items_capacity`. + /// The cache tracks recently seen non-resident keys as ghost entries, which + /// store only the key's hash. When an insertion matches a ghost entry, + /// the cache admits the item as "hot". + /// + /// The percentage applies to the resident count. The cache samples on the first ghost + /// addition, every 255 ghost additions after that, and on capacity changes. + /// Set to `0.0` to disable ghost history. /// /// Defaults to: `0.5` (50%). #[inline] @@ -131,14 +136,11 @@ impl OptionsBuilder { let weight_capacity = self .weight_capacity .ok_or(Error("weight_capacity is not set"))?; - let estimated_items_capacity = self - .estimated_items_capacity - .ok_or(Error("estimated_items_capacity is not set"))?; Ok(Options { shards, hot_allocation, ghost_allocation, - estimated_items_capacity, + estimated_items_capacity: self.estimated_items_capacity, weight_capacity, }) } diff --git a/src/shard.rs b/src/shard.rs index 13c1f0b..396fe2f 100644 --- a/src/shard.rs +++ b/src/shard.rs @@ -124,6 +124,8 @@ enum Entry { Ghost(u64), } +const GHOST_SAMPLE_INTERVAL: u8 = 255; + /// A bounded cache using a modified CLOCK-PRO eviction policy. /// The implementation allows some parallelism as gets don't require exclusive access. /// Any evicted items are returned so they can be dropped by the caller, outside the locks. @@ -152,6 +154,8 @@ pub struct CacheShard> { num_cold: usize, num_non_resident: usize, capacity_non_resident: usize, + ghost_allocation: f64, + ghosts_until_sample: u8, #[cfg(feature = "stats")] hits: AtomicU64, #[cfg(feature = "stats")] @@ -183,6 +187,8 @@ where num_cold: self.num_cold, num_non_resident: self.num_non_resident, capacity_non_resident: self.capacity_non_resident, + ghost_allocation: self.ghost_allocation, + ghosts_until_sample: self.ghosts_until_sample, #[cfg(feature = "stats")] hits: self.hits.load(atomic::Ordering::Relaxed).into(), #[cfg(feature = "stats")] @@ -361,6 +367,8 @@ impl> CacheShard self.capacity_non_resident { self.advance_ghost(); } @@ -1058,7 +1073,7 @@ impl< } } - while self.weight_hot + self.weight_cold > self.weight_capacity && self.advance_cold(lcs) {} + while self.weight() > self.weight_capacity && self.advance_cold(lcs) {} Ok(()) } @@ -1142,9 +1157,7 @@ impl< if weight != 0 { *list_head = Some(self.entries.link(placeholder.idx, *list_head)); - while self.weight_hot + self.weight_cold > self.weight_capacity - && self.advance_cold(lcs) - {} + while self.weight() > self.weight_capacity && self.advance_cold(lcs) {} } Ok(()) @@ -1193,9 +1206,7 @@ impl< // cache is filling up, admit as hot if possible let enter_hot = self.weight_hot + weight <= self.weight_target_hot; // pre-evict instead of post-evict, this gives sightly more priority to the new item - while self.weight_hot + self.weight_cold + weight > self.weight_capacity - && self.advance_cold(lcs) - {} + while self.weight() + weight > self.weight_capacity && self.advance_cold(lcs) {} let (state, list_head) = if enter_hot { self.num_hot += 1; @@ -1445,26 +1456,35 @@ impl< } pub fn set_capacity(&mut self, new_weight_capacity: u64, lcs: &mut L::RequestState) { - // Guard against division by zero when old capacity is 0 (produces inf/NaN ratios) - if self.weight_capacity == 0 { - self.weight_capacity = new_weight_capacity; - self.weight_target_hot = ((new_weight_capacity as f64 * DEFAULT_HOT_ALLOCATION) as u64) - .clamp(new_weight_capacity.min(1), new_weight_capacity); - // capacity_non_resident stays 0 since we have no basis to estimate + let hot_ratio = if self.weight_capacity == 0 { + DEFAULT_HOT_ALLOCATION } else { - let old_new_ratio = new_weight_capacity as f64 / self.weight_capacity as f64; - let hot_ratio = self.weight_target_hot as f64 / self.weight_capacity as f64; - - self.weight_capacity = new_weight_capacity; - self.weight_target_hot = ((new_weight_capacity as f64 * hot_ratio) as u64) - .clamp(new_weight_capacity.min(1), new_weight_capacity); - self.capacity_non_resident = - (self.capacity_non_resident as f64 * old_new_ratio) as usize; + self.weight_target_hot as f64 / self.weight_capacity as f64 + }; + self.weight_capacity = new_weight_capacity; + self.weight_target_hot = ((new_weight_capacity as f64 * hot_ratio) as u64) + .clamp(new_weight_capacity.min(1), new_weight_capacity); + + while self.weight() > self.weight_capacity && self.advance_cold(lcs) {} + if self.ghost_allocation > 0.0 { + self.update_ghost_capacity(); + if self.num_non_resident == 0 { + self.ghosts_until_sample = 1; + } } + } - // Evict items if we're over the new capacity - while self.weight_hot + self.weight_cold > self.weight_capacity && self.advance_cold(lcs) {} - // Trim ghost entries if needed + #[cold] + fn update_ghost_capacity(&mut self) { + self.ghosts_until_sample = GHOST_SAMPLE_INTERVAL; + if self.ghost_allocation == 0.0 { + return; + } + self.capacity_non_resident = if self.weight_capacity == 0 { + 0 + } else { + (self.len() as f64 * self.ghost_allocation) as usize + }; while self.num_non_resident > self.capacity_non_resident { self.advance_ghost(); } @@ -1574,12 +1594,119 @@ mod tests { assert_eq!(cache.peek(&0), Some(&0)); } + #[test] + fn learned_ghost_capacity() { + struct ValueWeighter; + impl Weighter for ValueWeighter { + fn weight(&self, _key: &u64, value: &u64) -> u64 { + *value + } + } + + let mut shard = CacheShard::<_, _, _, _, _, ()>::new( + 0.5, + 0.5, + 8, + ValueWeighter, + crate::DefaultHashBuilder::default(), + crate::unsync::DefaultLifecycle::default(), + ); + let insert = |shard: &mut CacheShard<_, _, _, _, _, ()>, key, value| { + let hash = shard.hash(&key); + shard + .insert(&mut (), hash, key, value, InsertStrategy::Insert, &mut ()) + .unwrap(); + }; + + for key in 0..=10 { + insert(&mut shard, key, u64::from(key >= 2)); + } + assert_eq!(shard.capacity_non_resident, 4); + assert_eq!(shard.num_non_resident, 1); + + insert(&mut shard, 11, 4); + assert_eq!(shard.num_non_resident, 4); + + // Stop after 254 ghost additions since the first sample. + for key in 12..262 { + insert(&mut shard, key, 4); + } + assert_eq!(shard.capacity_non_resident, 4); + insert(&mut shard, 262, 4); + assert_eq!(shard.capacity_non_resident, 3); + assert_eq!(shard.num_non_resident, 3); + + shard.set_capacity(0, &mut ()); + assert_eq!(shard.len(), 2); + assert_eq!(shard.capacity_non_resident, 0); + assert_eq!(shard.num_non_resident, 0); + + shard.set_capacity(8, &mut ()); + for key in 20..=28 { + insert(&mut shard, key, 1); + } + assert_eq!(shard.capacity_non_resident, 4); + assert_eq!(shard.num_non_resident, 1); + + for key in [0, 1] { + let hash = shard.hash(&key); + assert_eq!(shard.remove(hash, &key, &mut ()), Some((key, 0))); + } + shard.set_capacity(1, &mut ()); + assert_eq!(shard.len(), 1); + assert_eq!(shard.num_non_resident, 0); + + // Weightless entries allow the resident count to grow at the same capacity. + for (key, weight) in [(0, 0), (1, 0), (29, 1), (30, 1)] { + insert(&mut shard, key, weight); + } + assert_eq!(shard.num_non_resident, 1); + + drop(shard.drain()); + assert_eq!(shard.ghosts_until_sample, 1); + shard.set_capacity(1, &mut ()); + for key in 0..3 { + insert(&mut shard, key, 1); + } + assert_eq!(shard.ghosts_until_sample, GHOST_SAMPLE_INTERVAL); + } + + #[test] + fn reserve_projects_ghost_headroom() { + for (residents, weight_capacity, allocation, ghosts) in [ + (0, 200, 0.5, 64), + (40, 200, 0.5, 84), + (40, 200, 0.0, 0), + (0, 0, 0.5, 0), + ] { + let mut shard = CacheShard::<_, _, _, _, _, ()>::new( + DEFAULT_HOT_ALLOCATION, + allocation, + weight_capacity, + crate::UnitWeighter, + crate::DefaultHashBuilder::default(), + crate::unsync::DefaultLifecycle::default(), + ); + for key in 0..residents { + let hash = shard.hash(&key); + shard + .insert(&mut (), hash, key, key, InsertStrategy::Insert, &mut ()) + .unwrap(); + } + + shard.reserve(128); + assert!(shard.entries.capacity() >= residents + 128 + ghosts); + assert!(shard.map.capacity() >= residents + 128 + ghosts); + if ghosts == 0 { + assert!(shard.entries.capacity() < residents + 128 + 64); + } + assert_eq!(shard.capacity_non_resident, 0); + } + } + #[cfg(not(feature = "stats"))] #[test] fn reserve_caps_ghost_headroom() { - // A small reserve on a shard with a large estimated capacity (hence a - // large `capacity_non_resident`) must not over-allocate the slab by the - // full ghost cap; the ghost headroom is bounded by `additional`. let mut shard = CacheShard::< u64, u64, @@ -1589,22 +1716,15 @@ mod tests { std::num::NonZeroU64, >::new( DEFAULT_HOT_ALLOCATION, - 0.5, // ghost_allocation -> capacity_non_resident = 500_000 - 1_000_000, // estimated_items_capacity - u64::MAX, // weight_capacity + 0.5, + u64::MAX, crate::UnitWeighter, crate::DefaultHashBuilder::default(), crate::sync::DefaultLifecycle::default(), ); - assert_eq!(shard.capacity_non_resident, 500_000); + shard.capacity_non_resident = 500_000; shard.reserve(100); - // Ghost headroom is min(additional, capacity_non_resident) = 100, so the - // slab reserves ~200 entries, not 500_000+. - assert!( - shard.entries.capacity() < 1_000, - "slab over-allocated: {}", - shard.entries.capacity() - ); + assert!((200..1_000).contains(&shard.entries.capacity())); } #[test] diff --git a/src/sync.rs b/src/sync.rs index 826a27e..26da20f 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -107,8 +107,8 @@ impl< > Cache { /// Creates a new cache that can hold up to `weight_capacity` in weight. - /// `estimated_items_capacity` is the estimated number of items the cache is expected to hold, - /// roughly equivalent to `weight_capacity / average item weight`. + /// + /// See [`OptionsBuilder::estimated_items_capacity`] for the minimum shard size check. pub fn with( estimated_items_capacity: usize, weight_capacity: u64, @@ -148,24 +148,23 @@ impl< /// ``` pub fn with_options(options: Options, weighter: We, hash_builder: B, lifecycle: L) -> Self { let mut num_shards = options.shards.next_power_of_two() as u64; - let estimated_items_capacity = options.estimated_items_capacity as u64; let weight_capacity = options.weight_capacity; + let estimated_items_capacity = options + .estimated_items_capacity + .map_or(weight_capacity, |items| items as u64); let mut shard_items_cap = estimated_items_capacity.saturating_add(num_shards - 1) / num_shards; - let mut shard_weight_cap = - options.weight_capacity.saturating_add(num_shards - 1) / num_shards; - // try to make each shard hold at least 32 items + // Try to make each shard hold at least 32 items. while shard_items_cap < 32 && num_shards > 1 { num_shards /= 2; shard_items_cap = estimated_items_capacity.saturating_add(num_shards - 1) / num_shards; - shard_weight_cap = weight_capacity.saturating_add(num_shards - 1) / num_shards; } + let shard_weight_cap = weight_capacity.saturating_add(num_shards - 1) / num_shards; let shards = (0..num_shards) .map(|_| { RwLock::new(CacheShard::new( options.hot_allocation, options.ghost_allocation, - shard_items_cap as usize, shard_weight_cap, weighter.clone(), hash_builder.clone(), @@ -281,8 +280,7 @@ impl< self.shards.get(shard_idx).map(|s| (s, hash)) } - /// Reserve additional space for `additional` entries. - /// Note that this is counted in entries, and is not weighted. + /// Reserves space for `additional` items. The cache may reserve extra slots for ghost history. pub fn reserve(&self, additional: usize) { let additional_per_shard = additional.saturating_add(self.shards.len() - 1) / self.shards.len(); @@ -1045,6 +1043,33 @@ mod tests { thread, }; + #[test] + fn weight_only_shard_sizing() { + let unit_cache = |options: &OptionsBuilder| { + Cache::::with_options( + options.build().unwrap(), + UnitWeighter, + Default::default(), + Default::default(), + ) + }; + let mut options = OptionsBuilder::new(); + assert!(options.build().is_err()); + options.shards(64).weight_capacity(1024); + let inferred = unit_cache(&options); + let explicit = unit_cache(options.estimated_items_capacity(128)); + assert_eq!(inferred.shards.len(), 32); + assert_eq!(explicit.shards.len(), 4); + assert_eq!(inferred.capacity(), explicit.capacity()); + assert_eq!(explicit.capacity(), 1024); + assert_eq!( + unit_cache(OptionsBuilder::new().shards(64).weight_capacity(0)) + .shards + .len(), + 1 + ); + } + #[test] #[cfg_attr(miri, ignore)] fn test_multiple_threads() { diff --git a/src/sync_placeholder.rs b/src/sync_placeholder.rs index 66f0f7e..63be3a5 100644 --- a/src/sync_placeholder.rs +++ b/src/sync_placeholder.rs @@ -634,7 +634,6 @@ mod lazy_tests { 0.9, 0.5, 1024, - 1024, UnitWeighter, TestHasher::default(), DefaultLifecycle::default(), diff --git a/src/unsync.rs b/src/unsync.rs index 2e60c93..9b3fa7d 100644 --- a/src/unsync.rs +++ b/src/unsync.rs @@ -21,7 +21,6 @@ impl Cache { /// Creates a new cache with holds up to `items_capacity` items (approximately). pub fn new(items_capacity: usize) -> Self { Self::with( - items_capacity, items_capacity as u64, Default::default(), Default::default(), @@ -31,13 +30,8 @@ impl Cache { } impl> Cache { - pub fn with_weighter( - estimated_items_capacity: usize, - weight_capacity: u64, - weighter: We, - ) -> Self { + pub fn with_weighter(weight_capacity: u64, weighter: We) -> Self { Self::with( - estimated_items_capacity, weight_capacity, weighter, Default::default(), @@ -50,18 +44,9 @@ impl, B: BuildHasher, L: Lifecycle { /// Creates a new cache that can hold up to `weight_capacity` in weight. - /// `estimated_items_capacity` is the estimated number of items the cache is expected to hold, - /// roughly equivalent to `weight_capacity / average item weight`. - pub fn with( - estimated_items_capacity: usize, - weight_capacity: u64, - weighter: We, - hash_builder: B, - lifecycle: L, - ) -> Self { + pub fn with(weight_capacity: u64, weighter: We, hash_builder: B, lifecycle: L) -> Self { Self::with_options( OptionsBuilder::new() - .estimated_items_capacity(estimated_items_capacity) .weight_capacity(weight_capacity) .build() .unwrap(), @@ -80,7 +65,6 @@ impl, B: BuildHasher, L: Lifecycle::with_options( /// OptionsBuilder::new() - /// .estimated_items_capacity(10000) /// .weight_capacity(10000) /// .build() /// .unwrap(), @@ -93,7 +77,6 @@ impl, B: BuildHasher, L: Lifecycle, B: BuildHasher, L: Lifecycle