diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a48224b..6d67806 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,6 +66,9 @@ jobs: - run: cargo test - run: cargo test --no-default-features - run: cargo test --no-default-features --features sharded-lock + - run: cargo test --features stats + - run: cargo test --no-default-features --features stats + - run: cargo test --no-default-features --features sharded-lock,stats # no run because of shuttle feature and non-shuttle tests - run: cargo test --features shuttle --no-run diff --git a/src/lib.rs b/src/lib.rs index 635b21a..c02867d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -81,7 +81,30 @@ //! | `parking_lot` | ✓ | Use [parking_lot](https://crates.io/crates/parking_lot) for synchronization primitives. Mutually exclusive with `sharded-lock`. | //! | `sharded-lock` | | Use [`crossbeam_utils::sync::ShardedLock`](https://docs.rs/crossbeam-utils/latest/crossbeam_utils/sync/struct.ShardedLock.html) for synchronization primitives. Mutually exclusive with `parking_lot`. | //! | `shuttle` | | Enable [shuttle](https://crates.io/crates/shuttle) testing support for concurrency testing. | -//! | `stats` | | Enable cache statistics tracking via the `hits()`, `misses()`, and per-item `item_stats()` methods. Overhead: adds an 8-byte per-item access counter (`AtomicU64`) to each resident item — raising per-entry memory by up to 8 bytes, depending on layout — and performs two atomic increments per cache hit and one per miss. | +//! | `stats` | | Enable cache statistics tracking via the `hits()`, `misses()`, and per-item `item_stats()` methods. Overhead: adds an 8-byte per-item access counter (`AtomicU64`) to each resident item — raising per-entry memory by up to 8 bytes, depending on layout — and updates the cache and item counters on tracked accesses. See [Statistics](#statistics). | +//! +//! # Statistics +//! +//! With `stats`, `hits()` and `misses()` count internal tracked lookups, rather than +//! public method calls. `get` and `get_mut` count a resident hit or an absent miss; +//! peeks, membership tests, and mutations such as `insert` do not count lookups. +//! A sync loader first probes under a read lock, then probes for a value or +//! placeholder under a write lock. A cold load therefore counts two misses. +//! Joining an existing placeholder counts a hit, even if the caller times out; +//! the preceding sync read probe also counts a miss. An unsync cold load counts +//! one miss. Loader retries can add lookups. +//! +//! `entry` counts a hit when its callback returns `Retain` or it joins a placeholder, +//! and a miss when it creates a placeholder. `Remove` and `ReplaceWithGuard` do not +//! count resident hits. `entry_async` can probe an existing placeholder twice +//! before waiting, recording a hit for each probe. +//! A waiting loader that receives its value directly does not increment that +//! item's access count. Cache totals survive `clear`; replacing a resident value +//! resets its per-item count. Concurrent totals are observations rather than a +//! single snapshot. +//! +//! Shared read paths use atomic increments. Exclusive paths update counters through +//! mutable references. The `stats` feature requires target support for 64-bit atomics. #![allow(clippy::type_complexity)] #![cfg_attr(docsrs, feature(doc_cfg))] @@ -169,8 +192,10 @@ pub trait Weighter { /// Zero (0) weight items are allowed and will be ignored when looking for eviction /// candidates. Such items can only be manually removed or overwritten. /// - /// Note that it's undefined behavior for a cache item to change its weight. - /// The only exception to this is when Lifecycle::before_evict is called. + /// An item's weight must stay stable between cache operations. Values may change + /// weight through unsync mutable-reference guards, sync entry callbacks, and + /// [`Lifecycle::before_evict`]. The cache recalculates weight after these mutations. + /// Leaking a mutable-reference guard can leave weight accounting inaccurate. /// /// It's also undefined behavior in release mode if the summing of weights overflows, /// although this is unlikely to be a problem in practice. @@ -234,7 +259,7 @@ pub trait Lifecycle { /// Called when a cache item is about to be evicted. /// Note that value replacement (e.g. insertions for the same key) won't call this method. /// - /// This is the only time the item can change its weight. If the item weight becomes zero (0) it + /// If the item weight becomes zero (0) it /// will be left in the cache, otherwise it'll still be removed. Zero (0) weight items aren't evictable /// and are kept separated from the other items so it's possible to have a large number of them without /// negatively affecting eviction performance. @@ -302,18 +327,20 @@ impl MemoryUsed { /// /// Only available with the `stats` feature enabled. Enabling that feature adds an /// 8-byte per-item access counter to each resident item (raising per-entry memory -/// by up to 8 bytes, depending on layout) and performs two atomic increments per -/// cache hit and one per miss. +/// by up to 8 bytes, depending on layout). See the crate's [statistics documentation](crate#statistics) +/// for counter semantics and update costs. #[cfg(feature = "stats")] #[non_exhaustive] #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct ItemStats { /// Number of times the item has been accessed (read) since it became resident. /// - /// Incremented on every cache hit (`get`/`get_mut`/`get_value_or_guard`/`entry`). + /// Incremented on resident lookups, including `get`, `get_mut`, loader resident + /// lookups, and `entry` callbacks that return `Retain`. Placeholder joins and + /// values delivered directly to waiting loaders do not increment this count. /// Unlike the internal eviction counter, this is monotonic per residency and is /// not bounded by the eviction policy. It resets to zero if the slot is reused for - /// a new value (e.g. after eviction and re-insertion). + /// a new value, including replacement of an existing resident value. pub access_count: u64, } diff --git a/src/sync.rs b/src/sync.rs index d12c21a..77af87b 100644 --- a/src/sync.rs +++ b/src/sync.rs @@ -211,13 +211,13 @@ impl< self.shards.len() } - /// Returns the number of misses + /// Returns the number of tracked misses. See [Statistics](crate#statistics). #[cfg(feature = "stats")] pub fn misses(&self) -> u64 { self.shards.iter().map(|s| s.read().misses()).sum() } - /// Returns the number of hits + /// Returns the number of tracked hits. See [Statistics](crate#statistics). #[cfg(feature = "stats")] pub fn hits(&self) -> u64 { self.shards.iter().map(|s| s.read().hits()).sum() @@ -695,7 +695,7 @@ impl< /// Atomically accesses an existing entry, or gets a guard for insertion. /// /// If a value exists for `key`, `on_occupied` is called with a mutable reference - /// to the key and value. The callback returns an [`EntryAction`] to decide what to do: + /// to the value and a shared reference to the key. The callback returns an [`EntryAction`] to decide what to do: /// - [`EntryAction::Retain`]`(T)` — keep the entry, return `T`. /// Weight is recalculated after the callback returns. /// - [`EntryAction::Remove`] — remove the entry from the cache. diff --git a/src/unsync.rs b/src/unsync.rs index 7e9a5c7..b9b138b 100644 --- a/src/unsync.rs +++ b/src/unsync.rs @@ -123,13 +123,13 @@ impl, B: BuildHasher, L: Lifecycle u64 { self.shard.misses() } - /// Returns the number of hits + /// Returns the number of tracked hits. See [Statistics](crate#statistics). #[cfg(feature = "stats")] pub fn hits(&self) -> u64 { self.shard.hits() diff --git a/tests/stats.rs b/tests/stats.rs new file mode 100644 index 0000000..e225cf3 --- /dev/null +++ b/tests/stats.rs @@ -0,0 +1,148 @@ +#![cfg(feature = "stats")] + +use quick_cache::{sync, unsync}; +use std::{ + future::Future, + pin::pin, + task::{Context, Poll, Waker}, + time::Duration, +}; + +fn counts(cache: &sync::Cache) -> (u64, u64) { + (cache.hits(), cache.misses()) +} + +#[test] +fn loader_counts_internal_probes_and_placeholder_joins() { + let cache = sync::Cache::new(10); + let sync::GuardResult::Guard(guard) = cache.get_value_or_guard(&1, None) else { + panic!() + }; + assert_eq!(counts(&cache), (0, 2)); + assert!(matches!( + cache.get_value_or_guard(&1, Some(Duration::ZERO)), + sync::GuardResult::Timeout + )); + assert_eq!(counts(&cache), (1, 3)); + guard.insert(7).unwrap(); + assert!(matches!( + cache.get_value_or_guard(&1, None), + sync::GuardResult::Value(7) + )); + assert_eq!(counts(&cache), (2, 3)); + assert_eq!(cache.item_stats(&1).unwrap().access_count, 1); +} + +#[test] +fn failed_load_retries_and_unsync_loads_have_different_units() { + let cache = sync::Cache::::new(10); + assert_eq!( + cache.get_or_insert_with(&1, || Err::("failed")), + Err("failed") + ); + assert_eq!(counts(&cache), (0, 2)); + assert_eq!(cache.get_or_insert_with(&1, || Ok::<_, ()>(9)), Ok(9)); + assert_eq!(counts(&cache), (0, 4)); + let mut other = unsync::Cache::::new(10); + assert_eq!( + other.get_or_insert_with(&1, || Ok::<_, ()>(9)).unwrap(), + Some(&9) + ); + assert_eq!((other.hits(), other.misses()), (0, 1)); + *other.get_mut(&1).unwrap() = 10; + assert_eq!((other.hits(), other.misses()), (1, 1)); + assert_eq!(other.item_stats(&1).unwrap().access_count, 1); + assert!(other.get_mut(&2).is_none()); + assert_eq!((other.hits(), other.misses()), (1, 2)); +} + +#[test] +fn async_waiter_counts_join_without_counting_filled_value_as_access() { + let cache = sync::Cache::::new(10); + let mut context = Context::from_waker(Waker::noop()); + let mut owner = pin!(cache.get_value_or_guard_async(&1)); + let Poll::Ready(Err(guard)) = owner.as_mut().poll(&mut context) else { + panic!() + }; + assert_eq!(counts(&cache), (0, 2)); + let mut waiter = pin!(cache.get_value_or_guard_async(&1)); + assert!(waiter.as_mut().poll(&mut context).is_pending()); + assert_eq!(counts(&cache), (1, 3)); + assert!(waiter.as_mut().poll(&mut context).is_pending()); + assert_eq!(counts(&cache), (1, 3)); + guard.insert(9).unwrap(); + assert!(matches!( + waiter.as_mut().poll(&mut context), + Poll::Ready(Ok(9)) + )); + assert_eq!(cache.item_stats(&1).unwrap().access_count, 0); + assert_eq!(counts(&cache), (1, 3)); +} + +#[test] +fn entry_actions_and_residency_reset() { + let cache = sync::Cache::::new(10); + let guard = match cache.entry(&1, None, |_, _| sync::EntryAction::Retain(())) { + sync::EntryResult::Vacant(g) => g, + _ => panic!(), + }; + assert_eq!(counts(&cache), (0, 1)); + assert!(matches!( + cache.entry(&1, Some(Duration::ZERO), |_, _| sync::EntryAction::Retain( + () + )), + sync::EntryResult::Timeout + )); + assert_eq!(counts(&cache), (1, 1)); + guard.insert(9).unwrap(); + assert!(matches!( + cache.entry(&1, None, |_, _| sync::EntryAction::Retain(())), + sync::EntryResult::Retained(()) + )); + assert_eq!(cache.item_stats(&1).unwrap().access_count, 1); + assert!(matches!( + cache.entry::<_, ()>(&1, None, |_, _| sync::EntryAction::Remove), + sync::EntryResult::Removed(1, 9) + )); + assert_eq!(counts(&cache), (2, 1)); + cache.insert(1, 9); + let guard = match cache.entry::<_, ()>(&1, None, |_, _| sync::EntryAction::ReplaceWithGuard) { + sync::EntryResult::Replaced(g, 9) => g, + _ => panic!(), + }; + assert_eq!(counts(&cache), (2, 1)); + guard.insert(8).unwrap(); + assert_eq!(cache.item_stats(&1).unwrap().access_count, 0); + let _ = cache.get(&1); + cache.insert(1, 10); + assert_eq!(cache.item_stats(&1).unwrap().access_count, 0); + cache.clear(); + assert_eq!(counts(&cache), (3, 1)); +} + +#[test] +fn async_entry_counts_both_placeholder_probes() { + let cache = sync::Cache::::new(10); + let sync::GuardResult::Guard(guard) = cache.get_value_or_guard(&1, None) else { + panic!() + }; + let mut context = Context::from_waker(Waker::noop()); + let calls = std::cell::Cell::new(0); + let mut waiter = pin!(cache.entry_async(&1, |_, _| { + calls.set(calls.get() + 1); + sync::EntryAction::Retain(()) + })); + assert!(waiter.as_mut().poll(&mut context).is_pending()); + assert_eq!(counts(&cache), (2, 2)); + assert_eq!(calls.get(), 0); + assert!(waiter.as_mut().poll(&mut context).is_pending()); + assert_eq!(counts(&cache), (2, 2)); + guard.insert(9).unwrap(); + assert!(matches!( + waiter.as_mut().poll(&mut context), + Poll::Ready(sync::EntryResult::Retained(())) + )); + assert_eq!(calls.get(), 1); + assert_eq!(counts(&cache), (3, 2)); + assert_eq!(cache.item_stats(&1).unwrap().access_count, 1); +}