diff --git a/README.md b/README.md index 5c91177..94feed4 100644 --- a/README.md +++ b/README.md @@ -10,8 +10,7 @@ Lightweight and high performance concurrent cache optimized for low cache overhe * Scan resistant and high hit rate caching policy (S3-FIFO) * User defined weight per item * Scales well with the number of threads -* Atomic operations with `get_or_insert` and `get_value_or_guard` functions -* Atomic async operations with `get_or_insert_async` and `get_value_or_guard_async` functions +* Coordinate loads for the same key with `get_or_insert_with`, `get_value_or_guard`, and their async variants * Try methods avoid waiting for shard locks. * Closure-based `entry` API for atomic inspect-and-act patterns (keep, remove, replace) * Supports item pinning diff --git a/src/lib.rs b/src/lib.rs index 70169fc..f08a08c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,9 +27,9 @@ //! //! # Atomic operations //! -//! By using the `get_or_insert` or `get_value_or_guard` family of functions (both sync and async variants -//! are available, they can be mix and matched) the user can coordinate the insertion of entries, so only -//! one value is "computed" and inserted after a cache miss. +//! The loading helpers in [`sync::Cache`] coordinate concurrent loads for the same key. +//! Resident lookup, load reservation, invalidation, and admission take effect under +//! the key's shard lock. See [`sync::Cache::get_or_insert_with`] for what a load can return. //! //! The `entry` family of functions provide a closure-based API for atomically //! inspecting and acting on existing entries (keep, remove, or replace) while also coordinating diff --git a/src/shard.rs b/src/shard.rs index 8327026..93082fd 100644 --- a/src/shard.rs +++ b/src/shard.rs @@ -1224,7 +1224,7 @@ impl< weight = self.weighter.weight(&key, &value); // check again, it could have changed weight if weight > self.weight_target_hot { - return self.handle_insert_overweight(lcs, hash, key, value, strategy); + return self.handle_insert_overweight(lcs, hash, key, value, strategy, wakes); } } @@ -1271,15 +1271,25 @@ impl< key: Key, value: Val, strategy: InsertStrategy, + wakes: &mut Id::WakeBatch, ) -> Result<(), (Key, Val)> { - // Make sure to remove any existing entry - if let Some((idx, resident)) = self.search_resident(hash, &key) { - let prev_state = resident.state; - if let Some((ek, ev)) = self.remove_internal(hash, idx) { - match prev_state { - ResidentState::Hot => self.lifecycle.on_evict_hot(lcs, ek, ev), - ResidentState::Cold => self.lifecycle.on_evict_cold(lcs, ek, ev), + if let Some(idx) = self.search(hash, &key) { + match self.entries.get(idx).unwrap().0 { + Entry::Resident(resident) => { + let prev_state = resident.state; + let (ek, ev) = self.remove_internal(hash, idx).unwrap(); + match prev_state { + ResidentState::Hot => self.lifecycle.on_evict_hot(lcs, ek, ev), + ResidentState::Cold => self.lifecycle.on_evict_cold(lcs, ek, ev), + } + } + Entry::Placeholder(p) if matches!(strategy, InsertStrategy::Insert) => { + if let Some(shared) = p.shared.as_ref() { + Id::invalidate(shared, wakes); + } + self.remove_internal(hash, idx); } + _ => {} } } if matches!(strategy, InsertStrategy::Replace { .. }) { diff --git a/src/sync.rs b/src/sync.rs index 7666d8b..04d4eee 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -505,9 +505,8 @@ impl< /// Inserts an item in the cache with key `key`. /// - /// An admitted value invalidates any pending load for `key` and wakes its - /// waiters to retry the lookup. A value rejected at admission leaves the - /// pending load in place. + /// Invalidates any pending load for `key` and wakes its waiters to retry + /// the lookup, even when the value is rejected at admission. pub fn insert(&self, key: Key, value: Val) { let mut lcs = Default::default(); self.insert_with_lifecycle(key, value, &mut lcs); @@ -639,15 +638,17 @@ impl< } } - /// Gets an item from the cache with key `key` . + /// Returns the value for `key` or a guard to load it. /// - /// If the corresponding value isn't present in the cache, this function returns a guard - /// that can be used to insert the value once it's computed. - /// While the returned guard is alive, other calls with the same key using the - /// `get_value_or_guard` or `get_or_insert` family of functions will wait until the guard - /// is dropped or the value is inserted. - /// Removing, overwriting or clearing an in-flight entry wakes its waiters to retry lookup. - /// A value published before invalidation can still reach registered waiters. + /// If a load is pending, this call waits. If the guard is dropped without + /// inserting, a waiter can take over the load. + /// + /// [`remove`](Self::remove), [`clear`](Self::clear), and + /// [`insert`](Self::insert) invalidate pending loads for affected keys. + /// The loader can finish computing, but its guard returns `Err(value)` + /// if it tries to insert after invalidation. Waiters wake and retry the lookup. + /// Once a guard publishes a value, its waiters can still receive it + /// after the cache entry is removed or replaced. /// /// A `None` `timeout` means waiting forever. /// A `Some()` timeout will return a Timeout error immediately if the value is not present @@ -667,9 +668,13 @@ impl< PlaceholderGuard::join(shard, hash, key, timeout) } - /// Gets or inserts an item in the cache with key `key`. + /// Returns a resident value or the computed result of a load for `key`. + /// + /// The loader runs outside the shard lock. The caller that runs it can + /// receive the computed result even after its load is invalidated. + /// Admission and eviction can leave the result uncached. /// - /// See also `get_value_or_guard` and `get_value_or_guard_async`. + /// See [`Self::get_value_or_guard`] for the effects of invalidation. pub fn get_or_insert_with( &self, key: &Q, @@ -689,15 +694,7 @@ impl< } } - /// Gets an item from the cache with key `key`. - /// - /// If the corresponding value isn't present in the cache, this function returns a guard - /// that can be used to insert the value once it's computed. - /// While the returned guard is alive, other calls with the same key using the - /// `get_value_or_guard` or `get_or_insert` family of functions will wait until the guard - /// is dropped or the value is inserted. - /// Removing, overwriting or clearing an in-flight entry wakes its waiters to retry lookup. - /// A value published before invalidation can still reach registered waiters. + /// Async version of [`Self::get_value_or_guard`]. pub async fn get_value_or_guard_async<'a, Q>( &'a self, key: &Q, @@ -722,7 +719,7 @@ impl< } } - /// Gets or inserts an item in the cache with key `key`. + /// Async version of [`Self::get_or_insert_with`]. pub async fn get_or_insert_async( &self, key: &Q, diff --git a/src/sync_placeholder.rs b/src/sync_placeholder.rs index 1aefd4c..edfba6b 100644 --- a/src/sync_placeholder.rs +++ b/src/sync_placeholder.rs @@ -141,7 +141,8 @@ fn remove_waiter(waiters: &mut Vec, notified: *const AtomicBool) -> Wait /// which returns `Result` instead. #[derive(Debug)] pub enum GuardResult<'a, Key, Val, We, B, L> { - /// The value was found in the cache. + /// A resident value or the computed result of a load this lookup joined. + /// Waiters can receive the result even when the cache declines to admit it. Value(Val), /// The key was absent; use the guard to insert a value. Guard(PlaceholderGuard<'a, Key, Val, We, B, L>), diff --git a/tests/invalidation_shared.rs b/tests/invalidation_shared.rs index cffe1d2..53a04cd 100644 --- a/tests/invalidation_shared.rs +++ b/tests/invalidation_shared.rs @@ -67,6 +67,39 @@ fn remove_wakes_waiters_to_retry_without_old_value() { assert_eq!(cache.get(&0), Some(9)); } +#[test] +fn overweight_insert_invalidates_pending_load() { + #[derive(Clone)] + struct ValueWeight; + + impl quick_cache::Weighter for ValueWeight { + fn weight(&self, _: &u64, value: &u64) -> u64 { + *value + } + } + + let cache = Cache::with_weighter(64, 64, ValueWeight); + let GuardResult::Guard(old) = cache.get_value_or_guard(&0, None) else { + panic!("expected the first load guard"); + }; + let wakes = Arc::new(Wakes::default()); + let waker = Waker::from(wakes.clone()); + let mut cx = Context::from_waker(&waker); + let mut waiter = pin!(cache.get_value_or_guard_async(&0)); + assert!(waiter.as_mut().poll(&mut cx).is_pending()); + + cache.insert(0, 1000); + + assert_eq!(old.insert(7), Err(7)); + assert_eq!(cache.get(&0), None); + assert_eq!(wakes.0.load(Ordering::SeqCst), 1); + let Poll::Ready(Err(new)) = waiter.as_mut().poll(&mut cx) else { + panic!("expected the waiter to retry and get a new guard"); + }; + new.insert(9).unwrap(); + assert_eq!(cache.get(&0), Some(9)); +} + #[test] fn clear_multiple_pending_loads_wakes_every_waiter() { let cache = cache();