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) projector: Arc<dyn SecondaryIndexProjector>,
114 pub(super) deferred: bool,
115 pub(super) optional: bool,
119}
120
121pub(super) type SecondaryIndexSpecs = HashMap<String, BTreeMap<String, SecondaryIndexSpec>>;
122
123#[derive(Clone)]
124pub(super) struct PublishedSecondaryIndex {
125 pub identity: SecondaryIndexIdentity,
126 pub tree: Arc<BTree>,
127}
128
129impl PublishedSecondaryIndex {
130 pub(super) fn resume(&self) -> SecondaryIndexResume {
131 SecondaryIndexResume {
132 root_page: self.tree.root_page_id(),
133 codec_version: self.identity.codec_version,
134 definition: self.identity.definition,
135 }
136 }
137}
138
139impl PublishedKeyIndex {
140 pub(super) fn trees(&self) -> impl Iterator<Item = &Arc<BTree>> {
141 std::iter::once(&self.tree).chain(self.secondary.values().map(|index| &index.tree))
142 }
143}
144
145impl UnifiedStore {
146 #[cfg(test)]
147 pub(crate) fn rebuild_secondary_indices_on_next_checkpoint(
148 &self,
149 collection: &str,
150 names: &[&str],
151 ) {
152 let collection = Self::canonical_collection(collection);
153 let _publication = self.vault_publication_lock.lock();
154 let removed = {
155 let mut generations = self.key_indices.write();
156 let generation = generations
157 .get_mut(collection)
158 .expect("secondary-index checkpoint fixture generation");
159 names
160 .iter()
161 .filter_map(|name| generation.secondary.remove(*name))
162 .collect::<Vec<_>>()
163 };
164 assert_eq!(
165 removed.len(),
166 names.len(),
167 "secondary-index checkpoint fixture must remove every requested artifact"
168 );
169 for index in removed {
170 self.retire_btree(index.tree);
171 }
172 self.resident
173 .paged_registry_dirty
174 .store(true, Ordering::Release);
175 }
176
177 pub(crate) fn verify_persisted_secondary_index(
181 &self,
182 collection: &str,
183 name: &str,
184 limit_bytes: usize,
185 ) -> Result<Option<String>, StoreError> {
186 use reddb_engine::storage::collection_read::{CollectionCursor, PagedCollection};
187 let _publication = self.vault_publication_lock.lock();
188 let specs = self.secondary_index_specs.read();
189 let spec = specs
190 .get(collection)
191 .and_then(|indices| indices.get(name))
192 .ok_or_else(|| StoreError::Serialization("index has no persisted projection".into()))?;
193 let trees = self.btree_indices.read();
194 let Some(data) = trees.get(collection) else {
195 return Ok(Some("collection has no checkpoint generation".into()));
196 };
197 let keys = self.key_indices.read();
198 let index = keys
199 .get(collection)
200 .filter(|generation| generation.source.ptr_eq(&Arc::downgrade(data)))
201 .and_then(|generation| generation.secondary.get(name))
202 .filter(|index| index.identity == spec.identity);
203 let Some(index) = index else {
204 return Ok(Some("missing or incompatible persisted index".into()));
205 };
206 let source = PagedCollection::new(Arc::clone(data));
207 let mut cursor = source.scan()?;
208 let mut key = [0; SECONDARY_KEY_BYTES_MAX];
209 let mut expected = 0u64;
210 while let Some(record) = cursor.next_record(limit_bytes)? {
211 let (entity, _) = record.decode_with_budget(self.format_version(), limit_bytes)?;
212 let Some(length) = spec.projector.project(&entity, &mut key)? else {
213 continue;
214 };
215 if length > key.len() {
216 return Err(StoreError::Serialization(
217 "secondary key exceeds its bounded buffer".into(),
218 ));
219 }
220 let mut posting = [0; SECONDARY_KEY_BYTES_MAX + 8];
221 posting[..length].copy_from_slice(&key[..length]);
222 posting[length..length + 8].copy_from_slice(&entity.id.raw().to_be_bytes());
223 match index
224 .tree
225 .get_with_budget(&posting[..length + 8], limit_bytes)
226 {
227 Ok(Some(value)) if value.is_empty() => expected += 1,
228 Ok(_) => {
229 return Ok(Some(format!(
230 "missing or invalid posting for physical entity {}",
231 entity.id.raw()
232 )))
233 }
234 Err(error) => return Ok(Some(format!("index read failed: {error}"))),
235 }
236 }
237 let handle = SecondaryIndexRead::with_source(Arc::clone(&index.tree), Arc::clone(data));
238 let mut actual = 0u64;
239 if let Err(error) = handle.try_for_each(|_, _| {
240 actual += 1;
241 Ok(())
242 }) {
243 return Ok(Some(format!("index inventory failed: {error}")));
244 }
245 Ok((actual != expected)
246 .then(|| format!("posting count mismatch: expected {expected}, found {actual}")))
247 }
248
249 pub fn register_secondary_index(
253 &self,
254 collection: &str,
255 name: &str,
256 identity: SecondaryIndexIdentity,
257 projector: Arc<dyn SecondaryIndexProjector>,
258 ) -> Result<(), StoreError> {
259 self.register_secondary_index_as(collection, name, identity, projector, false)
260 }
261
262 pub fn register_optional_secondary_index(
265 &self,
266 collection: &str,
267 name: &str,
268 identity: SecondaryIndexIdentity,
269 projector: Arc<dyn SecondaryIndexProjector>,
270 ) -> Result<(), StoreError> {
271 self.register_secondary_index_as(collection, name, identity, projector, true)
272 }
273
274 fn register_secondary_index_as(
275 &self,
276 collection: &str,
277 name: &str,
278 identity: SecondaryIndexIdentity,
279 projector: Arc<dyn SecondaryIndexProjector>,
280 optional: bool,
281 ) -> Result<(), StoreError> {
282 let collection = Self::canonical_collection(collection);
283 if name.is_empty() || name.len() > 1024 || identity.codec_version == 0 {
284 return Err(StoreError::Serialization(
285 "invalid secondary index identity".into(),
286 ));
287 }
288 let _publication = self.vault_publication_lock.lock();
289 if self.config.resident_memory_bytes_max.is_none()
290 || (self.commit.is_none() && !self.is_read_only())
291 {
292 return Err(StoreError::Serialization(
293 "secondary trees require disk residency and durable page ownership".into(),
294 ));
295 }
296 if !self.resident.collections.read().contains_key(collection) {
297 return Err(StoreError::CollectionNotFound(collection.into()));
298 }
299 let mut specs = self.secondary_index_specs.write();
300 let indices = specs.entry(collection.to_owned()).or_default();
301 if !indices.contains_key(name) && indices.len() >= 4096 {
302 return Err(StoreError::Serialization(
303 "too many secondary indexes".into(),
304 ));
305 }
306 indices.insert(
307 name.to_owned(),
308 SecondaryIndexSpec {
309 identity,
310 projector,
311 deferred: false,
312 optional,
313 },
314 );
315 Ok(())
316 }
317
318 pub(crate) fn checkpoint_missing_secondary_indices(&self) -> Result<(), StoreError> {
327 let missing = {
328 let _publication = self.vault_publication_lock.lock();
329 let specs = self.secondary_index_specs.read();
330 specs.iter().any(|(collection, indices)| {
331 indices.iter().any(|(name, spec)| {
332 !spec.deferred
333 && !spec.optional
334 && self
335 .secondary_index(collection, name, &spec.identity)
336 .is_none()
337 })
338 })
339 };
340 if missing {
341 self.persist()?;
342 }
343 Ok(())
344 }
345
346 pub fn secondary_index(
350 &self,
351 collection: &str,
352 name: &str,
353 identity: &SecondaryIndexIdentity,
354 ) -> Option<SecondaryIndexRead> {
355 let collection = Self::canonical_collection(collection);
356 let _publication = self.vault_publication_lock.lock();
357 let trees = self.btree_indices.read();
358 let data = trees.get(collection)?;
359 let keys = self.key_indices.read();
360 let generation = keys.get(collection)?;
361 if !generation.source.ptr_eq(&Arc::downgrade(data)) {
362 return None;
363 }
364 let index = generation.secondary.get(name)?;
365 (index.identity == *identity)
366 .then(|| SecondaryIndexRead::with_source(Arc::clone(&index.tree), Arc::clone(data)))
367 }
368
369 pub fn unregister_secondary_index(&self, collection: &str, name: &str) {
372 let collection = Self::canonical_collection(collection);
373 let _publication = self.vault_publication_lock.lock();
374 if let Some(specs) = self.secondary_index_specs.write().get_mut(collection) {
375 specs.remove(name);
376 }
377 if let Some(index) = self
378 .key_indices
379 .write()
380 .get_mut(collection)
381 .and_then(|generation| generation.secondary.remove(name))
382 {
383 self.retire_btree(index.tree);
384 self.resident
385 .paged_registry_dirty
386 .store(true, Ordering::Release);
387 }
388 }
389
390 pub(super) fn checkpoint_secondary_indices(
391 &self,
392 collection: &str,
393 data: &Arc<BTree>,
394 previous: Option<&PublishedKeyIndex>,
395 pager: &Arc<Pager>,
396 limit_bytes: usize,
397 ) -> Result<BTreeMap<String, PublishedSecondaryIndex>, StoreError> {
398 use reddb_engine::storage::collection_read::{CollectionCursor, PagedCollection};
399 let same_generation = previous.filter(|index| index.source.ptr_eq(&Arc::downgrade(data)));
400 let mut next = same_generation
401 .map(|index| index.secondary.clone())
402 .unwrap_or_default();
403 let specs = self.secondary_index_specs.read();
404 let Some(specs) = specs.get(collection) else {
405 return Ok(next);
406 };
407 let mut builds = Vec::new();
408 for (name, spec) in specs {
409 if next
410 .get(name)
411 .is_some_and(|index| index.identity == spec.identity)
412 {
413 continue;
414 }
415 if spec.deferred {
416 continue;
417 }
418 if name == super::count_index::NAME {
419 if let Some(tree) = self.checkpoint_count_projection_seed(
420 collection,
421 data.root_page_id(),
422 &spec.identity,
423 pager,
424 )? {
425 next.insert(
426 name.clone(),
427 PublishedSecondaryIndex {
428 identity: spec.identity.clone(),
429 tree,
430 },
431 );
432 continue;
433 }
434 }
435 builds.push((name, spec, Self::new_derived_btree(pager)?));
436 }
437 if builds.is_empty() {
438 return Ok(next);
439 }
440 let source = PagedCollection::new(Arc::clone(data));
441 let mut cursor = source.scan()?;
442 let mut key = [0; SECONDARY_KEY_BYTES_MAX];
443 while let Some(record) = cursor.next_record(limit_bytes)? {
444 let (entity, _) = record.decode_with_budget(self.format_version(), limit_bytes)?;
445 #[cfg(test)]
446 if checkpoint_skips_secondary_index_entity(collection, entity.id.raw()) {
447 continue;
448 }
449 for (_, spec, tree) in &builds {
450 let Some(length) = spec.projector.project(&entity, &mut key)? else {
451 continue;
452 };
453 if length > key.len() {
454 return Err(StoreError::Serialization(
455 "secondary key exceeds its bounded buffer".into(),
456 ));
457 }
458 let mut posting = [0; SECONDARY_KEY_BYTES_MAX + 8];
459 posting[..length].copy_from_slice(&key[..length]);
460 posting[length..length + 8].copy_from_slice(&entity.id.raw().to_be_bytes());
461 tree.insert(&posting[..length + 8], &[])
462 .map_err(|error| StoreError::Io(std::io::Error::other(error.to_string())))?;
463 }
464 }
465 for (name, spec, tree) in builds {
466 next.insert(
467 name.clone(),
468 PublishedSecondaryIndex {
469 identity: spec.identity.clone(),
470 tree,
471 },
472 );
473 }
474 Ok(next)
475 }
476}
477
478#[cfg(test)]
479mod tests;