Skip to main content

reddb_server/storage/cache/
mod.rs

1//! Cache Module
2//!
3//! High-performance caching infrastructure for RedDB.
4//!
5//! # Components
6//!
7//! - **blob**: Byte-oriented L1 cache for exact-key cached blobs
8//! - **result**: Query result cache with dependency-based invalidation
9//! - **aggregates**: Precomputed aggregations (COUNT, SUM, AVG, etc.)
10//! - **spill**: Graph spill-to-disk for memory-limited environments
11//!
12//! # Architecture (inspired by Turso/Milvus/Neo4j)
13//!
14//! ```text
15//! ┌────────────────────────────────────────────────────────┐
16//! │                    Query Layer                         │
17//! ├────────────────────────────────────────────────────────┤
18//! │  Result Cache   │  Materialized Views  │  Plan Cache   │
19//! ├────────────────────────────────────────────────────────┤
20//! │           Aggregation Cache (COUNT/SUM/AVG)            │
21//! ├────────────────────────────────────────────────────────┤
22//! │      Blob Cache       │     Spill Manager              │
23//! ├────────────────────────────────────────────────────────┤
24//! │                   Storage Engine                       │
25//! └────────────────────────────────────────────────────────┘
26//! ```
27
28pub mod aggregates;
29pub mod bgwriter;
30pub mod blob;
31pub mod compressor;
32pub mod extended_ttl;
33pub mod promotion_pool;
34pub mod result;
35pub mod spill;
36pub mod sweeper;
37
38pub use aggregates::{AggCacheStats, AggValue, AggregationCache, CardinalityEstimate, NumericAgg};
39pub use blob::{
40    BlobCache, BlobCacheConfig, BlobCacheHit, BlobCachePolicy, BlobCachePut, BlobCacheStats,
41    CacheError, L1Admission, L2Compression, DEFAULT_BLOB_L1_BYTES_MAX, DEFAULT_BLOB_L2_BYTES_MAX,
42    DEFAULT_BLOB_MAX_NAMESPACES, DEFAULT_BLOB_NAMESPACE_BYTES_MAX,
43    METRIC_CACHE_BLOB_L1_BYTES_IN_USE, METRIC_CACHE_BLOB_L2_BYTES_IN_USE,
44    METRIC_CACHE_BLOB_L2_FULL_REJECTIONS_TOTAL, METRIC_CACHE_VERSION_MISMATCH_TOTAL,
45};
46pub use compressor::{CompressError, CompressOpts, Compressed, L2BlobCompressor};
47pub use extended_ttl::{EffectiveExpiry, ExpiryDecision, ExtendedTtlPolicy};
48pub use promotion_pool::{
49    AsyncPromotionPool, PoolOpts, PromotionExecutor, PromotionMetrics, PromotionRequest,
50    ScheduleOutcome,
51};
52pub use result::{
53    CacheKey, CachePolicy, MaterializedViewCache, MaterializedViewDef, RefreshPolicy, ResultCache,
54    ResultCacheStats,
55};
56pub use spill::{SpillConfig, SpillError, SpillManager, SpillStats, SpillableGraph};
57pub use sweeper::{
58    BlobCacheSweeper, NamespaceFlushReport, NamespaceSweepStats, OrphanReport, SweepLimit,
59    SweepReport,
60};
61
62// ---------------------------------------------------------------------------
63// Legacy standalone L2 Blob Cache backup helpers (issue #148 follow-up)
64// ---------------------------------------------------------------------------
65//
66// The normal server L2 lives in `red.cache.blob_l2` inside the primary
67// `.rdb`, so ordinary database backup and restore already cover it. These
68// helpers remain for direct engine callers that explicitly use the legacy
69// `cache.blob.l2_path` pager plus its reddb-file control sidecar.
70//
71// When the operator opts into `include_blob_cache=true` on a backup
72// (`backup.include_blob_cache`), we upload both files to
73// the configured remote backend under a stable prefix.
74//
75// Shape contract:
76//
77// - Two remote keys derived by `reddb-file`: one for the pager file and one
78//   for the control sidecar.
79// - The cache is *derived* state (ADR 0006). On any per-file failure
80//   we surface the error to the caller — `trigger_backup` logs and
81//   proceeds so a partial L2 archive never aborts the rest of the
82//   backup.
83//
84// Restore is the symmetric mirror: download both keys back into
85// `l2_path` and its reddb-file control sidecar. The cold-start synopsis
86// rebuild in `BlobCache::new` then re-indexes the metadata B+ tree (per
87// `cache/blob/l2.rs::BlobCacheL2::rebuild_l2_synopsis`).
88
89/// Archive the L2 pager file + control sidecar to `backend`. Returns
90/// the number of files uploaded (0..=2).
91///
92/// Caller (`trigger_backup`) decides what to do on error — the cache is
93/// derived state so a partial upload is logged, not fatal.
94pub fn archive_blob_cache_l2(
95    backend: &dyn crate::storage::backend::RemoteBackend,
96    l2_path: &std::path::Path,
97    prefix: &str,
98) -> Result<usize, crate::storage::backend::BackendError> {
99    let mut count = 0usize;
100    if l2_path.is_file() {
101        backend.upload(l2_path, &reddb_file::blob_cache_l2_backup_pager_key(prefix))?;
102        count += 1;
103    }
104    let control = reddb_file::blob_cache_control_path(l2_path);
105    if control.is_file() {
106        backend.upload(
107            &control,
108            &reddb_file::blob_cache_l2_backup_control_key(prefix),
109        )?;
110        count += 1;
111    }
112    Ok(count)
113}
114
115/// Restore the L2 pager file + control sidecar from `backend` into
116/// `l2_path` and its reddb-file control sidecar. Returns the number of
117/// files downloaded.
118///
119/// Cold-start synopsis rebuild on next `BlobCache::new` re-indexes the
120/// metadata. Surfaced for the documented restore procedure
121/// (`docs/operations/blob-cache-backup-restore.md` §3); not yet wired
122/// into a programmatic restore endpoint.
123pub fn restore_blob_cache_l2(
124    backend: &dyn crate::storage::backend::RemoteBackend,
125    prefix: &str,
126    l2_path: &std::path::Path,
127) -> Result<usize, crate::storage::backend::BackendError> {
128    if let Some(parent) = l2_path.parent() {
129        if !parent.as_os_str().is_empty() {
130            std::fs::create_dir_all(parent)
131                .map_err(|err| crate::storage::backend::BackendError::Transport(err.to_string()))?;
132        }
133    }
134    let mut count = 0usize;
135    if backend.download(&reddb_file::blob_cache_l2_backup_pager_key(prefix), l2_path)? {
136        count += 1;
137    }
138    let control = reddb_file::blob_cache_control_path(l2_path);
139    if backend.download(
140        &reddb_file::blob_cache_l2_backup_control_key(prefix),
141        &control,
142    )? {
143        count += 1;
144    }
145    Ok(count)
146}
147
148#[cfg(test)]
149mod backup_helpers_tests {
150    use super::*;
151    use crate::storage::backend::LocalBackend;
152    use std::sync::atomic::{AtomicU64, Ordering};
153
154    fn write_file(path: &std::path::Path, bytes: &[u8]) {
155        if let Some(parent) = path.parent() {
156            std::fs::create_dir_all(parent).unwrap();
157        }
158        std::fs::write(path, bytes).unwrap();
159    }
160
161    /// Per-test unique scratch root under the system temp dir.
162    /// The `tempfile` crate is not in dev-deps; we synthesize a
163    /// collision-free path using the test name + a process-local
164    /// monotonic counter, mirroring the convention already used by
165    /// `cache/blob/cache.rs::tests::l2_path`.
166    static SCRATCH_COUNTER: AtomicU64 = AtomicU64::new(0);
167    fn scratch(label: &str) -> std::path::PathBuf {
168        let pid = std::process::id();
169        let n = SCRATCH_COUNTER.fetch_add(1, Ordering::SeqCst);
170        let p = std::env::temp_dir().join(format!("reddb-blobcache-bk-{label}-{pid}-{n}"));
171        let _ = std::fs::remove_dir_all(&p);
172        std::fs::create_dir_all(&p).unwrap();
173        p
174    }
175
176    /// `LocalBackend` interprets keys as on-disk paths verbatim; we
177    /// therefore use absolute paths under tempdirs as the "prefix"
178    /// the test backends see. A real S3/HTTP backend would ignore the
179    /// path prefix and treat the keys as opaque strings — both
180    /// directions of the helper round-trip the same way.
181    #[test]
182    fn archive_then_restore_round_trips_l2_pager_and_control_files() {
183        let scratch_dir = scratch("pair-src");
184        let l2_src = scratch_dir.join("cache.rdb");
185        write_file(&l2_src, b"pager-bytes-on-disk");
186        write_file(
187            &reddb_file::blob_cache_control_path(&l2_src),
188            b"control-sidecar-bytes",
189        );
190
191        let backend_root = scratch("pair-be");
192        let prefix = format!("{}/blob_cache/", backend_root.display());
193
194        let uploaded =
195            archive_blob_cache_l2(&LocalBackend, &l2_src, &prefix).expect("archive succeeds");
196        assert_eq!(uploaded, 2, "pager + control sidecar uploaded");
197
198        let dst_dir = scratch("pair-dst");
199        let l2_dst = dst_dir.join("cache.rdb");
200        let downloaded =
201            restore_blob_cache_l2(&LocalBackend, &prefix, &l2_dst).expect("restore succeeds");
202        assert_eq!(downloaded, 2);
203
204        assert_eq!(std::fs::read(&l2_dst).unwrap(), b"pager-bytes-on-disk");
205        assert_eq!(
206            std::fs::read(reddb_file::blob_cache_control_path(&l2_dst)).unwrap(),
207            b"control-sidecar-bytes"
208        );
209
210        let _ = std::fs::remove_dir_all(&scratch_dir);
211        let _ = std::fs::remove_dir_all(&backend_root);
212        let _ = std::fs::remove_dir_all(&dst_dir);
213    }
214
215    #[test]
216    fn archive_missing_l2_path_is_noop() {
217        let backend_root = scratch("be-missing");
218        let prefix = format!("{}/blob_cache/", backend_root.display());
219        let count = archive_blob_cache_l2(
220            &LocalBackend,
221            std::path::Path::new("/nonexistent/path/for/reddb-test.rdb"),
222            &prefix,
223        )
224        .expect("missing path treated as nothing to archive");
225        assert_eq!(count, 0);
226        let _ = std::fs::remove_dir_all(&backend_root);
227    }
228
229    #[test]
230    fn restore_with_no_objects_creates_empty_parent_dir() {
231        let backend_root = scratch("be-empty");
232        let prefix = format!("{}/blob_cache/", backend_root.display());
233        let dst_dir = scratch("dst-empty");
234        let l2_dst = dst_dir.join("cache.rdb");
235        let count =
236            restore_blob_cache_l2(&LocalBackend, &prefix, &l2_dst).expect("empty restore is ok");
237        assert_eq!(count, 0);
238        let _ = std::fs::remove_dir_all(&backend_root);
239        let _ = std::fs::remove_dir_all(&dst_dir);
240    }
241
242    /// End-to-end round-trip through a real `BlobCache`:
243    /// 1. Build a cache with an L2 path, put two entries (so blob bytes
244    ///    plus metadata land on disk).
245    /// 2. Drop the cache (closes the L2 metadata B+ tree).
246    /// 3. Archive the L2 directory to the backend.
247    /// 4. Restore into a fresh L2 path.
248    /// 5. Open a new `BlobCache` against the restored path and verify
249    ///    `get` returns the original bytes — proves the cold-start
250    ///    synopsis rebuild (`blob/l2.rs::BlobCacheL2::rebuild_l2_synopsis`) re-indexes
251    ///    the restored tree end-to-end.
252    ///
253    /// This is the integration-test that ADR 0006 §"backup-restore"
254    /// commits to and that the lane plan calls out as the
255    /// `include_blob_cache=true` round-trip success criterion.
256    #[test]
257    fn full_round_trip_via_blob_cache_preserves_entries_after_restore() {
258        use crate::storage::cache::blob::{BlobCache, BlobCacheConfig, BlobCachePut};
259
260        let src_dir = scratch("rt-src");
261        let dst_dir = scratch("rt-dst");
262        let backend_root = scratch("rt-be");
263        let l2_src = src_dir.join("blob-cache.rdb");
264        let l2_dst = dst_dir.join("blob-cache.rdb");
265        let prefix = format!("{}/blob_cache/", backend_root.display());
266
267        // 1+2: put entries + drop the cache so L2 fsyncs.
268        {
269            let cache = BlobCache::open_with_l2(
270                BlobCacheConfig::default()
271                    .with_l1_bytes_max(64 * 1024)
272                    .with_shard_count(2)
273                    .with_max_namespaces(8)
274                    .with_l2_path(&l2_src),
275            )
276            .expect("open l2 src");
277            cache
278                .put("ns-a", "k1", BlobCachePut::new(b"value-1".to_vec()))
279                .expect("put k1");
280            cache
281                .put(
282                    "ns-b",
283                    "k2",
284                    BlobCachePut::new(b"value-2-longer-payload".to_vec()),
285                )
286                .expect("put k2");
287            // L2 path accessor must see the configured file path.
288            assert_eq!(cache.l2_path(), Some(l2_src.as_path()));
289        } // drop cache
290
291        // 3: archive L2 (pager file + control sidecar).
292        let uploaded = archive_blob_cache_l2(&LocalBackend, &l2_src, &prefix).expect("archive l2");
293        assert_eq!(uploaded, 2, "pager + control uploaded");
294
295        // 4: restore into fresh path.
296        let restored = restore_blob_cache_l2(&LocalBackend, &prefix, &l2_dst).expect("restore l2");
297        assert_eq!(restored, 2, "pager + control downloaded");
298
299        // 5: re-open against restored path and verify entries are
300        //    addressable. The synopsis rebuild fires automatically in
301        //    BlobCache::new (per blob/l2.rs::BlobCacheL2::rebuild_l2_synopsis).
302        let restored_cache = BlobCache::open_with_l2(
303            BlobCacheConfig::default()
304                .with_l1_bytes_max(64 * 1024)
305                .with_shard_count(2)
306                .with_max_namespaces(8)
307                .with_l2_path(&l2_dst),
308        )
309        .expect("open l2 dst");
310        let hit_a = restored_cache
311            .get("ns-a", "k1")
312            .expect("k1 survives restore");
313        assert_eq!(hit_a.value(), b"value-1");
314        let hit_b = restored_cache
315            .get("ns-b", "k2")
316            .expect("k2 survives restore");
317        assert_eq!(hit_b.value(), b"value-2-longer-payload");
318
319        let _ = std::fs::remove_dir_all(&src_dir);
320        let _ = std::fs::remove_dir_all(&dst_dir);
321        let _ = std::fs::remove_dir_all(&backend_root);
322    }
323
324    /// Inverse contract: with `include_blob_cache` left at its default
325    /// (false) — i.e., we simply skip the archive step — restoring into
326    /// a fresh path leaves the cache cold. This is the documented
327    /// default behaviour (`docs/operations/blob-cache-backup-restore.md`
328    /// §1: "Consequences for restore: the cache starts empty").
329    #[test]
330    fn skipped_archive_leaves_restored_cache_cold() {
331        use crate::storage::cache::blob::{BlobCache, BlobCacheConfig, BlobCachePut};
332
333        let src_dir = scratch("cold-src");
334        let dst_dir = scratch("cold-dst");
335        let l2_src = src_dir.join("blob-cache.rdb");
336        let l2_dst = dst_dir.join("blob-cache.rdb");
337
338        {
339            let cache = BlobCache::open_with_l2(BlobCacheConfig::default().with_l2_path(&l2_src))
340                .expect("open l2 src");
341            cache
342                .put("ns", "k", BlobCachePut::new(b"value".to_vec()))
343                .expect("put k");
344        }
345
346        // Note: NO archive step. The fresh L2 path stays empty, mirroring
347        // the default backup posture (include_blob_cache=false).
348        let cold_cache = BlobCache::open_with_l2(BlobCacheConfig::default().with_l2_path(&l2_dst))
349            .expect("open l2 dst");
350        assert!(
351            cold_cache.get("ns", "k").is_none(),
352            "restore without include_blob_cache must yield a cold cache"
353        );
354
355        let _ = std::fs::remove_dir_all(&src_dir);
356        let _ = std::fs::remove_dir_all(&dst_dir);
357    }
358}