Skip to main content

cqlite_core/memory/
mod.rs

1//! Memory management for CQLite.
2//!
3//! Issue #1568 (Epic B / B2) deleted the dead `MemoryManager` cache core — the
4//! LRU block cache, the row cache, and the buffer pool that no read path used —
5//! now that B1 (#1567) ships the real
6//! [`DecompressedChunkCache`](crate::storage::cache::DecompressedChunkCache).
7//! What remains is the **semver-frozen** public stats shell:
8//! [`MemoryManager::stats`] and [`MemoryStats`], reachable through
9//! `Database::stats().memory_stats`. Its block-cache numbers are now sourced
10//! from the live B1 cache (real hits/misses/occupancy) instead of the deleted
11//! always-zero counters, so a repeated cached read yields a non-zero
12//! [`MemoryStats::block_cache_hit_rate`] rather than a structural `0.0`.
13
14use std::sync::Arc;
15
16use crate::storage::cache::DecompressedChunkCache;
17#[cfg(feature = "state_machine")]
18use crate::Value;
19use crate::{Config, Result};
20
21/// Memory manager: the retained public stats shell over the real B1 cache.
22///
23/// It holds an optional handle to the shared
24/// [`DecompressedChunkCache`](crate::storage::cache::DecompressedChunkCache).
25/// When present (the production path — [`MemoryManager::with_chunk_cache`]),
26/// [`stats`](Self::stats) reports that cache's real activity. When absent
27/// ([`new`](Self::new), used where no cache is wired), the block-cache numbers
28/// report zero.
29#[derive(Debug)]
30pub struct MemoryManager {
31    /// The live shared decompressed-chunk cache backing the stats surface, if
32    /// this manager was wired to one.
33    chunk_cache: Option<Arc<DecompressedChunkCache>>,
34}
35
36impl MemoryManager {
37    /// Create a memory manager not wired to a cache.
38    ///
39    /// Retained for callers (and tests) that construct a manager without a live
40    /// storage engine; its [`stats`](Self::stats) reports zero block-cache
41    /// activity. Production opens use [`with_chunk_cache`](Self::with_chunk_cache).
42    pub fn new(_config: &Config) -> Result<Self> {
43        Ok(Self { chunk_cache: None })
44    }
45
46    /// Create a memory manager whose stats surface reports the real activity of
47    /// the shared B1 decompressed-chunk cache (issue #1568).
48    pub fn with_chunk_cache(chunk_cache: Arc<DecompressedChunkCache>) -> Self {
49        Self {
50            chunk_cache: Some(chunk_cache),
51        }
52    }
53
54    /// Get memory statistics.
55    ///
56    /// The block-cache hit/miss counts and occupancy (`total_memory_used`) are
57    /// sourced from the live B1 [`DecompressedChunkCache`] when wired (issue
58    /// #1568): `hit_count()` / `miss_count()` / `resident_bytes()`. The retained
59    /// row-cache and buffer-pool sub-fields report a fixed `0` — the richer
60    /// honest surface is Epic B / B5. The `-> Result<MemoryStats>` signature is
61    /// preserved for semver compatibility with `Database::stats()`.
62    ///
63    /// [`DecompressedChunkCache`]: crate::storage::cache::DecompressedChunkCache
64    pub fn stats(&self) -> Result<MemoryStats> {
65        let mut stats = MemoryStats::default();
66        if let Some(cache) = &self.chunk_cache {
67            stats.block_cache_hits = cache.hit_count();
68            stats.block_cache_misses = cache.miss_count();
69            stats.block_cache_evictions = cache.eviction_count();
70            stats.block_cache_capacity_bytes = cache.budget_bytes();
71            stats.total_memory_used = cache.resident_bytes();
72        }
73        Ok(stats)
74    }
75}
76
77/// Estimate the logical size, in bytes, of a single CQL value.
78///
79/// The single estimator reused by the SELECT executor's byte-bounded result
80/// budget (issue #1582). It is a *logical* content estimate and deliberately
81/// does not model container overhead (HashMap slots, `Arc`/`String` capacity),
82/// which is why the executor's byte budget sits well below the process memory
83/// target to leave headroom for that overhead.
84///
85/// `state_machine`-gated: its only consumer is the (feature-gated) query engine
86/// (`query::result_budget`), so under a minimal `--no-default-features` build it
87/// would otherwise be dead code.
88#[cfg(feature = "state_machine")]
89pub(crate) fn estimate_value_size(value: &Value) -> usize {
90    match value {
91        Value::Null => 1,
92        Value::Boolean(_) => 1,
93        Value::Integer(_) => 4,
94        Value::BigInt(_) => 8,
95        Value::Counter(_) => 8,
96        Value::Float(_) => 8,
97        Value::Text(s) => s.len(),
98        Value::Blob(b) => b.len(),
99        Value::Timestamp(_) => 8,
100        Value::Date(_) => 4,
101        Value::Time(_) => 8,
102        Value::Uuid(_) => 16,
103        Value::Inet(bytes) => bytes.len(),
104        Value::Json(json) => json.to_string().len(),
105        Value::List(items) => items.iter().map(estimate_value_size).sum(),
106        Value::Map(map) => map
107            .iter()
108            .map(|(k, v)| estimate_value_size(k) + estimate_value_size(v))
109            .sum(),
110        Value::TinyInt(_) => 1,
111        Value::SmallInt(_) => 2,
112        Value::Float32(_) => 4,
113        Value::Set(items) => items.iter().map(estimate_value_size).sum(),
114        Value::Tuple(items) => items.iter().map(estimate_value_size).sum(),
115        Value::Udt(udt) => udt
116            .fields
117            .iter()
118            .map(|f| f.value.as_ref().map_or(0, estimate_value_size))
119            .sum(),
120        Value::Frozen(boxed_value) => estimate_value_size(boxed_value),
121        Value::Varint(data) => data.len(),
122        Value::Decimal { unscaled, .. } => 4 + unscaled.len(), // scale + unscaled data
123        Value::Duration { .. } => 12,                          // 3 * 4 bytes
124        Value::Tombstone(_) => 16,                             // timestamp + type + optional TTL
125    }
126}
127
128/// Memory statistics.
129///
130/// Public-surface-wired (semver) through `Database::stats().memory_stats`. The
131/// field names and types are preserved verbatim (issue #1568, AK6); only the
132/// *source* of the block-cache numbers changed — they now reflect the real B1
133/// [`DecompressedChunkCache`](crate::storage::cache::DecompressedChunkCache).
134///
135/// # Independent sampling (advisory observability)
136///
137/// The `block_cache_*` fields and the `key_cache_*` fields are sampled
138/// **independently and at different instants**: the block-cache figures come from
139/// the [`MemoryManager`] (its shared B1 chunk cache), while the key-cache figures
140/// are aggregated from the storage engine's per-reader B4 caches
141/// (`SSTableManager::aggregate_key_cache_stats`) in a separate step. Under
142/// concurrent read load the two groups can therefore reflect slightly different
143/// moments in time, so within a single `memory_stats` snapshot the block-cache vs
144/// key-cache figures are **not guaranteed to be mutually coherent**. Treat this as
145/// advisory observability (trends, rough ratios), not a transactionally-consistent
146/// point-in-time view of both caches.
147#[derive(Debug, Clone, Default)]
148pub struct MemoryStats {
149    /// Block cache hits (real B1 cache hit count when wired).
150    pub block_cache_hits: u64,
151
152    /// Block cache misses (real B1 cache miss count when wired).
153    pub block_cache_misses: u64,
154
155    /// Block cache evictions: entries the B1 decompressed-chunk cache evicted to
156    /// stay within its byte budget (issue #1571, B5). Real `eviction_count()`
157    /// when wired; `0` (honest — no cache, no evictions) otherwise. High churn
158    /// relative to hits signals an undersized `block_cache_capacity_bytes`.
159    pub block_cache_evictions: u64,
160
161    /// Block cache configured byte budget (issue #1571, B5): the B1 cache's
162    /// `budget_bytes()` when wired, so a hit rate can be read against the budget
163    /// it was measured under; `0` when no cache is wired / block caching disabled.
164    pub block_cache_capacity_bytes: usize,
165
166    /// Key cache hits (issue #1571/#2059). A hit lets a repeated point read skip the
167    /// `Index.db` interval parse. Since #2059 the key cache is ONE process-global
168    /// instance shared by every open reader, so these counters are PROCESS-GLOBAL: they
169    /// aggregate activity across ALL `Database` instances in the process, not one
170    /// reader's slice (a semantic change from the retired per-reader counters). Real
171    /// counter; `0` before any reader touches the cache.
172    pub key_cache_hits: u64,
173
174    /// Key cache misses (issue #1571/#2059). Process-global, like
175    /// [`key_cache_hits`](Self::key_cache_hits) — summed across all `Database`
176    /// instances in the process.
177    pub key_cache_misses: u64,
178
179    /// Key cache evictions: entries evicted from the process-global key cache to
180    /// stay within its byte budget (issue #1571/#2059) — DISTINCT from
181    /// [`key_cache_invalidations`](Self::key_cache_invalidations).
182    pub key_cache_evictions: u64,
183
184    /// Key cache invalidations: entries dropped from the process-global key cache on
185    /// generation removal / compaction / warm-registry evict (issue #2059) — a
186    /// distinct counter from budget-driven [`key_cache_evictions`](Self::key_cache_evictions).
187    pub key_cache_invalidations: u64,
188
189    /// Key cache resident bytes: approximate resident footprint of the process-global
190    /// key cache (issue #1571/#2059).
191    pub key_cache_resident_bytes: usize,
192
193    /// Key cache capacity bytes: the process-global key cache's fixed configured byte
194    /// budget (issue #1571/#2059), or `0` when block caching is disabled.
195    pub key_cache_capacity_bytes: usize,
196
197    /// Row cache hits. Retained for shape compatibility; the row cache was
198    /// deleted (issue #1568), so this reports `0` (full surface is Epic B / B5).
199    pub row_cache_hits: u64,
200
201    /// Row cache misses. Retained for shape compatibility; reports `0`.
202    pub row_cache_misses: u64,
203
204    /// Total memory used. Now the B1 cache's resident decompressed bytes
205    /// (`resident_bytes()`) when wired (issue #1568).
206    pub total_memory_used: usize,
207
208    /// Buffer pool allocations. Retained for shape compatibility; the buffer
209    /// pool was deleted (issue #1568), so this reports `0`.
210    pub buffer_allocations: u64,
211
212    /// Buffer pool deallocations. Retained for shape compatibility; reports `0`.
213    pub buffer_deallocations: u64,
214}
215
216impl MemoryStats {
217    /// Calculate block cache hit rate.
218    pub fn block_cache_hit_rate(&self) -> f64 {
219        let total = self.block_cache_hits + self.block_cache_misses;
220        if total > 0 {
221            self.block_cache_hits as f64 / total as f64
222        } else {
223            0.0
224        }
225    }
226
227    /// Calculate the aggregate key-cache hit rate (issue #1571, B5) from the real
228    /// summed hit and miss counts. Returns `0.0` when there has been no key-cache
229    /// activity (honest — not a structural pin).
230    pub fn key_cache_hit_rate(&self) -> f64 {
231        let total = self.key_cache_hits + self.key_cache_misses;
232        if total > 0 {
233            self.key_cache_hits as f64 / total as f64
234        } else {
235            0.0
236        }
237    }
238
239    /// Calculate row cache hit rate.
240    pub fn row_cache_hit_rate(&self) -> f64 {
241        let total = self.row_cache_hits + self.row_cache_misses;
242        if total > 0 {
243            self.row_cache_hits as f64 / total as f64
244        } else {
245            0.0
246        }
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253    use crate::storage::cache::{ChunkKey, DecompressedChunkCache};
254
255    #[test]
256    fn stats_report_zero_without_a_wired_cache() {
257        let config = Config::default();
258        let manager = MemoryManager::new(&config).expect("construct manager");
259
260        let stats = manager.stats().expect("stats");
261        assert_eq!(stats.block_cache_hits, 0);
262        assert_eq!(stats.block_cache_misses, 0);
263        assert_eq!(stats.total_memory_used, 0);
264        assert_eq!(stats.block_cache_hit_rate(), 0.0);
265        // Issue #1571 (B5): every new cache-observability field reports an honest
266        // zero when no cache is wired — never a fabricated placeholder.
267        assert_eq!(stats.block_cache_evictions, 0);
268        assert_eq!(stats.block_cache_capacity_bytes, 0);
269        assert_eq!(stats.key_cache_hits, 0);
270        assert_eq!(stats.key_cache_misses, 0);
271        assert_eq!(stats.key_cache_evictions, 0);
272        // Issue #2059: the invalidations counter is distinct from evictions.
273        assert_eq!(stats.key_cache_invalidations, 0);
274        assert_eq!(stats.key_cache_resident_bytes, 0);
275        assert_eq!(stats.key_cache_capacity_bytes, 0);
276        assert_eq!(stats.key_cache_hit_rate(), 0.0);
277    }
278
279    #[test]
280    fn stats_bridge_reports_real_b1_cache_numbers() {
281        // A wired manager reports the live B1 cache's hits/misses/occupancy.
282        let cache = Arc::new(DecompressedChunkCache::with_budget_bytes(1 << 20));
283        let manager = MemoryManager::with_chunk_cache(Arc::clone(&cache));
284
285        let key = ChunkKey::new(1, 0);
286        cache.insert(key, vec![0xAB; 4096]); // resident bytes now non-zero
287        assert!(cache.get(&key).is_some()); // one hit
288        assert!(cache.get(&ChunkKey::new(1, 1)).is_none()); // one miss
289
290        let stats = manager.stats().expect("stats");
291        assert_eq!(stats.block_cache_hits, 1);
292        assert_eq!(stats.block_cache_misses, 1);
293        assert_eq!(stats.total_memory_used, cache.resident_bytes());
294        assert!(
295            stats.total_memory_used > 0,
296            "occupancy tracks resident bytes"
297        );
298        assert!(
299            stats.block_cache_hit_rate() > 0.0,
300            "a hit makes the reported rate non-zero (not structural 0.0)"
301        );
302        // Issue #1571 (B5): capacity is the real budget; no eviction yet.
303        assert_eq!(stats.block_cache_capacity_bytes, cache.budget_bytes());
304        assert_eq!(stats.block_cache_evictions, 0);
305    }
306
307    #[test]
308    fn stats_bridge_reports_real_b1_eviction_count() {
309        // Issue #1571 (B5): a wired manager surfaces the chunk cache's real
310        // eviction count. Tiny budget on a single shard forces deterministic
311        // evictions.
312        let cache = Arc::new(DecompressedChunkCache::with_budget_and_shards(200, 1));
313        let manager = MemoryManager::with_chunk_cache(Arc::clone(&cache));
314        for i in 0..5u64 {
315            cache.insert(ChunkKey::new(1, i), vec![i as u8; 100]);
316        }
317        let stats = manager.stats().expect("stats");
318        assert_eq!(stats.block_cache_evictions, cache.eviction_count());
319        assert!(
320            stats.block_cache_evictions > 0,
321            "over-budget inserts must have evicted"
322        );
323        assert_eq!(stats.block_cache_capacity_bytes, cache.budget_bytes());
324    }
325}