1use 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 && same_generation.is_some() {
465 continue;
466 }
467 if name == super::count_index::NAME {
468 if let Some(tree) = self.checkpoint_count_projection_seed(
469 collection,
470 data.root_page_id(),
471 &spec.identity,
472 pager,
473 )? {
474 next.insert(
475 name.clone(),
476 PublishedSecondaryIndex {
477 identity: spec.identity.clone(),
478 tree,
479 },
480 );
481 continue;
482 }
483 }
484 builds.push((name, spec, Self::new_derived_btree(pager)?));
485 }
486 if builds.is_empty() {
487 return Ok(next);
488 }
489 let source = PagedCollection::new(Arc::clone(data));
490 let mut cursor = source.scan()?;
491 let mut key = [0; SECONDARY_KEY_BYTES_MAX];
492 let run_bytes = (limit_bytes / 8).min(POSTING_RUNS_BYTES_MAX) / builds.len();
493 let mut runs: Vec<PostingRun> = builds.iter().map(|_| PostingRun::default()).collect();
494 while let Some(record) = cursor.next_record(limit_bytes)? {
495 let (entity, _) = record.decode_with_budget(self.format_version(), limit_bytes)?;
496 #[cfg(test)]
497 if checkpoint_skips_secondary_index_entity(collection, entity.id.raw()) {
498 continue;
499 }
500 for ((_, spec, tree), run) in builds.iter().zip(&mut runs) {
501 let Some(length) = spec.projector.project(&entity, &mut key)? else {
502 continue;
503 };
504 if length > key.len() {
505 return Err(StoreError::Serialization(
506 "secondary key exceeds its bounded buffer".into(),
507 ));
508 }
509 let mut posting = [0; SECONDARY_KEY_BYTES_MAX + 8];
510 posting[..length].copy_from_slice(&key[..length]);
511 posting[length..length + 8].copy_from_slice(&entity.id.raw().to_be_bytes());
512 run.push(&posting[..length + 8]);
513 if run.bytes() >= run_bytes {
514 run.load(tree)?;
515 }
516 }
517 }
518 for ((_, _, tree), run) in builds.iter().zip(&mut runs) {
519 run.load(tree)?;
520 }
521 for (name, spec, tree) in builds {
522 next.insert(
523 name.clone(),
524 PublishedSecondaryIndex {
525 identity: spec.identity.clone(),
526 tree,
527 },
528 );
529 }
530 Ok(next)
531 }
532}
533
534pub(super) const POSTING_RUNS_BYTES_MAX: usize = 64 * 1024 * 1024;
536
537#[derive(Default)]
545pub(super) struct PostingRun {
546 bytes: Vec<u8>,
547 spans: Vec<(u32, u16)>,
548 loaded: bool,
549}
550
551impl PostingRun {
552 pub(super) fn push(&mut self, posting: &[u8]) {
553 self.spans
554 .push((self.bytes.len() as u32, posting.len() as u16));
555 self.bytes.extend_from_slice(posting);
556 }
557
558 pub(super) fn bytes(&self) -> usize {
559 self.bytes.len() + self.spans.len() * std::mem::size_of::<(u32, u16)>()
560 }
561
562 pub(super) fn load(&mut self, tree: &BTree) -> Result<(), StoreError> {
563 let failed = |error: reddb_engine::storage::btree::BTreeError| {
564 StoreError::Io(std::io::Error::other(error.to_string()))
565 };
566 let bytes = &self.bytes;
567 let posting = |&(start, length): &(u32, u16)| {
568 &bytes[start as usize..start as usize + usize::from(length)]
569 };
570 self.spans
571 .sort_unstable_by(|a, b| posting(a).cmp(posting(b)));
572 if self.loaded {
573 for span in &self.spans {
574 tree.insert(posting(span), &[]).map_err(failed)?;
575 }
576 } else {
577 for chunk in self.spans.chunks(4096) {
578 let items: Vec<_> = chunk
579 .iter()
580 .map(|span| (posting(span).to_vec(), Vec::new()))
581 .collect();
582 tree.bulk_insert_sorted(&items).map_err(failed)?;
583 }
584 }
585 self.loaded |= !self.spans.is_empty();
586 self.spans.clear();
587 self.bytes.clear();
588 Ok(())
589 }
590}
591
592#[cfg(test)]
593mod tests;