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
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
98/// The projector is immutable, deterministic and must not re-enter storage.
99/// It writes a canonical key into the supplied bounded scratch buffer. The
100/// store appends the physical identity. Current secondary indexes omit retired
101/// MVCC versions; historical reads use the query layer's authoritative fallback.
102pub 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    /// Identities under which the same index was published before columns
114    /// were appended to the collection's schema. Every row has the same key
115    /// under them as under `identity`, so such a tree answers reads until the
116    /// next checkpoint publishes this index under `identity`.
117    pub(super) predecessors: Vec<SecondaryIndexIdentity>,
118    pub(super) projector: Arc<dyn SecondaryIndexProjector>,
119    pub(super) deferred: bool,
120    /// Reads answer without it, by walking the collection. Its tree is built
121    /// by whichever checkpoint comes next, never by one taken for its sake
122    /// while the store is being opened.
123    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    /// Check a registered index against its immutable checkpoint source. This
183    /// is an operator pass: O(rows * log(postings)), one bounded row at a time.
184    /// Source read failures propagate; only derived-tree failures are findings.
185    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    /// Register a projection for subsequent checkpoints. The definition must
255    /// include method, ordered columns, uniqueness and any collation options.
256    /// A changed fingerprint is never allowed to reuse the previous tree.
257    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    /// As [`Self::register_secondary_index`], for an index whose identity
268    /// moved because columns were appended to the collection's schema: a
269    /// tree published under one of `predecessors` holds the same key for
270    /// every row.
271    pub(super) fn register_secondary_index_after(
272        &self,
273        collection: &str,
274        name: &str,
275        identity: SecondaryIndexIdentity,
276        predecessors: Vec<SecondaryIndexIdentity>,
277        projector: Arc<dyn SecondaryIndexProjector>,
278    ) -> Result<(), StoreError> {
279        self.register_secondary_index_as(collection, name, identity, predecessors, projector, false)
280    }
281
282    /// Register an index that statements can do without: one a user declared.
283    /// A missing tree for it does not hold up opening the store.
284    pub fn register_optional_secondary_index(
285        &self,
286        collection: &str,
287        name: &str,
288        identity: SecondaryIndexIdentity,
289        projector: Arc<dyn SecondaryIndexProjector>,
290    ) -> Result<(), StoreError> {
291        self.register_secondary_index_as(collection, name, identity, Vec::new(), projector, true)
292    }
293
294    /// As [`Self::register_optional_secondary_index`], for an index whose
295    /// identity moved because columns were appended to the collection's
296    /// schema. A tree published under one of `predecessors` holds the same
297    /// key for every row and keeps answering reads; without this, declaring a
298    /// column leaves every index of the collection unread after the next
299    /// restart until a checkpoint completes.
300    pub fn register_optional_secondary_index_after(
301        &self,
302        collection: &str,
303        name: &str,
304        identity: SecondaryIndexIdentity,
305        predecessors: Vec<SecondaryIndexIdentity>,
306        projector: Arc<dyn SecondaryIndexProjector>,
307    ) -> Result<(), StoreError> {
308        self.register_secondary_index_as(collection, name, identity, predecessors, projector, true)
309    }
310
311    fn register_secondary_index_as(
312        &self,
313        collection: &str,
314        name: &str,
315        identity: SecondaryIndexIdentity,
316        predecessors: Vec<SecondaryIndexIdentity>,
317        projector: Arc<dyn SecondaryIndexProjector>,
318        optional: bool,
319    ) -> Result<(), StoreError> {
320        let collection = Self::canonical_collection(collection);
321        if name.is_empty() || name.len() > 1024 || identity.codec_version == 0 {
322            return Err(StoreError::Serialization(
323                "invalid secondary index identity".into(),
324            ));
325        }
326        let _publication = self.vault_publication_lock.lock();
327        if self.config.resident_memory_bytes_max.is_none()
328            || (self.commit.is_none() && !self.is_read_only())
329        {
330            return Err(StoreError::Serialization(
331                "secondary trees require disk residency and durable page ownership".into(),
332            ));
333        }
334        if !self.resident.collections.read().contains_key(collection) {
335            return Err(StoreError::CollectionNotFound(collection.into()));
336        }
337        let mut specs = self.secondary_index_specs.write();
338        let indices = specs.entry(collection.to_owned()).or_default();
339        if !indices.contains_key(name) && indices.len() >= 4096 {
340            return Err(StoreError::Serialization(
341                "too many secondary indexes".into(),
342            ));
343        }
344        indices.insert(
345            name.to_owned(),
346            SecondaryIndexSpec {
347                identity,
348                predecessors,
349                projector,
350                deferred: false,
351                optional,
352            },
353        );
354        Ok(())
355    }
356
357    /// Opening the store waits for this only on behalf of projections the
358    /// runtime cannot read without. A checkpoint here covers everything the
359    /// WAL replayed, which on a large store is many minutes during which the
360    /// server answers nothing, not even its health probes; an index a user
361    /// declared is not worth that, and the next checkpoint builds it anyway.
362    ///
363    /// Preparation is a full ownership/checkpoint epoch, not merely a catalog
364    /// flush. Reopened compatible roots need no source scan or publication.
365    pub(crate) fn checkpoint_missing_secondary_indices(&self) -> Result<(), StoreError> {
366        let missing = {
367            let _publication = self.vault_publication_lock.lock();
368            let specs = self.secondary_index_specs.read();
369            specs.iter().any(|(collection, indices)| {
370                indices.iter().any(|(name, spec)| {
371                    !spec.deferred
372                        && !spec.optional
373                        && self
374                            .secondary_index(collection, name, &spec.identity)
375                            .is_none()
376                })
377            })
378        };
379        if missing {
380            self.persist()?;
381        }
382        Ok(())
383    }
384
385    /// Pin an immutable index only if both the data generation and definition
386    /// still match, or the tree was published under a definition this one
387    /// declares as a predecessor. A miss requires rebuilding or a correct scan
388    /// fallback.
389    /// This is a physical base index: callers must merge the live WAL overlay.
390    pub fn secondary_index(
391        &self,
392        collection: &str,
393        name: &str,
394        identity: &SecondaryIndexIdentity,
395    ) -> Option<SecondaryIndexRead> {
396        let collection = Self::canonical_collection(collection);
397        let _publication = self.vault_publication_lock.lock();
398        let (published, tree, data) = {
399            let trees = self.btree_indices.read();
400            let data = trees.get(collection)?;
401            let keys = self.key_indices.read();
402            let generation = keys.get(collection)?;
403            if !generation.source.ptr_eq(&Arc::downgrade(data)) {
404                return None;
405            }
406            let index = generation.secondary.get(name)?;
407            (
408                index.identity.clone(),
409                Arc::clone(&index.tree),
410                Arc::clone(data),
411            )
412        };
413        // The publication lock keeps the registration and the published
414        // generation consistent. The spec table is read on its own, so this
415        // path adds no ordering between it and the generation locks.
416        let readable = published == *identity
417            || self
418                .secondary_index_specs
419                .read()
420                .get(collection)
421                .and_then(|indices| indices.get(name))
422                .is_some_and(|spec| {
423                    spec.identity == *identity && spec.predecessors.contains(&published)
424                });
425        readable.then(|| SecondaryIndexRead::with_source(tree, data))
426    }
427
428    /// The next checkpoint publishes the removal. Already-pinned readers keep
429    /// their old immutable tree until the normal retirement protocol releases it.
430    pub fn unregister_secondary_index(&self, collection: &str, name: &str) {
431        let collection = Self::canonical_collection(collection);
432        let _publication = self.vault_publication_lock.lock();
433        if let Some(specs) = self.secondary_index_specs.write().get_mut(collection) {
434            specs.remove(name);
435        }
436        if let Some(index) = self
437            .key_indices
438            .write()
439            .get_mut(collection)
440            .and_then(|generation| generation.secondary.remove(name))
441        {
442            self.retire_btree(index.tree);
443            self.resident
444                .paged_registry_dirty
445                .store(true, Ordering::Release);
446        }
447    }
448
449    pub(super) fn checkpoint_secondary_indices(
450        &self,
451        collection: &str,
452        data: &Arc<BTree>,
453        previous: Option<&PublishedKeyIndex>,
454        pager: &Arc<Pager>,
455        limit_bytes: usize,
456    ) -> Result<BTreeMap<String, PublishedSecondaryIndex>, StoreError> {
457        use reddb_engine::storage::collection_read::{CollectionCursor, PagedCollection};
458        let same_generation = previous.filter(|index| index.source.ptr_eq(&Arc::downgrade(data)));
459        let mut next = same_generation
460            .map(|index| index.secondary.clone())
461            .unwrap_or_default();
462        let specs = self.secondary_index_specs.read();
463        let Some(specs) = specs.get(collection) else {
464            return Ok(next);
465        };
466        let mut builds = Vec::new();
467        for (name, spec) in specs {
468            if next
469                .get(name)
470                .is_some_and(|index| index.identity == spec.identity)
471            {
472                continue;
473            }
474            // The background worker builds a deferred projection over the
475            // generation it was declared on. A republished collection is a new
476            // generation: that build has just lost its source, and leaving the
477            // projection out would republish the collection at every
478            // checkpoint that comes before a new build ends.
479            if spec.deferred && same_generation.is_some() {
480                continue;
481            }
482            if name == super::count_index::NAME {
483                if let Some(tree) = self.checkpoint_count_projection_seed(
484                    collection,
485                    data.root_page_id(),
486                    &spec.identity,
487                    pager,
488                )? {
489                    next.insert(
490                        name.clone(),
491                        PublishedSecondaryIndex {
492                            identity: spec.identity.clone(),
493                            tree,
494                        },
495                    );
496                    continue;
497                }
498            }
499            builds.push((name, spec, Self::new_derived_btree(pager)?));
500        }
501        if builds.is_empty() {
502            return Ok(next);
503        }
504        let source = PagedCollection::new(Arc::clone(data));
505        let mut cursor = source.scan()?;
506        let mut key = [0; SECONDARY_KEY_BYTES_MAX];
507        let run_bytes = (limit_bytes / 8).min(POSTING_RUNS_BYTES_MAX) / builds.len();
508        let mut runs: Vec<PostingRun> = builds.iter().map(|_| PostingRun::default()).collect();
509        while let Some(record) = cursor.next_record(limit_bytes)? {
510            let (entity, _) = record.decode_with_budget(self.format_version(), limit_bytes)?;
511            #[cfg(test)]
512            if checkpoint_skips_secondary_index_entity(collection, entity.id.raw()) {
513                continue;
514            }
515            for ((_, spec, _), run) in builds.iter().zip(&mut runs) {
516                let Some(length) = spec.projector.project(&entity, &mut key)? else {
517                    continue;
518                };
519                if length > key.len() {
520                    return Err(StoreError::Serialization(
521                        "secondary key exceeds its bounded buffer".into(),
522                    ));
523                }
524                let mut posting = [0; SECONDARY_KEY_BYTES_MAX + 8];
525                posting[..length].copy_from_slice(&key[..length]);
526                posting[length..length + 8].copy_from_slice(&entity.id.raw().to_be_bytes());
527                run.push(&posting[..length + 8]);
528                if run.bytes() >= run_bytes {
529                    run.spill(pager)?;
530                }
531            }
532        }
533        for ((_, _, tree), run) in builds.iter().zip(runs) {
534            run.finish(self, pager, tree)?;
535        }
536        for (name, spec, tree) in builds {
537            next.insert(
538                name.clone(),
539                PublishedSecondaryIndex {
540                    identity: spec.identity.clone(),
541                    tree,
542                },
543            );
544        }
545        Ok(next)
546    }
547}
548
549/// Postings buffered for every index a checkpoint rebuilds, in total.
550pub(super) const POSTING_RUNS_BYTES_MAX: usize = 64 * 1024 * 1024;
551
552/// Postings of one derived tree, collected in row order and loaded in key order.
553///
554/// A tree filled one posting at a time pays a root-to-leaf walk and a leaf
555/// rewrite per posting, each page proven on the way: about a millisecond per
556/// posting, which made the rebuild the cost of the checkpoint. Sorted, the
557/// same postings fill each leaf once.
558///
559/// A rebuild larger than one run sorts each run into a tree of its own and
560/// merges them at the end. It used to go back to one posting at a time for
561/// everything after the first run: past about 120,000 rows on a 256 MiB
562/// store, where copying a 172,800-row table rebuilt its indexes for 14
563/// seconds with every writer waiting.
564#[derive(Default)]
565pub(super) struct PostingRun {
566    bytes: Vec<u8>,
567    spans: Vec<(u32, u16)>,
568    spilled: Vec<Arc<BTree>>,
569}
570
571impl PostingRun {
572    pub(super) fn push(&mut self, posting: &[u8]) {
573        self.spans
574            .push((self.bytes.len() as u32, posting.len() as u16));
575        self.bytes.extend_from_slice(posting);
576    }
577
578    pub(super) fn bytes(&self) -> usize {
579        self.bytes.len() + self.spans.len() * std::mem::size_of::<(u32, u16)>()
580    }
581
582    /// Set the postings collected so far aside, sorted, in a tree of their own.
583    pub(super) fn spill(&mut self, pager: &Arc<Pager>) -> Result<(), StoreError> {
584        if self.spans.is_empty() {
585            return Ok(());
586        }
587        let tree = UnifiedStore::new_derived_btree(pager)?;
588        self.write_sorted(&tree)?;
589        self.spilled.push(tree);
590        #[cfg(test)]
591        POSTING_RUNS_SPILLED.with(|spilled| spilled.set(spilled.get() + 1));
592        Ok(())
593    }
594
595    /// Load every posting pushed into `tree`, which must be empty.
596    pub(super) fn finish(
597        mut self,
598        store: &UnifiedStore,
599        pager: &Arc<Pager>,
600        tree: &BTree,
601    ) -> Result<(), StoreError> {
602        if self.spilled.is_empty() {
603            return self.write_sorted(tree);
604        }
605        self.spill(pager)?;
606        let failed = |error: reddb_engine::storage::btree::BTreeError| {
607            StoreError::Io(std::io::Error::other(error.to_string()))
608        };
609        let mut cursors = Vec::with_capacity(self.spilled.len());
610        let mut heads = std::collections::BinaryHeap::with_capacity(self.spilled.len());
611        for (run, spilled) in self.spilled.iter().enumerate() {
612            let mut cursor = spilled.cursor_first_frozen().map_err(failed)?;
613            if let Some((posting, _)) = cursor.next().map_err(failed)? {
614                heads.push(std::cmp::Reverse((posting, run)));
615            }
616            cursors.push(cursor);
617        }
618        let mut batch = Vec::with_capacity(POSTING_BATCH);
619        while let Some(std::cmp::Reverse((posting, run))) = heads.pop() {
620            batch.push((posting, Vec::new()));
621            if batch.len() == POSTING_BATCH {
622                tree.bulk_insert_sorted(&batch).map_err(failed)?;
623                batch.clear();
624            }
625            if let Some((posting, _)) = cursors[run].next().map_err(failed)? {
626                heads.push(std::cmp::Reverse((posting, run)));
627            }
628        }
629        tree.bulk_insert_sorted(&batch).map_err(failed)?;
630        drop(cursors);
631        self.discard(store);
632        Ok(())
633    }
634
635    /// Give back the trees of a rebuild that is not going to be loaded.
636    pub(super) fn discard(self, store: &UnifiedStore) {
637        for spilled in self.spilled {
638            store.retire_btree(spilled);
639        }
640    }
641
642    fn write_sorted(&mut self, tree: &BTree) -> Result<(), StoreError> {
643        let failed = |error: reddb_engine::storage::btree::BTreeError| {
644            StoreError::Io(std::io::Error::other(error.to_string()))
645        };
646        let bytes = &self.bytes;
647        let posting = |&(start, length): &(u32, u16)| {
648            &bytes[start as usize..start as usize + usize::from(length)]
649        };
650        self.spans
651            .sort_unstable_by(|a, b| posting(a).cmp(posting(b)));
652        for chunk in self.spans.chunks(POSTING_BATCH) {
653            let items: Vec<_> = chunk
654                .iter()
655                .map(|span| (posting(span).to_vec(), Vec::new()))
656                .collect();
657            tree.bulk_insert_sorted(&items).map_err(failed)?;
658        }
659        self.spans.clear();
660        self.bytes.clear();
661        Ok(())
662    }
663}
664
665/// Postings handed to a tree in one sorted call.
666const POSTING_BATCH: usize = 4096;
667
668#[cfg(test)]
669thread_local! {
670    static POSTING_RUNS_SPILLED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
671}
672
673#[cfg(test)]
674mod tests;