Skip to main content

reddb_server/storage/unified/store/
secondary_index.rs

1//! Generation-bound secondary trees, built inside the existing checkpoint epoch.
2//!
3//! Resource sketch: conversion reads N source rows once per collection, writes
4//! O(N * indexes) compact postings, and holds one decoded row plus one 1 KiB key.
5//! Reopen loads only root handles (O(indexes)); queries use the shared page cache.
6//! No network I/O or per-index resident posting map is introduced here.
7use super::*;
8use reddb_file::native_resume::SecondaryIndexResume;
9
10/// Leave eight bytes for the physical entity identity in each B-tree key.
11pub use reddb_engine::storage::secondary_index_read::SECONDARY_KEY_BYTES_MAX;
12pub type SecondaryIndexRead =
13    reddb_engine::storage::secondary_index_read::SecondaryIndexRead<Pager>;
14
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct SecondaryIndexIdentity {
17    pub codec_version: u32,
18    pub definition: [u8; 32],
19}
20
21/// The projector is immutable, deterministic and must not re-enter storage.
22/// It writes a canonical key into the supplied bounded scratch buffer. The
23/// store appends the physical identity, retaining all MVCC versions. Visibility
24/// and logical uniqueness remain the query/transaction layer's responsibility.
25pub trait SecondaryIndexProjector: Send + Sync {
26    fn project(
27        &self,
28        entity: &UnifiedEntity,
29        key: &mut [u8; SECONDARY_KEY_BYTES_MAX],
30    ) -> Result<Option<usize>, StoreError>;
31}
32
33#[derive(Clone)]
34pub(super) struct SecondaryIndexSpec {
35    pub(super) identity: SecondaryIndexIdentity,
36    pub(super) projector: Arc<dyn SecondaryIndexProjector>,
37}
38
39pub(super) type SecondaryIndexSpecs = HashMap<String, BTreeMap<String, SecondaryIndexSpec>>;
40
41#[derive(Clone)]
42pub(super) struct PublishedSecondaryIndex {
43    pub identity: SecondaryIndexIdentity,
44    pub tree: Arc<BTree>,
45}
46
47impl PublishedSecondaryIndex {
48    pub(super) fn resume(&self) -> SecondaryIndexResume {
49        SecondaryIndexResume {
50            root_page: self.tree.root_page_id(),
51            codec_version: self.identity.codec_version,
52            definition: self.identity.definition,
53        }
54    }
55}
56
57impl PublishedKeyIndex {
58    pub(super) fn trees(&self) -> impl Iterator<Item = &Arc<BTree>> {
59        std::iter::once(&self.tree).chain(self.secondary.values().map(|index| &index.tree))
60    }
61}
62
63impl UnifiedStore {
64    /// Register a projection for subsequent checkpoints. The definition must
65    /// include method, ordered columns, uniqueness and any collation options.
66    /// A changed fingerprint is never allowed to reuse the previous tree.
67    pub fn register_secondary_index(
68        &self,
69        collection: &str,
70        name: &str,
71        identity: SecondaryIndexIdentity,
72        projector: Arc<dyn SecondaryIndexProjector>,
73    ) -> Result<(), StoreError> {
74        let collection = Self::canonical_collection(collection);
75        if name.is_empty() || name.len() > 1024 || identity.codec_version == 0 {
76            return Err(StoreError::Serialization(
77                "invalid secondary index identity".into(),
78            ));
79        }
80        let _publication = self.vault_publication_lock.lock();
81        if self.config.resident_memory_bytes_max.is_none()
82            || (self.commit.is_none() && !self.is_read_only())
83        {
84            return Err(StoreError::Serialization(
85                "secondary trees require disk residency and durable page ownership".into(),
86            ));
87        }
88        if !self.resident.collections.read().contains_key(collection) {
89            return Err(StoreError::CollectionNotFound(collection.into()));
90        }
91        let mut specs = self.secondary_index_specs.write();
92        let indices = specs.entry(collection.to_owned()).or_default();
93        if !indices.contains_key(name) && indices.len() >= 4096 {
94            return Err(StoreError::Serialization(
95                "too many secondary indexes".into(),
96            ));
97        }
98        indices.insert(
99            name.to_owned(),
100            SecondaryIndexSpec {
101                identity,
102                projector,
103            },
104        );
105        Ok(())
106    }
107
108    /// Preparation is a full ownership/checkpoint epoch, not merely a catalog
109    /// flush. Reopened compatible roots need no source scan or publication.
110    pub(crate) fn checkpoint_missing_secondary_indices(&self) -> Result<(), StoreError> {
111        let missing = {
112            let _publication = self.vault_publication_lock.lock();
113            let specs = self.secondary_index_specs.read();
114            specs.iter().any(|(collection, indices)| {
115                indices.iter().any(|(name, spec)| {
116                    self.secondary_index(collection, name, &spec.identity)
117                        .is_none()
118                })
119            })
120        };
121        if missing {
122            self.persist()?;
123        }
124        Ok(())
125    }
126
127    /// Pin an immutable index only if both the data generation and definition
128    /// still match. A miss requires rebuilding or a correct scan fallback.
129    /// This is a physical base index: callers must merge the live WAL overlay.
130    pub fn secondary_index(
131        &self,
132        collection: &str,
133        name: &str,
134        identity: &SecondaryIndexIdentity,
135    ) -> Option<SecondaryIndexRead> {
136        let collection = Self::canonical_collection(collection);
137        let _publication = self.vault_publication_lock.lock();
138        let trees = self.btree_indices.read();
139        let data = trees.get(collection)?;
140        let keys = self.key_indices.read();
141        let generation = keys.get(collection)?;
142        if !generation.source.ptr_eq(&Arc::downgrade(data)) {
143            return None;
144        }
145        let index = generation.secondary.get(name)?;
146        (index.identity == *identity)
147            .then(|| SecondaryIndexRead::with_source(Arc::clone(&index.tree), Arc::clone(data)))
148    }
149
150    /// The next checkpoint publishes the removal. Already-pinned readers keep
151    /// their old immutable tree until the normal retirement protocol releases it.
152    pub fn unregister_secondary_index(&self, collection: &str, name: &str) {
153        let collection = Self::canonical_collection(collection);
154        let _publication = self.vault_publication_lock.lock();
155        if let Some(specs) = self.secondary_index_specs.write().get_mut(collection) {
156            specs.remove(name);
157        }
158        if let Some(index) = self
159            .key_indices
160            .write()
161            .get_mut(collection)
162            .and_then(|generation| generation.secondary.remove(name))
163        {
164            self.retire_btree(index.tree);
165            self.resident
166                .paged_registry_dirty
167                .store(true, Ordering::Release);
168        }
169    }
170
171    pub(super) fn checkpoint_secondary_indices(
172        &self,
173        collection: &str,
174        data: &Arc<BTree>,
175        previous: Option<&PublishedKeyIndex>,
176        pager: &Arc<Pager>,
177        limit_bytes: usize,
178    ) -> Result<BTreeMap<String, PublishedSecondaryIndex>, StoreError> {
179        use reddb_engine::storage::collection_read::{CollectionCursor, PagedCollection};
180        let same_generation = previous.filter(|index| index.source.ptr_eq(&Arc::downgrade(data)));
181        let mut next = same_generation
182            .map(|index| index.secondary.clone())
183            .unwrap_or_default();
184        let specs = self.secondary_index_specs.read();
185        let Some(specs) = specs.get(collection) else {
186            return Ok(next);
187        };
188        let mut builds = Vec::new();
189        for (name, spec) in specs {
190            if next
191                .get(name)
192                .is_some_and(|index| index.identity == spec.identity)
193            {
194                continue;
195            }
196            builds.push((name, spec, Arc::new(BTree::new(Arc::clone(pager)))));
197        }
198        if builds.is_empty() {
199            return Ok(next);
200        }
201        let source = PagedCollection::new(Arc::clone(data));
202        let mut cursor = source.scan()?;
203        let mut key = [0; SECONDARY_KEY_BYTES_MAX];
204        while let Some(record) = cursor.next_record(limit_bytes)? {
205            let (entity, _) = record.decode_with_budget(self.format_version(), limit_bytes)?;
206            for (_, spec, tree) in &builds {
207                let Some(length) = spec.projector.project(&entity, &mut key)? else {
208                    continue;
209                };
210                if length > key.len() {
211                    return Err(StoreError::Serialization(
212                        "secondary key exceeds its bounded buffer".into(),
213                    ));
214                }
215                let mut posting = [0; SECONDARY_KEY_BYTES_MAX + 8];
216                posting[..length].copy_from_slice(&key[..length]);
217                posting[length..length + 8].copy_from_slice(&entity.id.raw().to_be_bytes());
218                tree.insert(&posting[..length + 8], &[])
219                    .map_err(|error| StoreError::Io(std::io::Error::other(error.to_string())))?;
220            }
221        }
222        for (name, spec, tree) in builds {
223            next.insert(
224                name.clone(),
225                PublishedSecondaryIndex {
226                    identity: spec.identity.clone(),
227                    tree,
228                },
229            );
230        }
231        Ok(next)
232    }
233}
234
235#[cfg(test)]
236mod tests;