Skip to main content

waratah_storage/
blob_index.rs

1//! RocksDB-backed blob index: 16-byte content hash -> tagged value.
2//!
3//! The registry's blob store keeps payloads at or below its inline threshold
4//! in this DB and larger payloads in append-only segment files. This module
5//! owns only the RocksDB plumbing; the tag/locator encoding and the segment
6//! files live in `waratah_registry::blobs`.
7//!
8//! The index is a point-lookup workload, so its tuning differs from the
9//! string dictionary's: 4 KiB blocks, a dedicated 64 MiB block cache, and a
10//! Bloom filter ([`RocksDbTuning::blob_index`]). It is a separate DB, not a
11//! column family in the dictionary, so `FlushMemtables`/`CompactRange` on the
12//! dictionary keep their current meaning and the two caches stay isolated.
13
14use std::fmt;
15use std::path::Path;
16
17use crate::rocksdb_db::{ColumnFamily, ColumnFamilyDefinition, Db, WriteBatch};
18use crate::{RocksDbOptionsHooks, RocksDbTuning, StorageError};
19
20// Re-exported so [`BlobIndex::iter_entries`] can name a type from the
21// private `rocksdb_db` module in a public signature; `waratah_storage`
22// re-exports it in turn as `BlobIndexIter`.
23pub use crate::rocksdb_db::Iter;
24
25/// Column family holding the blob index entries.
26pub const BLOB_INDEX_CF: &str = "index";
27
28/// Point-lookup RocksDB index over content-addressed blob entries.
29///
30/// Blob entries (16-byte hash keys) live in the `index` column family. A
31/// small set of maintenance keys (the per-segment durable lengths) live in
32/// the implicit `default` column family instead, so a meta key can never
33/// collide with a hash key and a full `index` scan yields exactly the blob
34/// entries.
35pub struct BlobIndex {
36    db: Db,
37    cf: ColumnFamily,
38    meta_cf: ColumnFamily,
39}
40
41impl fmt::Debug for BlobIndex {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        f.debug_struct("BlobIndex").finish_non_exhaustive()
44    }
45}
46
47impl BlobIndex {
48    /// Open (creating if missing) the blob index at `path` with
49    /// [`RocksDbTuning::blob_index`].
50    pub fn open(path: impl AsRef<Path>) -> Result<Self, StorageError> {
51        Self::open_with_tuning(path, RocksDbTuning::blob_index())
52    }
53
54    /// Open the blob index with explicit tuning (tests and benchmarks).
55    pub fn open_with_tuning(
56        path: impl AsRef<Path>,
57        tuning: RocksDbTuning,
58    ) -> Result<Self, StorageError> {
59        let path = path.as_ref();
60        std::fs::create_dir_all(path).map_err(|e| StorageError::Backend(e.to_string()))?;
61        let db = Db::open_read_write_with_hooks(
62            path,
63            vec![ColumnFamilyDefinition {
64                name: BLOB_INDEX_CF,
65                min_prefix_size: 0,
66                // No per-SST prefix filter: the blob index has its own
67                // always-on whole-key Bloom filter (see RocksDbTuning::blob_index);
68                // the prefix-filter machinery is for hexastore subject/class
69                // columns whose leading term is fixed-width.
70                prefix_filter: false,
71                permutation: None,
72            }],
73            RocksDbOptionsHooks {
74                tuning,
75                ..Default::default()
76            },
77        )?;
78        let cf = db.column_family(BLOB_INDEX_CF)?;
79        let meta_cf = db.column_family("default")?;
80        Ok(Self { db, cf, meta_cf })
81    }
82
83    /// Get one key, or `None` if absent.
84    pub fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, StorageError> {
85        self.db.get(&self.cf, key)
86    }
87
88    /// Positional batched point lookup; `None` marks a missing key.
89    ///
90    /// Values are copied once out of RocksDB's pinned `MultiGet` batch; the
91    /// pins are released before this returns. `keys` need not be sorted:
92    /// RocksDB sorts the batch internally.
93    pub fn multi_get(&self, keys: &[&[u8]]) -> Result<Vec<Option<Vec<u8>>>, StorageError> {
94        self.db.multi_get_pinned(&self.cf, keys, false)
95    }
96
97    /// Get one maintenance key from the `default` column family.
98    pub fn get_meta(&self, key: &[u8]) -> Result<Option<Vec<u8>>, StorageError> {
99        self.db.get(&self.meta_cf, key)
100    }
101
102    /// Iterate every blob entry (hash key → tagged value) in index order.
103    ///
104    /// Meta keys are excluded — they live in the `default` column family —
105    /// so a full walk of this iterator is exactly the blob entry set
106    /// (`waratah blob verify`).
107    pub fn iter_entries(&self) -> Iter<'_> {
108        self.db.scan_prefix(&self.cf, b"")
109    }
110
111    /// Start an atomic write batch against the index.
112    pub fn write_batch(&self) -> BlobIndexBatch {
113        BlobIndexBatch {
114            cf: self.cf,
115            meta_cf: self.meta_cf,
116            batch: self.db.write_batch(),
117        }
118    }
119
120    /// Flush the MemTables to SST files and wait for completion. Covers
121    /// both column families: the blob entries and the `default`
122    /// maintenance keys (per-segment durable lengths) — leaving the
123    /// maintenance keys unflushed would make them WAL-replay-only forever.
124    pub fn flush(&self) -> Result<(), StorageError> {
125        self.db.flush_cfs(&[&self.cf, &self.meta_cf])
126    }
127
128    /// Full-range compaction of both column families (blob entries and
129    /// the `default` maintenance keys).
130    pub fn compact(&self) {
131        self.db.compact_cf(&self.cf);
132        self.db.compact_cf(&self.meta_cf);
133    }
134
135    /// This DB's block-cache `(capacity, used)` bytes, for metrics.
136    pub fn block_cache_bytes(&self) -> Option<(u64, u64)> {
137        self.db.block_cache_bytes()
138    }
139}
140
141/// Atomic batch over the blob index.
142///
143/// Drop without [`Self::commit`] and nothing is written. The batch holds a
144/// `Db` clone, so the column-family handles stay valid for the batch's
145/// lifetime even if the [`BlobIndex`] is dropped first.
146pub struct BlobIndexBatch {
147    cf: ColumnFamily,
148    meta_cf: ColumnFamily,
149    batch: WriteBatch,
150}
151
152impl BlobIndexBatch {
153    /// Stage `key -> value` in the blob-entry column family.
154    pub fn insert(&mut self, key: &[u8], value: &[u8]) {
155        self.batch.insert(&self.cf, key, value);
156    }
157
158    /// Stage `key -> value` in the maintenance (`default`) column family.
159    pub fn insert_meta(&mut self, key: &[u8], value: &[u8]) {
160        self.batch.insert(&self.meta_cf, key, value);
161    }
162
163    /// Stage a delete of `key`.
164    pub fn delete(&mut self, key: &[u8]) {
165        self.batch.delete(&self.cf, key);
166    }
167
168    /// Commit every staged put/delete atomically. Durable on return: the
169    /// blob index is opened with [`RocksDbTuning::blob_index`], whose
170    /// synchronous WAL writes fsync the batch's WAL entry inside this call
171    /// (see [`crate::RocksDbTuning::sync_writes`]).
172    pub fn commit(self) -> Result<(), StorageError> {
173        self.batch.commit()
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180    use pretty_assertions::assert_eq;
181
182    fn index() -> (tempfile::TempDir, BlobIndex) {
183        let dir = tempfile::tempdir().unwrap();
184        let index = BlobIndex::open(dir.path().join("index")).unwrap();
185        (dir, index)
186    }
187
188    #[test]
189    fn get_and_multi_get_are_positional() {
190        let (_dir, index) = index();
191        let mut batch = index.write_batch();
192        batch.insert(b"a", b"alpha");
193        batch.insert(b"b", b"beta");
194        batch.commit().unwrap();
195        assert_eq!(index.get(b"a").unwrap(), Some(b"alpha".to_vec()));
196        let keys: Vec<&[u8]> = vec![b"b", b"missing", b"a", b"b"];
197        assert_eq!(
198            index.multi_get(&keys).unwrap(),
199            vec![
200                Some(b"beta".to_vec()),
201                None,
202                Some(b"alpha".to_vec()),
203                Some(b"beta".to_vec()),
204            ]
205        );
206    }
207
208    #[test]
209    fn dropped_batch_writes_nothing() {
210        let (_dir, index) = index();
211        {
212            let mut batch = index.write_batch();
213            batch.insert(b"a", b"alpha");
214        }
215        assert_eq!(index.get(b"a").unwrap(), None);
216    }
217
218    #[test]
219    fn batch_commits_puts_and_deletes_atomically() {
220        let (_dir, index) = index();
221        let mut batch = index.write_batch();
222        batch.insert(b"a", b"alpha");
223        batch.insert(b"b", b"beta");
224        batch.commit().unwrap();
225
226        let mut batch = index.write_batch();
227        batch.delete(b"a");
228        batch.insert(b"b", b"BETA");
229        batch.insert(b"c", b"gamma");
230        batch.commit().unwrap();
231
232        assert_eq!(index.get(b"a").unwrap(), None);
233        assert_eq!(index.get(b"b").unwrap(), Some(b"BETA".to_vec()));
234        assert_eq!(index.get(b"c").unwrap(), Some(b"gamma".to_vec()));
235    }
236
237    #[test]
238    fn flush_and_compact_are_callable() {
239        let (_dir, index) = index();
240        let mut batch = index.write_batch();
241        batch.insert(b"a", b"alpha");
242        batch.commit().unwrap();
243        index.flush().unwrap();
244        index.compact();
245        assert_eq!(index.get(b"a").unwrap(), Some(b"alpha".to_vec()));
246        assert!(index.block_cache_bytes().unwrap().0 > 0);
247    }
248
249    #[test]
250    fn ssts_carry_the_whole_key_bloom_filter() {
251        // The blob index's Bloom filter is a whole-key policy on the DB's
252        // base table options (RocksDbTuning::blob_index's
253        // bloom_filter_bits_per_key), inherited by every column family —
254        // unlike the per-SST prefix filters, which are opt-in per column
255        // family and env-gated. The blob index CFs opt out of the prefix
256        // machinery (prefix_filter: false); this pins that the whole-key
257        // policy still lands in every flushed SST, so the two filter
258        // mechanisms cannot silently shadow one another.
259        let (_dir, index) = index();
260        let mut batch = index.write_batch();
261        batch.insert(b"a", b"alpha");
262        batch.commit().unwrap();
263        index.flush().unwrap();
264        let names = index.db.table_filter_policy_names(&index.cf).unwrap();
265        assert!(
266            !names.is_empty(),
267            "flush must have written at least one SST"
268        );
269        assert!(
270            names.iter().all(|name| name == "bloomfilter"),
271            "every SST must carry the whole-key bloom (compatibility name \
272             \"bloomfilter\"), got {names:?}"
273        );
274    }
275}