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        if name.is_empty() || name.len() > 1024 || identity.codec_version == 0 {
75            return Err(StoreError::Serialization(
76                "invalid secondary index identity".into(),
77            ));
78        }
79        let _publication = self.vault_publication_lock.lock();
80        if self.config.resident_memory_bytes_max.is_none() || self.commit.is_none() {
81            return Err(StoreError::Serialization(
82                "secondary trees require disk residency and durable page ownership".into(),
83            ));
84        }
85        if !self.resident.collections.read().contains_key(collection) {
86            return Err(StoreError::CollectionNotFound(collection.into()));
87        }
88        let mut specs = self.secondary_index_specs.write();
89        let indices = specs.entry(collection.to_owned()).or_default();
90        if !indices.contains_key(name) && indices.len() >= 4096 {
91            return Err(StoreError::Serialization(
92                "too many secondary indexes".into(),
93            ));
94        }
95        indices.insert(
96            name.to_owned(),
97            SecondaryIndexSpec {
98                identity,
99                projector,
100            },
101        );
102        Ok(())
103    }
104
105    /// Preparation is a full ownership/checkpoint epoch, not merely a catalog
106    /// flush. Reopened compatible roots need no source scan or publication.
107    pub(crate) fn checkpoint_missing_secondary_indices(&self) -> Result<(), StoreError> {
108        let missing = {
109            let _publication = self.vault_publication_lock.lock();
110            let specs = self.secondary_index_specs.read();
111            specs.iter().any(|(collection, indices)| {
112                indices.iter().any(|(name, spec)| {
113                    self.secondary_index(collection, name, &spec.identity)
114                        .is_none()
115                })
116            })
117        };
118        if missing {
119            self.persist()?;
120        }
121        Ok(())
122    }
123
124    /// Pin an immutable index only if both the data generation and definition
125    /// still match. A miss requires rebuilding or a correct scan fallback.
126    /// This is a physical base index: callers must merge the live WAL overlay.
127    pub fn secondary_index(
128        &self,
129        collection: &str,
130        name: &str,
131        identity: &SecondaryIndexIdentity,
132    ) -> Option<SecondaryIndexRead> {
133        let _publication = self.vault_publication_lock.lock();
134        let trees = self.btree_indices.read();
135        let data = trees.get(collection)?;
136        let keys = self.key_indices.read();
137        let generation = keys.get(collection)?;
138        if !generation.source.ptr_eq(&Arc::downgrade(data)) {
139            return None;
140        }
141        let index = generation.secondary.get(name)?;
142        (index.identity == *identity)
143            .then(|| SecondaryIndexRead::with_source(Arc::clone(&index.tree), Arc::clone(data)))
144    }
145
146    /// The next checkpoint publishes the removal. Already-pinned readers keep
147    /// their old immutable tree until the normal retirement protocol releases it.
148    pub fn unregister_secondary_index(&self, collection: &str, name: &str) {
149        let _publication = self.vault_publication_lock.lock();
150        if let Some(specs) = self.secondary_index_specs.write().get_mut(collection) {
151            specs.remove(name);
152        }
153        if let Some(index) = self
154            .key_indices
155            .write()
156            .get_mut(collection)
157            .and_then(|generation| generation.secondary.remove(name))
158        {
159            self.retire_btree(index.tree);
160            self.resident
161                .paged_registry_dirty
162                .store(true, Ordering::Release);
163        }
164    }
165
166    pub(super) fn checkpoint_secondary_indices(
167        &self,
168        collection: &str,
169        data: &Arc<BTree>,
170        previous: Option<&PublishedKeyIndex>,
171        pager: &Arc<Pager>,
172        limit_bytes: usize,
173    ) -> Result<BTreeMap<String, PublishedSecondaryIndex>, StoreError> {
174        use reddb_engine::storage::collection_read::{CollectionCursor, PagedCollection};
175        let same_generation = previous.filter(|index| index.source.ptr_eq(&Arc::downgrade(data)));
176        let mut next = same_generation
177            .map(|index| index.secondary.clone())
178            .unwrap_or_default();
179        let specs = self.secondary_index_specs.read();
180        let Some(specs) = specs.get(collection) else {
181            return Ok(next);
182        };
183        let mut builds = Vec::new();
184        for (name, spec) in specs {
185            if next
186                .get(name)
187                .is_some_and(|index| index.identity == spec.identity)
188            {
189                continue;
190            }
191            builds.push((name, spec, Arc::new(BTree::new(Arc::clone(pager)))));
192        }
193        if builds.is_empty() {
194            return Ok(next);
195        }
196        let source = PagedCollection::new(Arc::clone(data));
197        let mut cursor = source.scan()?;
198        let mut key = [0; SECONDARY_KEY_BYTES_MAX];
199        while let Some(record) = cursor.next_record(limit_bytes)? {
200            let (entity, _) = record.decode_with_budget(self.format_version(), limit_bytes)?;
201            for (_, spec, tree) in &builds {
202                let Some(length) = spec.projector.project(&entity, &mut key)? else {
203                    continue;
204                };
205                if length > key.len() {
206                    return Err(StoreError::Serialization(
207                        "secondary key exceeds its bounded buffer".into(),
208                    ));
209                }
210                let mut posting = [0; SECONDARY_KEY_BYTES_MAX + 8];
211                posting[..length].copy_from_slice(&key[..length]);
212                posting[length..length + 8].copy_from_slice(&entity.id.raw().to_be_bytes());
213                tree.insert(&posting[..length + 8], &[])
214                    .map_err(|error| StoreError::Io(std::io::Error::other(error.to_string())))?;
215            }
216        }
217        for (name, spec, tree) in builds {
218            next.insert(
219                name.clone(),
220                PublishedSecondaryIndex {
221                    identity: spec.identity.clone(),
222                    tree,
223                },
224            );
225        }
226        Ok(next)
227    }
228}
229
230#[cfg(test)]
231mod tests;