From da96deee253187246b7176b1b86f1009b9101ca5 Mon Sep 17 00:00:00 2001 From: Arthur Silva Date: Sat, 21 Nov 2026 01:58:58 +0100 Subject: [PATCH 1/7] Estimate ghost capacity when the item estimate is omitted Use the weight budget for shard sizing when the builder has no item estimate. Sample resident counts periodically to size ghost history. --- src/lib.rs | 2 + src/options.rs | 21 +++-- src/shard.rs | 167 ++++++++++++++++++++++++++++++++-------- src/sync.rs | 42 ++++++++-- src/sync_placeholder.rs | 2 +- 5 files changed, 182 insertions(+), 52 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 583d9a4..99ca203 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 //! diff --git a/src/options.rs b/src/options.rs index ad527ae..a25c0b4 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(), @@ -74,8 +73,10 @@ 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. + /// This sets the ghost history size and helps choose the number of sync cache shards. + /// By default, the cache sizes ghost history from resident entries. The sync cache uses the + /// weight capacity as its item estimate for shard sizing, so heavier items can leave + /// fewer entries per shard. #[inline] pub fn estimated_items_capacity(&mut self, estimated_items_capacity: usize) -> &mut Self { self.estimated_items_capacity = Some(estimated_items_capacity); @@ -107,9 +108,10 @@ impl OptionsBuilder { /// 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`. + /// again, the item is admitted as "hot". + /// The percentage applies to the estimated item capacity, when supplied. Otherwise, the cache + /// samples the resident count on the first ghost addition, every 255 ghost additions after + /// that, and on capacity changes. /// /// Defaults to: `0.5` (50%). #[inline] @@ -131,14 +133,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..1b78592 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, + adaptive_ghost_allocation: Option, + 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, + adaptive_ghost_allocation: self.adaptive_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,10 @@ impl> CacheShard, weight_capacity: u64, weighter: We, hash_builder: B, @@ -412,7 +422,11 @@ impl< // can truncate to 0 for small capacities, which would reject all inserts as overweight. let weight_target_hot = ((weight_capacity as f64 * hot_allocation) as u64) .clamp(weight_capacity.min(1), weight_capacity); - let capacity_non_resident = (estimated_items_capacity as f64 * ghost_allocation) as usize; + let capacity_non_resident = + (estimated_items_capacity.unwrap_or_default() as f64 * ghost_allocation) as usize; + let adaptive_ghost_allocation = (estimated_items_capacity.is_none() + && ghost_allocation > 0.0) + .then_some(ghost_allocation); Self { hash_builder, map: HashTable::with_capacity(0), @@ -427,6 +441,8 @@ impl< hot_head: None, ghost_head: None, capacity_non_resident, + adaptive_ghost_allocation, + ghosts_until_sample: u8::from(adaptive_ghost_allocation.is_some()), weight_target_hot, num_hot: 0, num_cold: 0, @@ -506,10 +522,7 @@ impl< /// Reserver additional space for `additional` entries. /// Note that this is counted in entries, and is not weighted. pub fn reserve(&mut self, additional: usize) { - // Ghost (non-resident) entries also occupy slab/map slots. The number - // produced by `additional` insertions is bounded both by `additional` - // (each insert evicts at most one resident into a ghost) and by the - // shard-wide cap `capacity_non_resident`, so reserve for the smaller. + // Reserve extra slots for ghost history up to the current ghost limit. let additional = additional.saturating_add(additional.min(self.capacity_non_resident)); self.entries.reserve(additional); self.map.reserve(additional, |&idx| { @@ -870,7 +883,11 @@ impl< self.ghost_head = Some(self.entries.link(idx, self.ghost_head)); self.num_cold -= 1; self.num_non_resident += 1; - // evict from ghost if oversized + // Fixed sizing leaves the countdown at zero when it reaches the sampler. + self.ghosts_until_sample = self.ghosts_until_sample.wrapping_sub(1); + if self.ghosts_until_sample == 0 { + self.update_ghost_capacity(); + } if self.num_non_resident > self.capacity_non_resident { self.advance_ghost(); } @@ -1058,7 +1075,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 +1159,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 +1208,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 +1458,48 @@ 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; + if self.adaptive_ghost_allocation.is_none() { + let old_new_ratio = new_weight_capacity as f64 / self.weight_capacity as f64; + 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.adaptive_ghost_allocation.is_some() { + let sample_next_ghost = self.num_non_resident == 0 || self.len() == 0; + self.update_ghost_capacity(); + if sample_next_ghost { + self.ghosts_until_sample = 1; + } + } else { + self.trim_ghosts(); } + } + + #[cold] + fn update_ghost_capacity(&mut self) { + let Some(allocation) = self.adaptive_ghost_allocation else { + return; + }; + self.capacity_non_resident = if self.weight_capacity == 0 { + 0 + } else { + (self.len() as f64 * allocation) as usize + }; + self.ghosts_until_sample = GHOST_SAMPLE_INTERVAL; + self.trim_ghosts(); + } - // 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 + #[inline] + fn trim_ghosts(&mut self) { while self.num_non_resident > self.capacity_non_resident { self.advance_ghost(); } @@ -1574,6 +1609,70 @@ 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, + None, + 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); + + 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); + } + #[cfg(not(feature = "stats"))] #[test] fn reserve_caps_ghost_headroom() { @@ -1589,9 +1688,9 @@ 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, // ghost_allocation -> capacity_non_resident = 500_000 + Some(1_000_000), // estimated_items_capacity + u64::MAX, // weight_capacity crate::UnitWeighter, crate::DefaultHashBuilder::default(), crate::sync::DefaultLifecycle::default(), diff --git a/src/sync.rs b/src/sync.rs index 826a27e..65f211a 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -148,24 +148,27 @@ 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 shard_items_cap = options + .estimated_items_capacity + .map(|_| shard_items_cap as usize); let shards = (0..num_shards) .map(|_| { RwLock::new(CacheShard::new( options.hot_allocation, options.ghost_allocation, - shard_items_cap as usize, + shard_items_cap, shard_weight_cap, weighter.clone(), hash_builder.clone(), @@ -1045,6 +1048,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(1024)); + for cache in [inferred, explicit] { + assert_eq!(cache.shards.len(), 32); + assert_eq!(cache.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..5e016ae 100644 --- a/src/sync_placeholder.rs +++ b/src/sync_placeholder.rs @@ -633,7 +633,7 @@ mod lazy_tests { RwLock::new(CacheShard::new( 0.9, 0.5, - 1024, + Some(1024), 1024, UnitWeighter, TestHasher::default(), From 41d337e1cc604b0c9f6d54ba46b9d1b4e3949f35 Mon Sep 17 00:00:00 2001 From: Arthur Silva Date: Sat, 21 Nov 2026 10:45:04 +0100 Subject: [PATCH 2/7] Document that ghost entries store key hashes --- src/options.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/options.rs b/src/options.rs index a25c0b4..f7b1dcc 100644 --- a/src/options.rs +++ b/src/options.rs @@ -106,9 +106,10 @@ 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, the item is admitted as "hot". + /// 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 estimated item capacity, when supplied. Otherwise, the cache /// samples the resident count on the first ghost addition, every 255 ghost additions after /// that, and on capacity changes. From 01f64343e28485bd7ccf8c8535875c51b79affa9 Mon Sep 17 00:00:00 2001 From: Arthur Silva Date: Sat, 21 Nov 2026 12:05:13 +0100 Subject: [PATCH 3/7] Rearm ghost sampling when a resize clears history Check for empty history after trimming the resized limit. Document how weight-only sizing can affect admission in a sharded cache. --- src/options.rs | 5 +++-- src/shard.rs | 17 +++++++++++++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/options.rs b/src/options.rs index f7b1dcc..85bce23 100644 --- a/src/options.rs +++ b/src/options.rs @@ -75,8 +75,9 @@ impl OptionsBuilder { /// /// This sets the ghost history size and helps choose the number of sync cache shards. /// By default, the cache sizes ghost history from resident entries. The sync cache uses the - /// weight capacity as its item estimate for shard sizing, so heavier items can leave - /// fewer entries per shard. + /// weight capacity as its item estimate for shard sizing. 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); diff --git a/src/shard.rs b/src/shard.rs index 1b78592..7d330fd 100644 --- a/src/shard.rs +++ b/src/shard.rs @@ -1474,9 +1474,8 @@ impl< while self.weight() > self.weight_capacity && self.advance_cold(lcs) {} if self.adaptive_ghost_allocation.is_some() { - let sample_next_ghost = self.num_non_resident == 0 || self.len() == 0; self.update_ghost_capacity(); - if sample_next_ghost { + if self.num_non_resident == 0 { self.ghosts_until_sample = 1; } } else { @@ -1664,6 +1663,20 @@ mod tests { 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 ()); From 387fc0534502bd92684f12229c68c01f0cb31d19 Mon Sep 17 00:00:00 2001 From: Arthur Silva Date: Sat, 21 Nov 2026 23:45:41 +0100 Subject: [PATCH 4/7] Size ghost history from resident count --- src/lib.rs | 2 +- src/options.rs | 15 +++--- src/shard.rs | 102 ++++++++++++++++++++++------------------ src/sync.rs | 14 ++---- src/sync_placeholder.rs | 1 - src/unsync.rs | 51 ++++++++++++-------- 6 files changed, 101 insertions(+), 84 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 99ca203..38a704d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -385,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 85bce23..cf76979 100644 --- a/src/options.rs +++ b/src/options.rs @@ -73,11 +73,10 @@ 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 sets the ghost history size and helps choose the number of sync cache shards. - /// By default, the cache sizes ghost history from resident entries. The sync cache uses the - /// weight capacity as its item estimate for shard sizing. 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. + /// The sync cache uses this estimate to choose its shard count. It uses the weight capacity + /// by default. 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); @@ -111,9 +110,9 @@ impl OptionsBuilder { /// 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 estimated item capacity, when supplied. Otherwise, the cache - /// samples the resident count on the first ghost addition, every 255 ghost additions after - /// that, and on capacity changes. + /// 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] diff --git a/src/shard.rs b/src/shard.rs index 7d330fd..972ec00 100644 --- a/src/shard.rs +++ b/src/shard.rs @@ -154,7 +154,7 @@ pub struct CacheShard> { num_cold: usize, num_non_resident: usize, capacity_non_resident: usize, - adaptive_ghost_allocation: Option, + ghost_allocation: f64, ghosts_until_sample: u8, #[cfg(feature = "stats")] hits: AtomicU64, @@ -187,7 +187,7 @@ where num_cold: self.num_cold, num_non_resident: self.num_non_resident, capacity_non_resident: self.capacity_non_resident, - adaptive_ghost_allocation: self.adaptive_ghost_allocation, + ghost_allocation: self.ghost_allocation, ghosts_until_sample: self.ghosts_until_sample, #[cfg(feature = "stats")] hits: self.hits.load(atomic::Ordering::Relaxed).into(), @@ -367,10 +367,8 @@ impl> CacheShard 0.0); self.weight_hot = 0; self.weight_cold = 0; self.map.clear(); @@ -412,7 +410,6 @@ impl< pub fn new( hot_allocation: f64, ghost_allocation: f64, - estimated_items_capacity: Option, weight_capacity: u64, weighter: We, hash_builder: B, @@ -422,11 +419,6 @@ impl< // can truncate to 0 for small capacities, which would reject all inserts as overweight. let weight_target_hot = ((weight_capacity as f64 * hot_allocation) as u64) .clamp(weight_capacity.min(1), weight_capacity); - let capacity_non_resident = - (estimated_items_capacity.unwrap_or_default() as f64 * ghost_allocation) as usize; - let adaptive_ghost_allocation = (estimated_items_capacity.is_none() - && ghost_allocation > 0.0) - .then_some(ghost_allocation); Self { hash_builder, map: HashTable::with_capacity(0), @@ -440,9 +432,9 @@ impl< cold_head: None, hot_head: None, ghost_head: None, - capacity_non_resident, - adaptive_ghost_allocation, - ghosts_until_sample: u8::from(adaptive_ghost_allocation.is_some()), + capacity_non_resident: 0, + ghost_allocation, + ghosts_until_sample: u8::from(ghost_allocation > 0.0), weight_target_hot, num_hot: 0, num_cold: 0, @@ -522,8 +514,14 @@ impl< /// Reserver additional space for `additional` entries. /// Note that this is counted in entries, and is not weighted. pub fn reserve(&mut self, additional: usize) { - // Reserve extra slots for ghost history up to the current ghost limit. - let additional = additional.saturating_add(additional.min(self.capacity_non_resident)); + let additional = if self.weight_capacity == 0 { + additional + } else { + let projected_len = self.len().saturating_add(additional); + let projected_ghost_limit = (projected_len as f64 * self.ghost_allocation) as usize; + let ghost_limit = self.capacity_non_resident.max(projected_ghost_limit); + additional.saturating_add(additional.min(ghost_limit)) + }; self.entries.reserve(additional); self.map.reserve(additional, |&idx| { let (entry, _) = self.entries.get(idx).unwrap(); @@ -883,7 +881,6 @@ impl< self.ghost_head = Some(self.entries.link(idx, self.ghost_head)); self.num_cold -= 1; self.num_non_resident += 1; - // Fixed sizing leaves the countdown at zero when it reaches the sampler. self.ghosts_until_sample = self.ghosts_until_sample.wrapping_sub(1); if self.ghosts_until_sample == 0 { self.update_ghost_capacity(); @@ -1461,11 +1458,6 @@ impl< let hot_ratio = if self.weight_capacity == 0 { DEFAULT_HOT_ALLOCATION } else { - if self.adaptive_ghost_allocation.is_none() { - let old_new_ratio = new_weight_capacity as f64 / self.weight_capacity as f64; - 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; @@ -1473,27 +1465,25 @@ impl< .clamp(new_weight_capacity.min(1), new_weight_capacity); while self.weight() > self.weight_capacity && self.advance_cold(lcs) {} - if self.adaptive_ghost_allocation.is_some() { + if self.ghost_allocation > 0.0 { self.update_ghost_capacity(); if self.num_non_resident == 0 { self.ghosts_until_sample = 1; } - } else { - self.trim_ghosts(); } } #[cold] fn update_ghost_capacity(&mut self) { - let Some(allocation) = self.adaptive_ghost_allocation else { + 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 * allocation) as usize + (self.len() as f64 * self.ghost_allocation) as usize }; - self.ghosts_until_sample = GHOST_SAMPLE_INTERVAL; self.trim_ghosts(); } @@ -1620,7 +1610,6 @@ mod tests { let mut shard = CacheShard::<_, _, _, _, _, ()>::new( 0.5, 0.5, - None, 8, ValueWeighter, crate::DefaultHashBuilder::default(), @@ -1686,12 +1675,42 @@ mod tests { 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, @@ -1701,22 +1720,15 @@ mod tests { std::num::NonZeroU64, >::new( DEFAULT_HOT_ALLOCATION, - 0.5, // ghost_allocation -> capacity_non_resident = 500_000 - Some(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 65f211a..3e8da2d 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -160,15 +160,11 @@ impl< shard_items_cap = estimated_items_capacity.saturating_add(num_shards - 1) / num_shards; } let shard_weight_cap = weight_capacity.saturating_add(num_shards - 1) / num_shards; - let shard_items_cap = options - .estimated_items_capacity - .map(|_| shard_items_cap as usize); let shards = (0..num_shards) .map(|_| { RwLock::new(CacheShard::new( options.hot_allocation, options.ghost_allocation, - shard_items_cap, shard_weight_cap, weighter.clone(), hash_builder.clone(), @@ -1062,11 +1058,11 @@ mod tests { assert!(options.build().is_err()); options.shards(64).weight_capacity(1024); let inferred = unit_cache(&options); - let explicit = unit_cache(options.estimated_items_capacity(1024)); - for cache in [inferred, explicit] { - assert_eq!(cache.shards.len(), 32); - assert_eq!(cache.capacity(), 1024); - } + 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 diff --git a/src/sync_placeholder.rs b/src/sync_placeholder.rs index 5e016ae..63be3a5 100644 --- a/src/sync_placeholder.rs +++ b/src/sync_placeholder.rs @@ -633,7 +633,6 @@ mod lazy_tests { RwLock::new(CacheShard::new( 0.9, 0.5, - Some(1024), 1024, UnitWeighter, TestHasher::default(), diff --git a/src/unsync.rs b/src/unsync.rs index 2e60c93..a22cb87 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 Date: Sun, 22 Nov 2026 00:02:01 +0100 Subject: [PATCH 5/7] Simplify ghost sampling and trimming --- src/shard.rs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/src/shard.rs b/src/shard.rs index 972ec00..50888dc 100644 --- a/src/shard.rs +++ b/src/shard.rs @@ -368,7 +368,7 @@ impl> CacheShard 0.0); + self.ghosts_until_sample = 1; self.weight_hot = 0; self.weight_cold = 0; self.map.clear(); @@ -434,7 +434,7 @@ impl< ghost_head: None, capacity_non_resident: 0, ghost_allocation, - ghosts_until_sample: u8::from(ghost_allocation > 0.0), + ghosts_until_sample: 1, weight_target_hot, num_hot: 0, num_cold: 0, @@ -881,7 +881,7 @@ impl< self.ghost_head = Some(self.entries.link(idx, self.ghost_head)); self.num_cold -= 1; self.num_non_resident += 1; - self.ghosts_until_sample = self.ghosts_until_sample.wrapping_sub(1); + self.ghosts_until_sample -= 1; if self.ghosts_until_sample == 0 { self.update_ghost_capacity(); } @@ -1484,11 +1484,6 @@ impl< } else { (self.len() as f64 * self.ghost_allocation) as usize }; - self.trim_ghosts(); - } - - #[inline] - fn trim_ghosts(&mut self) { while self.num_non_resident > self.capacity_non_resident { self.advance_ghost(); } From dd217474dff175dbe9b5360cdee3bf2619658179 Mon Sep 17 00:00:00 2001 From: Arthur Silva Date: Sun, 22 Nov 2026 00:10:27 +0100 Subject: [PATCH 6/7] Clarify the minimum shard size check and reserve docs --- src/options.rs | 16 +++++++++------- src/sync.rs | 7 +++---- src/unsync.rs | 3 +-- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/options.rs b/src/options.rs index cf76979..17ef476 100644 --- a/src/options.rs +++ b/src/options.rs @@ -60,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); @@ -73,10 +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. /// - /// The sync cache uses this estimate to choose its shard count. It uses the weight capacity - /// by default. 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. + /// 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); diff --git a/src/sync.rs b/src/sync.rs index 3e8da2d..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, @@ -280,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(); diff --git a/src/unsync.rs b/src/unsync.rs index a22cb87..9294d87 100644 --- a/src/unsync.rs +++ b/src/unsync.rs @@ -117,8 +117,7 @@ impl, B: BuildHasher, L: Lifecycle Date: Sun, 22 Nov 2026 00:18:57 +0100 Subject: [PATCH 7/7] Account for existing ghosts when reserving --- src/shard.rs | 3 ++- src/unsync.rs | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/shard.rs b/src/shard.rs index 50888dc..396fe2f 100644 --- a/src/shard.rs +++ b/src/shard.rs @@ -520,7 +520,8 @@ impl< let projected_len = self.len().saturating_add(additional); let projected_ghost_limit = (projected_len as f64 * self.ghost_allocation) as usize; let ghost_limit = self.capacity_non_resident.max(projected_ghost_limit); - additional.saturating_add(additional.min(ghost_limit)) + let ghost_headroom = ghost_limit.saturating_sub(self.num_non_resident); + additional.saturating_add(additional.min(ghost_headroom)) }; self.entries.reserve(additional); self.map.reserve(additional, |&idx| { diff --git a/src/unsync.rs b/src/unsync.rs index 9294d87..9b3fa7d 100644 --- a/src/unsync.rs +++ b/src/unsync.rs @@ -618,6 +618,17 @@ mod tests { } } + #[test] + fn reserve_counts_existing_ghosts() { + let mut cache = Cache::new(12); + for key in 0..17 { + cache.insert(key, key); + } + let map_bytes = cache.memory_used().map; + cache.reserve(7); + assert_eq!(cache.memory_used().map, map_bytes); + } + #[test] fn test_set_capacity_with_ghosts() { // Create a cache that will generate ghost entries