reddb_server/storage/unified/store/
secondary_index.rs1use super::*;
8use reddb_file::native_resume::SecondaryIndexResume;
9
10pub use reddb_engine::storage::secondary_index_read::SECONDARY_KEY_BYTES_MAX;
12pub type SecondaryIndexRead =
13 reddb_engine::storage::secondary_index_read::SecondaryIndexRead<Pager>;
14
15pub(crate) const RUNTIME_SECONDARY_INDEX_CODEC_VERSION: u32 = 3;
16
17#[cfg(test)]
18std::thread_local! {
19 static LEGACY_RUNTIME_SECONDARY_INDEX_IDENTITY: std::cell::Cell<bool> =
20 const { std::cell::Cell::new(false) };
21 static CHECKPOINT_SECONDARY_INDEX_SKIP_ENTITY:
22 std::cell::RefCell<Option<(String, u64)>> = const { std::cell::RefCell::new(None) };
23}
24
25pub(crate) fn runtime_secondary_index_codec_version() -> u32 {
26 #[cfg(test)]
27 if LEGACY_RUNTIME_SECONDARY_INDEX_IDENTITY.with(std::cell::Cell::get) {
28 return 2;
29 }
30 RUNTIME_SECONDARY_INDEX_CODEC_VERSION
31}
32
33#[cfg(test)]
34pub(crate) struct LegacyRuntimeSecondaryIndexIdentityGuard;
35
36#[cfg(test)]
37impl Drop for LegacyRuntimeSecondaryIndexIdentityGuard {
38 fn drop(&mut self) {
39 LEGACY_RUNTIME_SECONDARY_INDEX_IDENTITY.with(|legacy| legacy.set(false));
40 }
41}
42
43#[cfg(test)]
44pub(crate) fn use_legacy_runtime_secondary_index_identity(
45) -> LegacyRuntimeSecondaryIndexIdentityGuard {
46 assert!(
47 !LEGACY_RUNTIME_SECONDARY_INDEX_IDENTITY.with(|legacy| legacy.replace(true)),
48 "legacy runtime secondary-index identity is already active"
49 );
50 LegacyRuntimeSecondaryIndexIdentityGuard
51}
52
53#[cfg(test)]
54pub(crate) struct CheckpointSecondaryIndexSkipEntityGuard;
55
56#[cfg(test)]
57impl Drop for CheckpointSecondaryIndexSkipEntityGuard {
58 fn drop(&mut self) {
59 CHECKPOINT_SECONDARY_INDEX_SKIP_ENTITY.with(|skip| {
60 skip.borrow_mut().take();
61 });
62 }
63}
64
65#[cfg(test)]
66pub(crate) fn checkpoint_secondary_indices_without_entity(
67 collection: &str,
68 entity_id: u64,
69) -> CheckpointSecondaryIndexSkipEntityGuard {
70 CHECKPOINT_SECONDARY_INDEX_SKIP_ENTITY.with(|skip| {
71 let previous = skip.borrow_mut().replace((
72 UnifiedStore::canonical_collection(collection).to_string(),
73 entity_id,
74 ));
75 assert!(
76 previous.is_none(),
77 "secondary-index checkpoint skip is already active"
78 );
79 });
80 CheckpointSecondaryIndexSkipEntityGuard
81}
82
83#[cfg(test)]
84fn checkpoint_skips_secondary_index_entity(collection: &str, entity_id: u64) -> bool {
85 CHECKPOINT_SECONDARY_INDEX_SKIP_ENTITY.with(|skip| {
86 skip.borrow()
87 .as_ref()
88 .is_some_and(|(candidate, id)| candidate == collection && *id == entity_id)
89 })
90}
91
92#[derive(Clone, Debug, PartialEq, Eq)]
93pub struct SecondaryIndexIdentity {
94 pub codec_version: u32,
95 pub definition: [u8; 32],
96}
97
98pub trait SecondaryIndexProjector: Send + Sync {
103 fn project(
104 &self,
105 entity: &UnifiedEntity,
106 key: &mut [u8; SECONDARY_KEY_BYTES_MAX],
107 ) -> Result<Option<usize>, StoreError>;
108}
109
110#[derive(Clone)]
111pub(super) struct SecondaryIndexSpec {
112 pub(super) identity: SecondaryIndexIdentity,
113 pub(super) predecessors: Vec<SecondaryIndexIdentity>,
118 pub(super) projector: Arc<dyn SecondaryIndexProjector>,
119 pub(super) deferred: bool,
120 pub(super) optional: bool,
124}
125
126pub(super) type SecondaryIndexSpecs = HashMap<String, BTreeMap<String, SecondaryIndexSpec>>;
127
128#[derive(Clone)]
129pub(super) struct PublishedSecondaryIndex {
130 pub identity: SecondaryIndexIdentity,
131 pub tree: Arc<BTree>,
132}
133
134impl PublishedSecondaryIndex {
135 pub(super) fn resume(&self) -> SecondaryIndexResume {
136 SecondaryIndexResume {
137 root_page: self.tree.root_page_id(),
138 codec_version: self.identity.codec_version,
139 definition: self.identity.definition,
140 }
141 }
142}
143
144impl PublishedKeyIndex {
145 pub(super) fn trees(&self) -> impl Iterator<Item = &Arc<BTree>> {
146 std::iter::once(&self.tree).chain(self.secondary.values().map(|index| &index.tree))
147 }
148}
149
150impl UnifiedStore {
151 #[cfg(test)]
152 pub(crate) fn rebuild_secondary_indices_on_next_checkpoint(
153 &self,
154 collection: &str,
155 names: &[&str],
156 ) {
157 let collection = Self::canonical_collection(collection);
158 let _publication = self.vault_publication_lock.lock();
159 let removed = {
160 let mut generations = self.key_indices.write();
161 let generation = generations
162 .get_mut(collection)
163 .expect("secondary-index checkpoint fixture generation");
164 names
165 .iter()
166 .filter_map(|name| generation.secondary.remove(*name))
167 .collect::<Vec<_>>()
168 };
169 assert_eq!(
170 removed.len(),
171 names.len(),
172 "secondary-index checkpoint fixture must remove every requested artifact"
173 );
174 for index in removed {
175 self.retire_btree(index.tree);
176 }
177 self.resident
178 .paged_registry_dirty
179 .store(true, Ordering::Release);
180 }
181
182 pub(crate) fn verify_persisted_secondary_index(
186 &self,
187 collection: &str,
188 name: &str,
189 limit_bytes: usize,
190 ) -> Result<Option<String>, StoreError> {
191 use reddb_engine::storage::collection_read::{CollectionCursor, PagedCollection};
192 let _publication = self.vault_publication_lock.lock();
193 let specs = self.secondary_index_specs.read();
194 let spec = specs
195 .get(collection)
196 .and_then(|indices| indices.get(name))
197 .ok_or_else(|| StoreError::Serialization("index has no persisted projection".into()))?;
198 let trees = self.btree_indices.read();
199 let Some(data) = trees.get(collection) else {
200 return Ok(Some("collection has no checkpoint generation".into()));
201 };
202 let keys = self.key_indices.read();
203 let index = keys
204 .get(collection)
205 .filter(|generation| generation.source.ptr_eq(&Arc::downgrade(data)))
206 .and_then(|generation| generation.secondary.get(name))
207 .filter(|index| index.identity == spec.identity);
208 let Some(index) = index else {
209 return Ok(Some("missing or incompatible persisted index".into()));
210 };
211 let source = PagedCollection::new(Arc::clone(data));
212 let mut cursor = source.scan()?;
213 let mut key = [0; SECONDARY_KEY_BYTES_MAX];
214 let mut expected = 0u64;
215 while let Some(record) = cursor.next_record(limit_bytes)? {
216 let (entity, _) = record.decode_with_budget(self.format_version(), limit_bytes)?;
217 let Some(length) = spec.projector.project(&entity, &mut key)? else {
218 continue;
219 };
220 if length > key.len() {
221 return Err(StoreError::Serialization(
222 "secondary key exceeds its bounded buffer".into(),
223 ));
224 }
225 let mut posting = [0; SECONDARY_KEY_BYTES_MAX + 8];
226 posting[..length].copy_from_slice(&key[..length]);
227 posting[length..length + 8].copy_from_slice(&entity.id.raw().to_be_bytes());
228 match index
229 .tree
230 .get_with_budget(&posting[..length + 8], limit_bytes)
231 {
232 Ok(Some(value)) if value.is_empty() => expected += 1,
233 Ok(_) => {
234 return Ok(Some(format!(
235 "missing or invalid posting for physical entity {}",
236 entity.id.raw()
237 )))
238 }
239 Err(error) => return Ok(Some(format!("index read failed: {error}"))),
240 }
241 }
242 let handle = SecondaryIndexRead::with_source(Arc::clone(&index.tree), Arc::clone(data));
243 let mut actual = 0u64;
244 if let Err(error) = handle.try_for_each(|_, _| {
245 actual += 1;
246 Ok(())
247 }) {
248 return Ok(Some(format!("index inventory failed: {error}")));
249 }
250 Ok((actual != expected)
251 .then(|| format!("posting count mismatch: expected {expected}, found {actual}")))
252 }
253
254 pub fn register_secondary_index(
258 &self,
259 collection: &str,
260 name: &str,
261 identity: SecondaryIndexIdentity,
262 projector: Arc<dyn SecondaryIndexProjector>,
263 ) -> Result<(), StoreError> {
264 self.register_secondary_index_as(collection, name, identity, Vec::new(), projector, false)
265 }
266
267 pub fn register_optional_secondary_index(
270 &self,
271 collection: &str,
272 name: &str,
273 identity: SecondaryIndexIdentity,
274 projector: Arc<dyn SecondaryIndexProjector>,
275 ) -> Result<(), StoreError> {
276 self.register_secondary_index_as(collection, name, identity, Vec::new(), projector, true)
277 }
278
279 pub fn register_optional_secondary_index_after(
286 &self,
287 collection: &str,
288 name: &str,
289 identity: SecondaryIndexIdentity,
290 predecessors: Vec<SecondaryIndexIdentity>,
291 projector: Arc<dyn SecondaryIndexProjector>,
292 ) -> Result<(), StoreError> {
293 self.register_secondary_index_as(collection, name, identity, predecessors, projector, true)
294 }
295
296 fn register_secondary_index_as(
297 &self,
298 collection: &str,
299 name: &str,
300 identity: SecondaryIndexIdentity,
301 predecessors: Vec<SecondaryIndexIdentity>,
302 projector: Arc<dyn SecondaryIndexProjector>,
303 optional: bool,
304 ) -> Result<(), StoreError> {
305 let collection = Self::canonical_collection(collection);
306 if name.is_empty() || name.len() > 1024 || identity.codec_version == 0 {
307 return Err(StoreError::Serialization(
308 "invalid secondary index identity".into(),
309 ));
310 }
311 let _publication = self.vault_publication_lock.lock();
312 if self.config.resident_memory_bytes_max.is_none()
313 || (self.commit.is_none() && !self.is_read_only())
314 {
315 return Err(StoreError::Serialization(
316 "secondary trees require disk residency and durable page ownership".into(),
317 ));
318 }
319 if !self.resident.collections.read().contains_key(collection) {
320 return Err(StoreError::CollectionNotFound(collection.into()));
321 }
322 let mut specs = self.secondary_index_specs.write();
323 let indices = specs.entry(collection.to_owned()).or_default();
324 if !indices.contains_key(name) && indices.len() >= 4096 {
325 return Err(StoreError::Serialization(
326 "too many secondary indexes".into(),
327 ));
328 }
329 indices.insert(
330 name.to_owned(),
331 SecondaryIndexSpec {
332 identity,
333 predecessors,
334 projector,
335 deferred: false,
336 optional,
337 },
338 );
339 Ok(())
340 }
341
342 pub(crate) fn checkpoint_missing_secondary_indices(&self) -> Result<(), StoreError> {
351 let missing = {
352 let _publication = self.vault_publication_lock.lock();
353 let specs = self.secondary_index_specs.read();
354 specs.iter().any(|(collection, indices)| {
355 indices.iter().any(|(name, spec)| {
356 !spec.deferred
357 && !spec.optional
358 && self
359 .secondary_index(collection, name, &spec.identity)
360 .is_none()
361 })
362 })
363 };
364 if missing {
365 self.persist()?;
366 }
367 Ok(())
368 }
369
370 pub fn secondary_index(
376 &self,
377 collection: &str,
378 name: &str,
379 identity: &SecondaryIndexIdentity,
380 ) -> Option<SecondaryIndexRead> {
381 let collection = Self::canonical_collection(collection);
382 let _publication = self.vault_publication_lock.lock();
383 let (published, tree, data) = {
384 let trees = self.btree_indices.read();
385 let data = trees.get(collection)?;
386 let keys = self.key_indices.read();
387 let generation = keys.get(collection)?;
388 if !generation.source.ptr_eq(&Arc::downgrade(data)) {
389 return None;
390 }
391 let index = generation.secondary.get(name)?;
392 (
393 index.identity.clone(),
394 Arc::clone(&index.tree),
395 Arc::clone(data),
396 )
397 };
398 let readable = published == *identity
402 || self
403 .secondary_index_specs
404 .read()
405 .get(collection)
406 .and_then(|indices| indices.get(name))
407 .is_some_and(|spec| {
408 spec.identity == *identity && spec.predecessors.contains(&published)
409 });
410 readable.then(|| SecondaryIndexRead::with_source(tree, data))
411 }
412
413 pub fn unregister_secondary_index(&self, collection: &str, name: &str) {
416 let collection = Self::canonical_collection(collection);
417 let _publication = self.vault_publication_lock.lock();
418 if let Some(specs) = self.secondary_index_specs.write().get_mut(collection) {
419 specs.remove(name);
420 }
421 if let Some(index) = self
422 .key_indices
423 .write()
424 .get_mut(collection)
425 .and_then(|generation| generation.secondary.remove(name))
426 {
427 self.retire_btree(index.tree);
428 self.resident
429 .paged_registry_dirty
430 .store(true, Ordering::Release);
431 }
432 }
433
434 pub(super) fn checkpoint_secondary_indices(
435 &self,
436 collection: &str,
437 data: &Arc<BTree>,
438 previous: Option<&PublishedKeyIndex>,
439 pager: &Arc<Pager>,
440 limit_bytes: usize,
441 ) -> Result<BTreeMap<String, PublishedSecondaryIndex>, StoreError> {
442 use reddb_engine::storage::collection_read::{CollectionCursor, PagedCollection};
443 let same_generation = previous.filter(|index| index.source.ptr_eq(&Arc::downgrade(data)));
444 let mut next = same_generation
445 .map(|index| index.secondary.clone())
446 .unwrap_or_default();
447 let specs = self.secondary_index_specs.read();
448 let Some(specs) = specs.get(collection) else {
449 return Ok(next);
450 };
451 let mut builds = Vec::new();
452 for (name, spec) in specs {
453 if next
454 .get(name)
455 .is_some_and(|index| index.identity == spec.identity)
456 {
457 continue;
458 }
459 if spec.deferred {
460 continue;
461 }
462 if name == super::count_index::NAME {
463 if let Some(tree) = self.checkpoint_count_projection_seed(
464 collection,
465 data.root_page_id(),
466 &spec.identity,
467 pager,
468 )? {
469 next.insert(
470 name.clone(),
471 PublishedSecondaryIndex {
472 identity: spec.identity.clone(),
473 tree,
474 },
475 );
476 continue;
477 }
478 }
479 builds.push((name, spec, Self::new_derived_btree(pager)?));
480 }
481 if builds.is_empty() {
482 return Ok(next);
483 }
484 let source = PagedCollection::new(Arc::clone(data));
485 let mut cursor = source.scan()?;
486 let mut key = [0; SECONDARY_KEY_BYTES_MAX];
487 while let Some(record) = cursor.next_record(limit_bytes)? {
488 let (entity, _) = record.decode_with_budget(self.format_version(), limit_bytes)?;
489 #[cfg(test)]
490 if checkpoint_skips_secondary_index_entity(collection, entity.id.raw()) {
491 continue;
492 }
493 for (_, spec, tree) in &builds {
494 let Some(length) = spec.projector.project(&entity, &mut key)? else {
495 continue;
496 };
497 if length > key.len() {
498 return Err(StoreError::Serialization(
499 "secondary key exceeds its bounded buffer".into(),
500 ));
501 }
502 let mut posting = [0; SECONDARY_KEY_BYTES_MAX + 8];
503 posting[..length].copy_from_slice(&key[..length]);
504 posting[length..length + 8].copy_from_slice(&entity.id.raw().to_be_bytes());
505 tree.insert(&posting[..length + 8], &[])
506 .map_err(|error| StoreError::Io(std::io::Error::other(error.to_string())))?;
507 }
508 }
509 for (name, spec, tree) in builds {
510 next.insert(
511 name.clone(),
512 PublishedSecondaryIndex {
513 identity: spec.identity.clone(),
514 tree,
515 },
516 );
517 }
518 Ok(next)
519 }
520}
521
522#[cfg(test)]
523mod tests;