Skip to main content

reddb_engine/storage/btree/
impl.rs

1use super::*;
2use crate::storage::overflow::OverflowChain;
3
4impl<P: PageStore> BTree<P> {
5    /// If `stored` is a pointer cell (slice E layout), walk the overflow
6    /// chain anchored at it and return every page to the free list.
7    /// No-op for inline cells (raw or compressed) and for empty cells.
8    ///
9    /// Used by the B-tree paths that drop or overwrite a pointer cell —
10    /// `delete` and the shrinking branches of `upsert` /
11    /// `upsert_batch_sorted` (slice F of PRD #662). At the B-tree layer
12    /// this is synchronous: a higher transactional layer that needs
13    /// MVCC-aware reclamation must defer freeing through its own
14    /// snapshot machinery rather than calling these primitives during a
15    /// rollback-capable window.
16    fn free_chain_if_pointer(&self, stored: &[u8]) -> BTreeResult<()> {
17        if let Some(head) = value_layout::pointer_head(stored) {
18            OverflowChain::new(self.pager.as_ref())
19                .free(head)
20                .map_err(value_layout::ValueLayoutError::from)?;
21        }
22        Ok(())
23    }
24    /// Create a new B+ tree using the given pager
25    pub fn new(pager: Arc<P>) -> Self {
26        Self {
27            retirement_pin: Arc::new(()),
28            pager: Arc::new(super::page_proofs::TreePageStore::legacy(pager)),
29            root_page_id: RwLock::new(0),
30            rightmost_leaf: RwLock::new(None),
31            writer: parking_lot::ReentrantMutex::new(()),
32        }
33    }
34
35    /// Create a B+ tree with an existing root
36    pub fn with_root(pager: Arc<P>, root_page_id: u32) -> Self {
37        Self {
38            retirement_pin: Arc::new(()),
39            pager: Arc::new(super::page_proofs::TreePageStore::legacy(pager)),
40            root_page_id: RwLock::new(root_page_id),
41            rightmost_leaf: RwLock::new(None),
42            writer: parking_lot::ReentrantMutex::new(()),
43        }
44    }
45
46    /// Get the root page ID
47    pub fn root_page_id(&self) -> u32 {
48        *self
49            .root_page_id
50            .read()
51            .unwrap_or_else(|poisoned| poisoned.into_inner())
52    }
53
54    /// Start an authenticated tree. Retired proof paths remain owned until
55    /// the host publishes its replacement catalog through the pager fence.
56    pub fn new_verified(pager: Arc<P>) -> BTreeResult<Self> {
57        Self::with_verified_root(pager, 0, reddb_file::page_proof::PageProofRoot::default())
58    }
59
60    pub fn has_page_proofs(&self) -> bool {
61        self.pager.has_page_proofs()
62    }
63
64    /// Restore independently sealed page-image authority without scanning data.
65    pub fn with_verified_root(
66        pager: Arc<P>,
67        root_page_id: u32,
68        proof: reddb_file::page_proof::PageProofRoot,
69    ) -> BTreeResult<Self> {
70        if root_page_id != 0 && proof.reference.page_id == 0 {
71            return Err(BTreeError::Corrupted(
72                "missing published page generation proof".into(),
73            ));
74        }
75        if root_page_id == 0 && proof.reference.page_id != 0 {
76            return Err(BTreeError::Corrupted(
77                "empty tree retains a published page generation proof".into(),
78            ));
79        }
80        Ok(Self {
81            retirement_pin: Arc::new(()),
82            pager: Arc::new(super::page_proofs::TreePageStore::verified(pager, proof)?),
83            root_page_id: RwLock::new(root_page_id),
84            rightmost_leaf: RwLock::new(None),
85            writer: parking_lot::ReentrantMutex::new(()),
86        })
87    }
88
89    /// The host must sync before publishing this pair in its catalog. Sealing
90    /// writes the proof entries the generation set, so it can allocate and
91    /// free proof pages: take page inventories after it, not before.
92    pub fn seal_page_proofs(
93        &self,
94    ) -> BTreeResult<Option<(u32, reddb_file::page_proof::PageProofRoot)>> {
95        let _writer = self.writer.lock();
96        Ok(self.pager.seal()?.map(|proof| (self.root_page_id(), proof)))
97    }
98
99    /// Check if tree is empty
100    pub fn is_empty(&self) -> bool {
101        self.root_page_id() == 0
102    }
103
104    /// Get value for a key
105    pub fn get(&self, key: &[u8]) -> BTreeResult<Option<Vec<u8>>> {
106        self.get_with_budget(key, usize::MAX)
107    }
108
109    /// Point lookups in ascending key order; see [`SortedProbe`].
110    pub fn sorted_probe(&self) -> SortedProbe<'_, P> {
111        SortedProbe {
112            tree: self,
113            leaf: None,
114            last: Vec::new(),
115        }
116    }
117
118    /// The leaf `key` is in if the tree has it: the descent, then the
119    /// right-link hops `get` makes for a leaf split after the descent.
120    pub(super) fn leaf_for(&self, key: &[u8]) -> BTreeResult<Option<Page>> {
121        let root_id = self.root_page_id();
122        if root_id == 0 {
123            return Ok(None);
124        }
125        let (mut leaf_id, _) = self.find_leaf(root_id, key)?;
126        const MAX_RIGHTLINK_HOPS: usize = 32;
127        for _ in 0..MAX_RIGHTLINK_HOPS {
128            let page = self.pager.read_page(leaf_id)?;
129            let right = leaf_right_sibling(&page);
130            let cells = usize::from(page.cell_count());
131            if right != 0 && cells > 0 && key > read_leaf_cell_borrowed(&page, cells - 1)?.0 {
132                leaf_id = right;
133                continue;
134            }
135            return Ok(Some(page));
136        }
137        let (leaf_id, _) = self.find_leaf(self.root_page_id(), key)?;
138        Ok(Some(self.pager.read_page(leaf_id)?))
139    }
140
141    /// Bound value materialization before allocating overflow or decode buffers.
142    pub fn get_with_budget(&self, key: &[u8], limit_bytes: usize) -> BTreeResult<Option<Vec<u8>>> {
143        let root_id = self.root_page_id();
144        if root_id == 0 {
145            return Ok(None);
146        }
147
148        // Descend from root to the target leaf
149        let (leaf_id, _) = self.find_leaf(root_id, key)?;
150
151        // D3 — Lehman-Yao right-link traversal.
152        //
153        // A concurrent insert may have split the leaf between our descent
154        // and this read. If the key we're searching for is greater than the
155        // current page's high_key (max stored key), the key lives on a
156        // right-sibling page — follow the right-link instead of re-descending
157        // from the root. Cap at MAX_RIGHTLINK_HOPS to guard against corrupt
158        // link chains.
159        const MAX_RIGHTLINK_HOPS: usize = 32;
160        let mut current_id = leaf_id;
161        for _ in 0..MAX_RIGHTLINK_HOPS {
162            let page = self.pager.read_page(current_id)?;
163
164            match search_leaf(&page, key)? {
165                SearchResult::Found(pos) => {
166                    let (_, stored) = read_leaf_cell(&page, pos)?;
167                    let value = value_layout::decode_with_budget(
168                        self.pager.as_ref(),
169                        &stored,
170                        limit_bytes,
171                    )?;
172                    return Ok(Some(value));
173                }
174                SearchResult::NotFound(_) => {
175                    // Check if a split pushed our key to the right sibling
176                    let right = leaf_right_sibling(&page);
177                    if right != 0 {
178                        if let Some(high_key) = leaf_high_key(&page)? {
179                            if key > high_key.as_slice() {
180                                // Key belongs on a right sibling — follow link
181                                current_id = right;
182                                continue;
183                            }
184                        }
185                    }
186                    // Key genuinely not present
187                    return Ok(None);
188                }
189            }
190        }
191
192        // Exhausted hop limit — fall back to root descent (corrupt link chain)
193        let (leaf_id, _) = self.find_leaf(self.root_page_id(), key)?;
194        let page = self.pager.read_page(leaf_id)?;
195        match search_leaf(&page, key)? {
196            SearchResult::Found(pos) => {
197                let (_, stored) = read_leaf_cell(&page, pos)?;
198                let value =
199                    value_layout::decode_with_budget(self.pager.as_ref(), &stored, limit_bytes)?;
200                Ok(Some(value))
201            }
202            SearchResult::NotFound(_) => Ok(None),
203        }
204    }
205
206    /// Insert a key-value pair.
207    ///
208    /// Applies the value-layout spill ladder before touching the tree:
209    /// the 256 MB ceiling rejects here without any allocation; values
210    /// at or below `COMPRESSION_THRESHOLD` go inline raw; larger values
211    /// select raw/compressed bytes and spill beyond `OVERFLOW_THRESHOLD`
212    /// into an [`crate::storage::overflow::OverflowChain`].
213    /// The encoded bytes are then committed through [`Self::insert_encoded`].
214    pub fn insert(&self, key: &[u8], value: &[u8]) -> BTreeResult<()> {
215        let _writer = self.writer.lock();
216        if key.len() > MAX_KEY_SIZE {
217            return Err(BTreeError::KeyTooLarge(key.len()));
218        }
219        let stored = value_layout::encode(self.pager.as_ref(), value)?;
220        self.insert_encoded(key, &stored)
221    }
222
223    /// Insert a key with bytes already produced by [`value_layout::encode`].
224    ///
225    /// Internal entry point used by `bulk_insert_sorted` so its fast
226    /// path can pre-encode the whole batch (eagerly allocating overflow
227    /// pages, surfacing oversize rows up front) and still re-use the
228    /// generic insert machinery for fallback. Public callers should go
229    /// through [`Self::insert`] which encodes for them.
230    pub(crate) fn insert_encoded(&self, key: &[u8], value: &[u8]) -> BTreeResult<()> {
231        let _writer = self.writer.lock();
232        let root_id = self.root_page_id();
233
234        // Dispatch before reserving the existing-tree page buffers. A bulk
235        // checkpoint can create proof pages on the same worker stack.
236        if root_id == 0 {
237            return self.insert_encoded_new_root(key, value);
238        }
239        self.insert_encoded_existing_root(root_id, key, value)
240    }
241
242    fn insert_encoded_new_root(&self, key: &[u8], value: &[u8]) -> BTreeResult<()> {
243        let mut page = self.pager.allocate_page(PageType::BTreeLeaf)?;
244        clear_leaf_cells(&mut page);
245        insert_into_leaf(&mut page, key, value)?;
246        init_leaf_links(&mut page, 0, 0);
247        page.update_checksum();
248        let new_root = page.page_id();
249        self.pager.write_page(new_root, page)?;
250        *self.root_page_id.write().map_err(|e| {
251            BTreeError::LockPoisoned(format!("insert: root_page_id write lock: {e}"))
252        })? = new_root;
253        Ok(())
254    }
255
256    fn insert_encoded_existing_root(
257        &self,
258        root_id: u32,
259        key: &[u8],
260        value: &[u8],
261    ) -> BTreeResult<()> {
262        // D2 fastpath: if key > cached rightmost high_key, go directly to
263        // the cached leaf without descending from the root. This cuts
264        // tree descent entirely for monotonic append workloads (timeseries,
265        // auto-increment entity IDs).
266        let cached = {
267            self.rightmost_leaf
268                .read()
269                .map_err(|e| BTreeError::LockPoisoned(format!("rightmost_leaf read: {e}")))?
270                .clone()
271        };
272        if let Some((cached_page_id, ref high_key)) = cached {
273            if key > high_key.as_slice() {
274                let mut page = self.pager.read_page(cached_page_id)?;
275                // Confirm this page is still a valid leaf with a right-link
276                // of 0 (i.e., it IS the rightmost leaf — not mid-tree after
277                // a concurrent split moved the boundary).
278                let right_sibling = leaf_right_sibling(&page);
279                if right_sibling == 0 {
280                    // Still the rightmost leaf. Try fast append.
281                    if can_insert_leaf(&page, key, value) {
282                        insert_into_leaf(&mut page, key, value)?;
283                        // Skip update_checksum here — pager.write_page
284                        // below recomputes it. Saves one CRC32 on 16 KiB
285                        // per insert on the hot append path.
286                        let page_id = page.page_id();
287                        // Update cached high_key
288                        *self.rightmost_leaf.write().map_err(|e| {
289                            BTreeError::LockPoisoned(format!("rightmost_leaf write: {e}"))
290                        })? = Some((page_id, key.to_vec()));
291                        self.pager.write_page(page_id, page)?;
292                        return Ok(());
293                    }
294                    // Leaf is full — split. After split, invalidate cache
295                    // (the new rightmost leaf is the split result).
296                    let (new_leaf, separator_key) = self.split_leaf(&mut page, key, value)?;
297                    let new_leaf_id = new_leaf.page_id();
298                    page.update_checksum();
299                    let page_id = page.page_id();
300                    self.pager.write_page(page_id, page.clone())?;
301                    // Cache the new rightmost leaf after split
302                    self.cache_rightmost_leaf(&new_leaf)?;
303                    // Get parent path for the split propagation.
304                    // The left child is the original cached leaf.
305                    let (_, path) = self.find_leaf(root_id, &separator_key)?;
306                    self.insert_into_parent(path, cached_page_id, &separator_key, new_leaf_id)?;
307                    return Ok(());
308                }
309                // right_sibling != 0: cached page is no longer rightmost.
310                // Fall through to the full find_leaf path below and
311                // refresh the cache.
312                *self.rightmost_leaf.write().map_err(|e| {
313                    BTreeError::LockPoisoned(format!("rightmost_leaf write: {e}"))
314                })? = None;
315            }
316        }
317
318        // Find the leaf and path to it
319        let (leaf_id, path) = self.find_leaf(root_id, key)?;
320        let mut page = self.pager.read_page(leaf_id)?;
321
322        // Check for duplicate
323        if let SearchResult::Found(_) = search_leaf(&page, key)? {
324            return Err(BTreeError::DuplicateKey);
325        }
326
327        // Try to insert into leaf
328        if can_insert_leaf(&page, key, value) {
329            insert_into_leaf(&mut page, key, value)?;
330            // Skip update_checksum — pager.write_page recomputes it.
331            let page_id = page.page_id();
332            // If this is the rightmost leaf (right_sibling == 0), cache it.
333            if leaf_right_sibling(&page) == 0 {
334                self.cache_rightmost_leaf(&page)?;
335            }
336            self.pager.write_page(page_id, page)?;
337            return Ok(());
338        }
339
340        // Need to split the leaf
341        let (new_leaf, separator_key) = self.split_leaf(&mut page, key, value)?;
342        let new_leaf_id = new_leaf.page_id();
343        page.update_checksum();
344        let page_id = page.page_id();
345        self.pager.write_page(page_id, page.clone())?;
346        // Cache the new rightmost leaf (split result gets the larger keys)
347        self.cache_rightmost_leaf(&new_leaf)?;
348
349        // Propagate split up the tree
350        self.insert_into_parent(path, page_id, &separator_key, new_leaf_id)?;
351
352        Ok(())
353    }
354
355    /// Insert or update a key. If the key already exists and the new
356    /// value has the same length as the old, the value bytes are
357    /// overwritten in place — no structural changes, no rebalance,
358    /// one leaf page write.
359    ///
360    /// Falls back to `delete + insert` when the key is missing or the
361    /// new value has a different length. Callers like
362    /// `persist_entities_to_pager` that re-serialize a mutated entity
363    /// with a fixed-width schema almost always hit the fast path,
364    /// eliminating the `BTree::delete + rebalance` cost that previously
365    /// dominated UPDATE workloads (~50% of `bulk_update` CPU).
366    pub fn upsert(&self, key: &[u8], value: &[u8]) -> BTreeResult<()> {
367        let _writer = self.writer.lock();
368        let root_id = self.root_page_id();
369        if root_id == 0 {
370            return self.insert(key, value);
371        }
372
373        // Encode the new value once. The in-place fast path compares
374        // encoded lengths so the leaf cell stays in the on-disk format
375        // documented in `value_layout`; without this the in-place write
376        // would scribble raw bytes over a flag-prefixed cell.
377        let new_stored = value_layout::encode(self.pager.as_ref(), value)?;
378
379        let (leaf_id, _path) = self.find_leaf(root_id, key)?;
380        let mut page = self.pager.read_page(leaf_id)?;
381
382        if let SearchResult::Found(pos) = search_leaf(&page, key)? {
383            let (_, old_value) = read_leaf_cell(&page, pos)?;
384            if new_stored.len() <= old_value.len() {
385                // Shrinking (or same-size) overwrite. If the old cell
386                // owned an overflow chain, free it before the new bytes
387                // overwrite the pointer header — otherwise the chain
388                // is unreachable but still allocated (slice F).
389                self.free_chain_if_pointer(&old_value)?;
390                overwrite_leaf_value(&mut page, pos, &new_stored)?;
391                let page_id = page.page_id();
392                self.pager.write_page(page_id, page)?;
393                return Ok(());
394            }
395            // Grow case: fall through to delete+insert for a proper
396            // reallocation + potential rebalance.
397            let _ = self.delete(key);
398            return self.insert_encoded(key, &new_stored);
399        }
400
401        // Key is new — plain insert path. Reuse the bytes we already
402        // encoded above instead of re-running LZ4 / re-allocating.
403        self.insert_encoded(key, &new_stored)
404    }
405
406    /// Upsert inline values without allocating, freeing or changing tree links.
407    /// The caller must make every value durable in its WAL before
408    /// calling this method. Returns false without writing if any item needs a
409    /// structural update or an overflow chain.
410    pub fn try_upsert_inline_without_splits(
411        &self,
412        items: &[(Vec<u8>, Vec<u8>)],
413    ) -> BTreeResult<bool> {
414        let _writer = self.writer.lock();
415        let root_id = self.root_page_id();
416        if root_id == 0 && !items.is_empty() {
417            return Ok(false);
418        }
419        let mut pages = std::collections::BTreeMap::<u32, (Page, Vec<(Vec<u8>, Vec<u8>)>)>::new();
420        for (key, value) in items {
421            if key.len() > MAX_KEY_SIZE {
422                return Err(BTreeError::KeyTooLarge(key.len()));
423            }
424            let Some(new_value) = value_layout::encode_inline_without_pages(value)? else {
425                return Ok(false);
426            };
427            let (leaf_id, _) = self.find_leaf(root_id, key)?;
428            if let std::collections::btree_map::Entry::Vacant(entry) = pages.entry(leaf_id) {
429                let page = self.pager.read_page(leaf_id)?;
430                let entries = read_leaf_entries(&page)?;
431                entry.insert((page, entries));
432            }
433            let (_, entries) = pages.get_mut(&leaf_id).expect("leaf was loaded");
434            match entries.binary_search_by(|(existing, _)| existing.as_slice().cmp(key)) {
435                Ok(position) => {
436                    if value_layout::pointer_head(&entries[position].1).is_some() {
437                        return Ok(false);
438                    }
439                    entries[position].1 = new_value;
440                }
441                Err(position) => entries.insert(position, (key.clone(), new_value)),
442            }
443        }
444        // Check every leaf before writing any of them. Repacking can use dead
445        // cell space, but must never split or alter routing links.
446        for (page, entries) in pages.values_mut() {
447            if leaf_entries_size(entries) > PAGE_SIZE - LEAF_SLOT_ARRAY_OFFSET {
448                return Ok(false);
449            }
450            write_leaf_entries(page, entries)?;
451        }
452        for (page_id, (page, _)) in pages {
453            self.pager.write_page(page_id, page)?;
454        }
455        Ok(true)
456    }
457
458    /// Batch upsert for sorted keys landing in a small set of leaves.
459    ///
460    /// Walks to each leaf once, applies every same-or-shrink in-place
461    /// overwrite that belongs there, writes the page once, then moves
462    /// on. Keys that miss or whose new value grows fall back to the
463    /// generic single-key `upsert` path — correctness identical,
464    /// structural re-layout handled there.
465    ///
466    /// Callers pass lex-sorted `(key, value)` pairs. For the entity
467    /// UPDATE path, IDs are big-endian so u64 ordering = lex ordering.
468    pub fn upsert_batch_sorted(&self, items: &[(Vec<u8>, Vec<u8>)]) -> BTreeResult<()> {
469        let _writer = self.writer.lock();
470        if items.is_empty() {
471            return Ok(());
472        }
473        if self.root_page_id() == 0 {
474            for (k, v) in items {
475                self.upsert(k, v)?;
476            }
477            return Ok(());
478        }
479
480        let mut current_leaf: Option<(u32, Page, bool)> = None; // (leaf_id, page, dirty)
481        for (key, value) in items {
482            // The leaf in hand is this key's while it reaches that far: the
483            // descent used to be made for every key, three page reads to
484            // learn what the page already said. A key the leaf cannot hold
485            // is routed from the root, which a split below may have moved.
486            let in_hand = match &current_leaf {
487                Some((_, page, _)) => leaf_holds_ascending(page, key)?,
488                None => false,
489            };
490            if !in_hand {
491                let (leaf_id, _path) = self.find_leaf(self.root_page_id(), key)?;
492                if current_leaf.as_ref().map(|(id, _, _)| *id) != Some(leaf_id) {
493                    if let Some((id, page, dirty)) = current_leaf.take() {
494                        self.write_batch_leaf(id, page, dirty)?;
495                    }
496                    let page = self.pager.read_page(leaf_id)?;
497                    current_leaf = Some((leaf_id, page, false));
498                }
499            }
500
501            // Encode the new value through the spill ladder so the
502            // length comparison is between encoded bytes (matching the
503            // on-disk cell format). Compute lazily: only the in-place
504            // branch needs it, and an oversize value gets caught by the
505            // single-key `upsert` fallback below.
506            let applied_in_place = {
507                let (_, page, dirty) = current_leaf.as_mut().expect("set above");
508                if let SearchResult::Found(pos) = search_leaf(page, key)? {
509                    let (_, old_value) = read_leaf_cell(page, pos)?;
510                    match value_layout::encode(self.pager.as_ref(), value) {
511                        Ok(new_stored) if new_stored.len() <= old_value.len() => {
512                            // Shrinking overwrite: free the old chain
513                            // before the pointer header is scribbled over
514                            // (slice F).
515                            self.free_chain_if_pointer(&old_value)?;
516                            overwrite_leaf_value(page, pos, &new_stored)?;
517                            *dirty = true;
518                            true
519                        }
520                        _ => false,
521                    }
522                } else {
523                    // A new key that fits joins the leaf and is written with
524                    // it. Each one used to leave the batch for a descent and
525                    // a leaf write of its own.
526                    match value_layout::encode_inline_without_pages(value) {
527                        Ok(Some(stored)) if can_insert_leaf(page, key, &stored) => {
528                            insert_into_leaf(page, key, &stored)?;
529                            *dirty = true;
530                            true
531                        }
532                        _ => false,
533                    }
534                }
535            };
536            if !applied_in_place {
537                if let Some((id, page, dirty)) = current_leaf.take() {
538                    self.write_batch_leaf(id, page, dirty)?;
539                }
540                self.upsert(key, value)?;
541            }
542        }
543
544        if let Some((id, page, dirty)) = current_leaf.take() {
545            self.write_batch_leaf(id, page, dirty)?;
546        }
547        Ok(())
548    }
549
550    /// Write the leaf a sorted batch had in hand, if the batch changed it.
551    fn write_batch_leaf(&self, id: u32, mut page: Page, dirty: bool) -> BTreeResult<()> {
552        if !dirty {
553            return Ok(());
554        }
555        page.update_checksum();
556        if leaf_right_sibling(&page) == 0 {
557            self.cache_rightmost_leaf(&page)?;
558        }
559        self.pager.write_page(id, page)?;
560        Ok(())
561    }
562
563    /// Insert keys given in ascending order, wherever in the tree they belong.
564    ///
565    /// Walks to a leaf once, puts into it every following key that belongs
566    /// there and fits, and writes it once. `insert` walks from the root and
567    /// rewrites the leaf for each key, and `bulk_insert_sorted` batches only
568    /// keys past the end of a leaf. A key that does not fit, or whose value
569    /// leaves the leaf, takes the single-key path, which splits.
570    pub fn insert_sorted(&self, items: &[(Vec<u8>, Vec<u8>)]) -> BTreeResult<()> {
571        let _writer = self.writer.lock();
572        for (key, _) in items {
573            if key.len() > MAX_KEY_SIZE {
574                return Err(BTreeError::KeyTooLarge(key.len()));
575            }
576        }
577        let mut next = 0;
578        while next < items.len() {
579            let (key, value) = &items[next];
580            let root_id = self.root_page_id();
581            if root_id == 0 {
582                self.insert(key, value)?;
583                next += 1;
584                continue;
585            }
586            let (leaf_id, path) = self.find_leaf(root_id, key)?;
587            let mut page = self.pager.read_page(leaf_id)?;
588            // The next leaf's first key is a hard ceiling; an ancestor
589            // separator can define an earlier routing boundary.
590            let next_min = match leaf_right_sibling(&page) {
591                0 => None,
592                next_id => {
593                    let following = self.pager.read_page(next_id)?;
594                    if following.page_type()? != PageType::BTreeLeaf || following.cell_count() == 0
595                    {
596                        return Err(BTreeError::Corrupted(
597                            "invalid next leaf during sorted insert".into(),
598                        ));
599                    }
600                    Some(read_leaf_cell(&following, 0)?.0)
601                }
602            };
603            let parent_upper = if next_min.is_some() {
604                self.leaf_upper_bound(leaf_id, &path)?
605            } else {
606                None
607            };
608            let mut placed = 0;
609            for (key, value) in &items[next..] {
610                if [&next_min, &parent_upper]
611                    .into_iter()
612                    .flatten()
613                    .any(|bound| key.as_slice() >= bound.as_slice())
614                {
615                    break;
616                }
617                let Some(stored) = value_layout::encode_inline_without_pages(value)? else {
618                    break;
619                };
620                if !can_insert_leaf(&page, key, &stored) {
621                    break;
622                }
623                insert_into_leaf(&mut page, key, &stored)?;
624                placed += 1;
625            }
626            if placed == 0 {
627                self.insert(key, value)?;
628                next += 1;
629            } else {
630                self.write_batch_leaf(leaf_id, page, true)?;
631                next += placed;
632            }
633        }
634        Ok(())
635    }
636
637    /// Bulk insert for sorted key-value pairs.
638    ///
639    /// Optimized for monotonically increasing keys (e.g. entity IDs):
640    /// - Walks to the target leaf ONCE, then appends many entries
641    ///   before re-walking.
642    /// - Writes each leaf only once per batch (amortized over many inserts).
643    ///
644    /// Falls back to per-entity `insert` on splits.
645    pub fn bulk_insert_sorted(&self, items: &[(Vec<u8>, Vec<u8>)]) -> BTreeResult<()> {
646        let _writer = self.writer.lock();
647        if items.is_empty() {
648            return Ok(());
649        }
650        // Key check is a hard fail (oversized keys would corrupt the
651        // ordering invariant). Value oversize, by contrast, is skipped
652        // per-row so a single huge row in the middle of a batch cannot
653        // poison the rest — the caller still gets a signal because we
654        // return the first ValueTooLarge after the rest have landed.
655        for (key, _) in items {
656            if key.len() > MAX_KEY_SIZE {
657                return Err(BTreeError::KeyTooLarge(key.len()));
658            }
659        }
660
661        // Pre-encode every value through the spill ladder. Oversized
662        // rows are dropped from the encoded batch but remembered so we
663        // can surface the first violation at the end of the call.
664        // Encoding here also allocates overflow pages eagerly, which
665        // mirrors single-key `insert` behaviour and keeps the bulk fast
666        // path below opaque to value shape.
667        let mut encoded: Vec<(&[u8], Vec<u8>)> = Vec::with_capacity(items.len());
668        let mut first_oversize: Option<usize> = None;
669        for (key, value) in items {
670            match value_layout::encode(self.pager.as_ref(), value) {
671                Ok(stored) => encoded.push((key.as_slice(), stored)),
672                Err(value_layout::ValueLayoutError::ValueTooLarge(n)) => {
673                    if first_oversize.is_none() {
674                        first_oversize = Some(n);
675                    }
676                }
677                Err(other) => return Err(other.into()),
678            }
679        }
680
681        let items: Vec<(&[u8], &[u8])> = encoded.iter().map(|(k, v)| (*k, v.as_slice())).collect();
682
683        // After a filled leaf is written to disk, the next ascending
684        // key almost certainly belongs on the right-sibling leaf
685        // (leaves are linked via `leaf_right_sibling`). Cache the
686        // just-written leaf id so the next outer iteration can hop
687        // the sibling pointer in one page read instead of a full
688        // root-to-leaf walk. Any fallback to `self.insert` (which
689        // may split the tree) invalidates the hint.
690        let mut last_filled_leaf: Option<u32> = None;
691        let mut i = 0;
692        while i < items.len() {
693            let root_id = self.root_page_id();
694            if root_id == 0 {
695                // Empty tree — use single insert to create root.
696                // Bytes are already encoded, so go through the internal
697                // entry point that skips the spill ladder.
698                let (k, v) = items[i];
699                self.insert_encoded(k, v)?;
700                i += 1;
701                last_filled_leaf = None;
702                continue;
703            }
704
705            // Try the right-sibling hop first. Valid when: (a) we have
706            // a cached last-filled leaf, (b) it points to a non-zero
707            // sibling, (c) the current key > sibling's last key (or
708            // the sibling is empty). Any mismatch → fall back to
709            // `find_leaf`.
710            let hint_leaf_id: Option<u32> = if let Some(prev) = last_filled_leaf {
711                let prev_page = self.pager.read_page(prev)?;
712                let sibling = leaf_right_sibling(&prev_page);
713                if sibling != 0 {
714                    let sib_page = self.pager.read_page(sibling)?;
715                    match leaf_high_key(&sib_page)? {
716                        None if leaf_right_sibling(&sib_page) == 0 => Some(sibling),
717                        None => None,
718                        Some(hk)
719                            if leaf_right_sibling(&sib_page) == 0 && items[i].0 > hk.as_slice() =>
720                        {
721                            Some(sibling)
722                        }
723                        Some(_) => None,
724                    }
725                } else {
726                    None
727                }
728            } else {
729                None
730            };
731
732            let (leaf_id, path) = match hint_leaf_id {
733                Some(id) => (id, Vec::new()),
734                None => self.find_leaf(root_id, items[i].0)?,
735            };
736            let mut page = self.pager.read_page(leaf_id)?;
737            // The next leaf's first key is a hard ceiling; an ancestor
738            // separator can define an earlier routing boundary.
739            let next_min = match leaf_right_sibling(&page) {
740                0 => None,
741                next_id => {
742                    let next = self.pager.read_page(next_id)?;
743                    if next.page_type()? != PageType::BTreeLeaf || next.cell_count() == 0 {
744                        return Err(BTreeError::Corrupted(
745                            "invalid next leaf during bulk insert".into(),
746                        ));
747                    }
748                    Some(read_leaf_cell(&next, 0)?.0)
749                }
750            };
751            let parent_upper = if next_min.is_some() {
752                self.leaf_upper_bound(leaf_id, &path)?
753            } else {
754                None
755            };
756
757            // Snapshot the leaf's last key (via the O(1) slot lookup)
758            // and current free bytes. Both drive the append fast path
759            // below. The old O(M) forward-walk that this block used to
760            // do was made redundant by the slotted layout.
761            let mut last_key_in_leaf: Option<Vec<u8>> = {
762                let cell_count = page.cell_count() as usize;
763                if cell_count == 0 {
764                    None
765                } else {
766                    Some(read_leaf_cell(&page, cell_count - 1)?.0)
767                }
768            };
769
770            // Fast path for monotonically-ascending keys: append new
771            // cells at the tail of the cell-data area and push new
772            // slot pointers onto the slot array. Every key must be
773            // strictly greater than `last_key_in_leaf` and must still
774            // fit in the leaf's free bytes.
775            let mut inserted = 0usize;
776            while i + inserted < items.len() {
777                let (key, value) = items[i + inserted];
778                if next_min
779                    .as_ref()
780                    .is_some_and(|bound| key >= bound.as_slice())
781                    || parent_upper
782                        .as_ref()
783                        .is_some_and(|bound| key >= bound.as_slice())
784                {
785                    break;
786                }
787
788                // Strictly-ascending check, doubles as duplicate
789                // detection without a leaf binary search.
790                if let Some(lk) = &last_key_in_leaf {
791                    match key.cmp(lk.as_slice()) {
792                        Ordering::Greater => {}
793                        Ordering::Equal => return Err(BTreeError::DuplicateKey),
794                        Ordering::Less => break,
795                    }
796                }
797
798                // Free-space check: account for every slot appended in this
799                // batch even though `page.cell_count()` is only updated once
800                // at the end. Otherwise we can overrun the slot array into the
801                // cell area near the end of the page and persist bad offsets.
802                let cell_size = 4 + key.len() + value.len();
803                let slot_end_after =
804                    LEAF_SLOT_ARRAY_OFFSET + (page.cell_count() as usize + inserted + 1) * 2;
805                let cells_start = leaf_cells_start(&page);
806                if slot_end_after + cell_size > cells_start {
807                    break;
808                }
809
810                // Append the cell at the tail of the cell-data area
811                // and push a new slot pointer. `page.cell_count()`
812                // still reflects the state before this inserted batch,
813                // so the new slot index is `cell_count + inserted`.
814                let cell_offset = cells_start - cell_size;
815                {
816                    let data = page.as_bytes_mut();
817                    data[cell_offset..cell_offset + 2]
818                        .copy_from_slice(&(key.len() as u16).to_le_bytes());
819                    data[cell_offset + 2..cell_offset + 4]
820                        .copy_from_slice(&(value.len() as u16).to_le_bytes());
821                    data[cell_offset + 4..cell_offset + 4 + key.len()].copy_from_slice(key);
822                    data[cell_offset + 4 + key.len()..cell_offset + cell_size]
823                        .copy_from_slice(value);
824                }
825                page.set_free_end(cell_offset as u16);
826
827                let new_slot_index = page.cell_count() as usize + inserted;
828                let slot_pos = leaf_slot_offset_for(new_slot_index);
829                {
830                    let data = page.as_bytes_mut();
831                    data[slot_pos..slot_pos + 2]
832                        .copy_from_slice(&(cell_offset as u16).to_le_bytes());
833                }
834
835                last_key_in_leaf = Some(key.to_vec());
836                inserted += 1;
837            }
838
839            if inserted > 0 {
840                let new_count = page.cell_count() as usize + inserted;
841                page.set_cell_count(new_count as u16);
842                page.set_free_start((LEAF_SLOT_ARRAY_OFFSET + new_count * 2) as u16);
843                page.update_checksum();
844                self.cache_rightmost_leaf(&page)?;
845                self.pager.write_page(leaf_id, page)?;
846                i += inserted;
847                // Remember this leaf; the next outer iteration will
848                // try its right sibling before re-walking from root.
849                last_filled_leaf = Some(leaf_id);
850            } else {
851                // Couldn't fit even one entry via the fast path —
852                // either the leaf is full, or the next key belongs
853                // in the middle of the leaf. Delegate to the generic
854                // insert path which handles both splitting and
855                // mid-leaf positioning. Splits can invalidate the
856                // leaf-chain topology so drop the hint.
857                let (k, v) = items[i];
858                self.insert_encoded(k, v)?;
859                i += 1;
860                last_filled_leaf = None;
861            }
862        }
863
864        // Valid rows have all landed by this point; surface the first
865        // oversize so callers still see a `ValueTooLarge` signal
866        // without losing the rest of the batch (AC #5 — one oversized
867        // row in the middle is rejected but the rest land).
868        if let Some(n) = first_oversize {
869            return Err(BTreeError::ValueTooLarge(n));
870        }
871
872        Ok(())
873    }
874
875    /// Delete a key
876    pub fn delete(&self, key: &[u8]) -> BTreeResult<bool> {
877        let _writer = self.writer.lock();
878        let root_id = self.root_page_id();
879        if root_id == 0 {
880            return Ok(false);
881        }
882
883        // D3 — Lehman-Yao right-link traversal for delete.
884        // A split may have moved the key to a right sibling between our
885        // descent and the actual page read. Follow right-links before giving up.
886        let (leaf_id, path) = self.find_leaf(root_id, key)?;
887        let mut current_id = leaf_id;
888        const MAX_RIGHTLINK_HOPS: usize = 32;
889        for _ in 0..MAX_RIGHTLINK_HOPS {
890            let mut page = self.pager.read_page(current_id)?;
891            match search_leaf(&page, key)? {
892                SearchResult::Found(pos) => {
893                    // Found — delete from this page (may differ from leaf_id).
894                    // If the cell carries a spill pointer, return every
895                    // overflow page to the free list before the leaf cell
896                    // goes away; otherwise the chain leaks (slice F).
897                    let (_, stored) = read_leaf_cell(&page, pos)?;
898                    self.free_chain_if_pointer(&stored)?;
899                    delete_from_leaf(&mut page, pos)?;
900                    page.update_checksum();
901                    let page_id = page.page_id();
902                    self.pager.write_page(page_id, page.clone())?;
903
904                    *self
905                        .rightmost_leaf
906                        .write()
907                        .unwrap_or_else(|e| e.into_inner()) = None;
908
909                    if page.cell_count() == 0 && page_id == root_id {
910                        self.pager.free_page(root_id)?;
911                        self.pager.reset_empty()?;
912                        *self.root_page_id.write().map_err(|e| {
913                            BTreeError::LockPoisoned(format!(
914                                "delete: root_page_id write lock: {e}"
915                            ))
916                        })? = 0;
917                    } else {
918                        self.rebalance_leaf(current_id, path)?;
919                    }
920                    return Ok(true);
921                }
922                SearchResult::NotFound(_) => {
923                    let right = leaf_right_sibling(&page);
924                    if right != 0 {
925                        if let Some(high_key) = leaf_high_key(&page)? {
926                            if key > high_key.as_slice() {
927                                current_id = right;
928                                continue;
929                            }
930                        }
931                    }
932                    return Ok(false);
933                }
934            }
935        }
936        Ok(false)
937    }
938
939    /// Create a cursor at the first entry of a tree that nothing writes while
940    /// the cursor lives, such as a sorted run about to be merged. It keeps the
941    /// leaf it is on; a cursor from [`Self::cursor_first`] reads its leaf
942    /// again, and proves it again, for every entry.
943    pub fn cursor_first_frozen(&self) -> BTreeResult<BTreeCursor<P>> {
944        Ok(self.cursor_first()?.with_immutable_leaves())
945    }
946
947    /// Create a cursor starting at the first entry
948    pub fn cursor_first(&self) -> BTreeResult<BTreeCursor<P>> {
949        let root_id = self.root_page_id();
950        if root_id == 0 {
951            return Ok(BTreeCursor {
952                _retirement_pin: Arc::clone(&self.retirement_pin),
953                leaf_page_id: 0,
954                position: 0,
955                pager: self.pager.clone(),
956                prefetched_next: false,
957                immutable: false,
958                immutable_leaf: None,
959            });
960        }
961
962        // Find leftmost leaf
963        let first_leaf = self.find_first_leaf(root_id)?;
964
965        Ok(BTreeCursor {
966            _retirement_pin: Arc::clone(&self.retirement_pin),
967            leaf_page_id: first_leaf,
968            position: 0,
969            pager: self.pager.clone(),
970            prefetched_next: false,
971            immutable: false,
972            immutable_leaf: None,
973        })
974    }
975
976    /// Create a cursor starting at or after the given key
977    pub fn cursor_seek(&self, key: &[u8]) -> BTreeResult<BTreeCursor<P>> {
978        let root_id = self.root_page_id();
979        if root_id == 0 {
980            return Ok(BTreeCursor {
981                _retirement_pin: Arc::clone(&self.retirement_pin),
982                leaf_page_id: 0,
983                position: 0,
984                pager: self.pager.clone(),
985                prefetched_next: false,
986                immutable: false,
987                immutable_leaf: None,
988            });
989        }
990
991        let (leaf_id, _) = self.find_leaf(root_id, key)?;
992        let page = self.pager.read_page(leaf_id)?;
993
994        let position = match search_leaf(&page, key)? {
995            SearchResult::Found(pos) => pos,
996            SearchResult::NotFound(pos) => pos,
997        };
998
999        Ok(BTreeCursor {
1000            _retirement_pin: Arc::clone(&self.retirement_pin),
1001            leaf_page_id: leaf_id,
1002            position,
1003            pager: self.pager.clone(),
1004            prefetched_next: false,
1005            immutable: false,
1006            immutable_leaf: None,
1007        })
1008    }
1009
1010    /// Range scan from start_key to end_key (inclusive)
1011    pub fn range(&self, start_key: &[u8], end_key: &[u8]) -> BTreeResult<Vec<(Vec<u8>, Vec<u8>)>> {
1012        let mut results = Vec::new();
1013        let mut cursor = self.cursor_seek(start_key)?;
1014
1015        while let Some((key, value)) = cursor.next()? {
1016            if key.as_slice() > end_key {
1017                break;
1018            }
1019            results.push((key, value));
1020        }
1021
1022        Ok(results)
1023    }
1024
1025    /// Count entries in the tree
1026    pub fn count(&self) -> BTreeResult<usize> {
1027        let root_id = self.root_page_id();
1028        if root_id == 0 {
1029            return Ok(0);
1030        }
1031
1032        let mut count = 0;
1033        let mut cursor = self.cursor_first()?;
1034        while cursor.next()?.is_some() {
1035            count += 1;
1036        }
1037
1038        Ok(count)
1039    }
1040
1041    // ==================== Internal Methods ====================
1042
1043    fn cache_rightmost_leaf(&self, page: &Page) -> BTreeResult<()> {
1044        // A split's incoming key may land in its left half. Caching that
1045        // key as the right half's maximum sends later inserts to the wrong
1046        // leaf, even with a single writer (#2376).
1047        let cached = if leaf_right_sibling(page) == 0 {
1048            leaf_high_key(page)?.map(|high| (page.page_id(), high))
1049        } else {
1050            None
1051        };
1052        *self.rightmost_leaf.write().map_err(|error| {
1053            BTreeError::LockPoisoned(format!("rightmost_leaf write: {error}"))
1054        })? = cached;
1055        Ok(())
1056    }
1057
1058    /// Find the first upper separator on the path from a leaf to the root.
1059    /// A separator may be lower than the next leaf's current minimum after
1060    /// deletion, so the neighboring leaf alone is not a routing boundary.
1061    fn leaf_upper_bound(&self, leaf_id: u32, path: &[u32]) -> BTreeResult<Option<Vec<u8>>> {
1062        let mut child_id = leaf_id;
1063        for &parent_id in path.iter().rev() {
1064            let parent = self.pager.read_page(parent_id)?;
1065            let (keys, children) = read_interior_keys_children(&parent)?;
1066            let position = children
1067                .iter()
1068                .position(|id| *id == child_id)
1069                .ok_or_else(|| {
1070                    BTreeError::Corrupted("bulk insert path is missing its child".into())
1071                })?;
1072            if let Some(upper) = keys.get(position) {
1073                return Ok(Some(upper.clone()));
1074            }
1075            child_id = parent_id;
1076        }
1077        Ok(None)
1078    }
1079
1080    /// Find the leaf page containing the key
1081    fn find_leaf(&self, page_id: u32, key: &[u8]) -> BTreeResult<(u32, Vec<u32>)> {
1082        let mut current_id = page_id;
1083        let mut path = Vec::new();
1084
1085        // A u32 page address space cannot contain a valid B-tree this deep.
1086        // Bound corrupt child cycles before they grow the descent path.
1087        for _ in 0..64 {
1088            let page = self.pager.read_page(current_id)?;
1089
1090            match page.page_type()? {
1091                PageType::BTreeLeaf => {
1092                    return Ok((current_id, path));
1093                }
1094                PageType::BTreeInterior => {
1095                    path.push(current_id);
1096                    current_id = find_child(&page, key)?;
1097                }
1098                other => {
1099                    return Err(BTreeError::Corrupted(format!(
1100                        "Unexpected page type in B-tree: {:?}",
1101                        other
1102                    )));
1103                }
1104            }
1105        }
1106        Err(BTreeError::Corrupted(
1107            "B-tree descent exceeds maximum depth".into(),
1108        ))
1109    }
1110
1111    /// Find the leftmost leaf page
1112    pub(crate) fn find_first_leaf(&self, page_id: u32) -> BTreeResult<u32> {
1113        let mut current_id = page_id;
1114
1115        for _ in 0..64 {
1116            let page = self.pager.read_page(current_id)?;
1117
1118            match page.page_type()? {
1119                PageType::BTreeLeaf => return Ok(current_id),
1120                PageType::BTreeInterior => {
1121                    // Go to leftmost child
1122                    current_id = find_first_child(&page)?;
1123                }
1124                _ => {
1125                    return Err(BTreeError::Corrupted("Invalid page type".into()));
1126                }
1127            }
1128        }
1129        Err(BTreeError::Corrupted(
1130            "leftmost-leaf descent exceeds maximum depth".into(),
1131        ))
1132    }
1133
1134    /// Split a leaf page
1135    fn split_leaf(
1136        &self,
1137        page: &mut Page,
1138        new_key: &[u8],
1139        new_value: &[u8],
1140    ) -> BTreeResult<(Page, Vec<u8>)> {
1141        // Collect all entries including the new one
1142        let mut entries: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
1143        let cell_count = page.cell_count() as usize;
1144
1145        for i in 0..cell_count {
1146            entries.push(read_leaf_cell(page, i)?);
1147        }
1148
1149        // Insert new entry in sorted position
1150        let insert_pos = entries.partition_point(|(k, _)| k.as_slice() < new_key);
1151        entries.insert(insert_pos, (new_key.to_vec(), new_value.to_vec()));
1152
1153        // Balance occupied bytes, including slots. A count midpoint can put
1154        // almost every wide cell on one side of a mixed-width leaf.
1155        let capacity = PAGE_SIZE - LEAF_SLOT_ARRAY_OFFSET;
1156        let total = leaf_entries_size(&entries);
1157        let mut left_bytes = 0;
1158        let mut split = None;
1159        let mut best_balance = usize::MAX;
1160        for index in 1..entries.len() {
1161            left_bytes += leaf_entry_size(&entries[index - 1]);
1162            let right_bytes = total - left_bytes;
1163            if left_bytes <= capacity && right_bytes <= capacity {
1164                let balance = left_bytes.abs_diff(right_bytes);
1165                if balance < best_balance {
1166                    split = Some(index);
1167                    best_balance = balance;
1168                }
1169            }
1170        }
1171        let mid = split
1172            .ok_or_else(|| BTreeError::Corrupted("leaf entries cannot fit in two pages".into()))?;
1173
1174        // Create new leaf
1175        let mut new_page = self.pager.allocate_page(PageType::BTreeLeaf)?;
1176
1177        // Update leaf links
1178        let old_next = read_next_leaf(page);
1179        init_leaf_links(&mut new_page, page.page_id(), old_next);
1180        set_next_leaf(page, new_page.page_id());
1181
1182        // Rebuild both halves through the slotted layout so their
1183        // cell_count, free_start and free_end headers are consistent.
1184        write_leaf_entries(page, &entries[..mid])?;
1185        write_leaf_entries(&mut new_page, &entries[mid..])?;
1186
1187        // Separator is first key of new leaf
1188        let separator = entries[mid].0.clone();
1189
1190        new_page.update_checksum();
1191        let new_page_id = new_page.page_id();
1192        self.pager.write_page(new_page_id, new_page.clone())?;
1193        if old_next != 0 {
1194            // Splitting a non-rightmost leaf inserts a new predecessor for the
1195            // old successor. Keep its backlink coherent with the forward chain.
1196            let mut successor = self.pager.read_page(old_next)?;
1197            if successor.page_type()? != PageType::BTreeLeaf {
1198                return Err(BTreeError::Corrupted("invalid split successor type".into()));
1199            }
1200            set_prev_leaf(&mut successor, new_page_id);
1201            successor.update_checksum();
1202            self.pager.write_page(old_next, successor)?;
1203        }
1204
1205        Ok((new_page, separator))
1206    }
1207
1208    /// Insert into parent after split
1209    fn insert_into_parent(
1210        &self,
1211        mut path: Vec<u32>,
1212        mut left_child: u32,
1213        key: &[u8],
1214        mut right_child: u32,
1215    ) -> BTreeResult<()> {
1216        let mut key = std::borrow::Cow::Borrowed(key);
1217        loop {
1218            let Some(parent_id) = path.pop() else {
1219                let mut new_root = self.pager.allocate_page(PageType::BTreeInterior)?;
1220                write_interior_entries(&mut new_root, &[key.to_vec()], &[left_child, right_child])?;
1221                new_root.update_checksum();
1222                let new_root_id = new_root.page_id();
1223                self.pager.write_page(new_root_id, new_root)?;
1224                *self.root_page_id.write().map_err(|e| {
1225                    BTreeError::LockPoisoned(format!(
1226                        "insert_into_parent: root_page_id write lock: {e}"
1227                    ))
1228                })? = new_root_id;
1229                return Ok(());
1230            };
1231            let mut parent = self.pager.read_page(parent_id)?;
1232            if can_insert_interior(&parent, &key) {
1233                insert_into_interior(&mut parent, &key, left_child, right_child)?;
1234                parent.update_checksum();
1235                self.pager.write_page(parent_id, parent)?;
1236                return Ok(());
1237            }
1238            let (new_interior, separator) =
1239                self.split_interior(&mut parent, &key, left_child, right_child)?;
1240            parent.update_checksum();
1241            self.pager.write_page(parent_id, parent)?;
1242            // Only compact identities ascend; 16-KiB page buffers must not
1243            // accumulate recursively while a salvage visitor is also active.
1244            left_child = parent_id;
1245            right_child = new_interior;
1246            key = std::borrow::Cow::Owned(separator);
1247        }
1248    }
1249
1250    /// Split an interior node
1251    fn split_interior(
1252        &self,
1253        page: &mut Page,
1254        new_key: &[u8],
1255        left_child: u32,
1256        right_child: u32,
1257    ) -> BTreeResult<(u32, Vec<u8>)> {
1258        let (mut keys, mut children) = read_interior_keys_children(page)?;
1259        let key_insert_pos = keys.partition_point(|key| key.as_slice() < new_key);
1260        let child_insert_pos = children
1261            .iter()
1262            .position(|child| *child == left_child)
1263            .unwrap_or(key_insert_pos);
1264
1265        keys.insert(key_insert_pos, new_key.to_vec());
1266        children.insert(child_insert_pos + 1, right_child);
1267
1268        // The promoted separator does not stay in either side; each
1269        // resulting page is rebuilt through the shared slotted writer.
1270        let mid = keys.len() / 2;
1271        let separator = keys[mid].clone();
1272
1273        // Create new interior node
1274        let mut new_page = self.pager.allocate_page(PageType::BTreeInterior)?;
1275
1276        write_interior_entries(page, &keys[..mid], &children[..mid + 1])?;
1277        write_interior_entries(&mut new_page, &keys[mid + 1..], &children[mid + 1..])?;
1278
1279        new_page.update_checksum();
1280        let new_page_id = new_page.page_id();
1281        self.pager.write_page(new_page_id, new_page)?;
1282
1283        Ok((new_page_id, separator))
1284    }
1285
1286    fn rebalance_leaf(&self, leaf_id: u32, mut path: Vec<u32>) -> BTreeResult<()> {
1287        // Finish the leaf step before ascending so its page buffers do not
1288        // accumulate with interior buffers on ordinary worker stacks.
1289        if let Some(parent_id) = self.rebalance_leaf_step(leaf_id, &path)? {
1290            path.pop();
1291            self.rebalance_interior(parent_id, path)?;
1292        }
1293        Ok(())
1294    }
1295
1296    fn rebalance_leaf_step(&self, leaf_id: u32, path: &[u32]) -> BTreeResult<Option<u32>> {
1297        if path.is_empty() {
1298            return Ok(None);
1299        }
1300
1301        let root_id = self.root_page_id();
1302        if leaf_id == root_id {
1303            return Ok(None);
1304        }
1305
1306        let mut leaf = self.pager.read_page(leaf_id)?;
1307        let min_bytes = leaf_min_bytes();
1308
1309        let parent_id = *path.last().ok_or_else(|| {
1310            BTreeError::Corrupted("rebalance_leaf: path unexpectedly empty".into())
1311        })?;
1312        let mut parent = self.pager.read_page(parent_id)?;
1313        // Most deletes leave the leaf full enough and its first key where the
1314        // parent says it is. Answer that from the page bytes: decoding the
1315        // leaf and its parent for every deleted row was most of a checkpoint
1316        // that applied a retention sweep.
1317        if leaf_used_bytes(&leaf)? >= min_bytes {
1318            match interior_child_slot(&parent, leaf_id)? {
1319                None => return Err(BTreeError::Corrupted("Leaf missing from parent".into())),
1320                Some((_, None)) => return Ok(None),
1321                Some((_, Some(separator))) => {
1322                    if read_leaf_cell_borrowed(&leaf, 0)?.0 == separator {
1323                        return Ok(None);
1324                    }
1325                }
1326            }
1327        }
1328        let mut leaf_entries = read_leaf_entries(&leaf)?;
1329        let (mut parent_keys, mut parent_children) = read_interior_keys_children(&parent)?;
1330
1331        let child_index = parent_children
1332            .iter()
1333            .position(|&id| id == leaf_id)
1334            .ok_or_else(|| BTreeError::Corrupted("Leaf missing from parent".into()))?;
1335
1336        if child_index > 0 {
1337            if let Some((first_key, _)) = leaf_entries.first() {
1338                if parent_keys.get(child_index - 1).map(|k| k.as_slice())
1339                    != Some(first_key.as_slice())
1340                {
1341                    parent_keys[child_index - 1] = first_key.clone();
1342                    write_interior_entries(&mut parent, &parent_keys, &parent_children)?;
1343                    parent.update_checksum();
1344                    self.pager.write_page(parent_id, parent.clone())?;
1345                }
1346            }
1347        }
1348
1349        if leaf_entries_size(&leaf_entries) >= min_bytes {
1350            return Ok(None);
1351        }
1352
1353        if child_index > 0 {
1354            let left_id = parent_children[child_index - 1];
1355            let mut left = self.pager.read_page(left_id)?;
1356            let mut left_entries = read_leaf_entries(&left)?;
1357            // Take entries until the two leaves are even, not only until
1358            // this one reaches the minimum: topped up to the minimum, the
1359            // next row deleted here borrows again, and a sweep in key order
1360            // rewrote both leaves and their parent for every row.
1361            let mut leaf_size = leaf_entries_size(&leaf_entries);
1362            let mut left_size = leaf_entries_size(&left_entries);
1363            let mut taken = 0;
1364            for entry in left_entries.iter().rev() {
1365                let moved = leaf_entry_size(entry);
1366                let left_after = left_size - moved;
1367                if left_after < min_bytes
1368                    || (leaf_size >= min_bytes && leaf_size + moved > left_after)
1369                {
1370                    break;
1371                }
1372                leaf_size += moved;
1373                left_size = left_after;
1374                taken += 1;
1375            }
1376            let borrowed = taken > 0;
1377            if borrowed {
1378                let mut moved = left_entries.split_off(left_entries.len() - taken);
1379                moved.append(&mut leaf_entries);
1380                leaf_entries = moved;
1381            }
1382
1383            if borrowed {
1384                write_leaf_entries(&mut left, &left_entries)?;
1385                left.update_checksum();
1386                self.pager.write_page(left_id, left)?;
1387
1388                write_leaf_entries(&mut leaf, &leaf_entries)?;
1389                leaf.update_checksum();
1390                self.pager.write_page(leaf_id, leaf)?;
1391
1392                if let Some((first_key, _)) = leaf_entries.first() {
1393                    parent_keys[child_index - 1] = first_key.clone();
1394                    write_interior_entries(&mut parent, &parent_keys, &parent_children)?;
1395                    parent.update_checksum();
1396                    self.pager.write_page(parent_id, parent)?;
1397                }
1398
1399                return Ok(None);
1400            }
1401        }
1402
1403        if child_index + 1 < parent_children.len() {
1404            let right_id = parent_children[child_index + 1];
1405            let mut right = self.pager.read_page(right_id)?;
1406            let mut right_entries = read_leaf_entries(&right)?;
1407            let mut leaf_size = leaf_entries_size(&leaf_entries);
1408            let mut right_size = leaf_entries_size(&right_entries);
1409            let mut taken = 0;
1410            for entry in &right_entries {
1411                let moved = leaf_entry_size(entry);
1412                let right_after = right_size - moved;
1413                if right_after < min_bytes
1414                    || (leaf_size >= min_bytes && leaf_size + moved > right_after)
1415                {
1416                    break;
1417                }
1418                leaf_size += moved;
1419                right_size = right_after;
1420                taken += 1;
1421            }
1422            let borrowed = taken > 0;
1423            if borrowed {
1424                leaf_entries.extend(right_entries.drain(..taken));
1425            }
1426
1427            if borrowed {
1428                write_leaf_entries(&mut right, &right_entries)?;
1429                right.update_checksum();
1430                self.pager.write_page(right_id, right)?;
1431
1432                write_leaf_entries(&mut leaf, &leaf_entries)?;
1433                leaf.update_checksum();
1434                self.pager.write_page(leaf_id, leaf)?;
1435
1436                if let Some((first_key, _)) = right_entries.first() {
1437                    parent_keys[child_index] = first_key.clone();
1438                    write_interior_entries(&mut parent, &parent_keys, &parent_children)?;
1439                    parent.update_checksum();
1440                    self.pager.write_page(parent_id, parent)?;
1441                }
1442
1443                return Ok(None);
1444            }
1445        }
1446
1447        if child_index > 0 {
1448            let left_id = parent_children[child_index - 1];
1449            let mut left = self.pager.read_page(left_id)?;
1450            let mut left_entries = read_leaf_entries(&left)?;
1451
1452            left_entries.extend(leaf_entries);
1453            write_leaf_entries(&mut left, &left_entries)?;
1454
1455            let next_leaf = read_next_leaf(&leaf);
1456            set_next_leaf(&mut left, next_leaf);
1457            if next_leaf != 0 {
1458                let mut next = self.pager.read_page(next_leaf)?;
1459                set_prev_leaf(&mut next, left_id);
1460                next.update_checksum();
1461                self.pager.write_page(next_leaf, next)?;
1462            }
1463
1464            left.update_checksum();
1465            self.pager.write_page(left_id, left)?;
1466            self.pager.free_page(leaf_id)?;
1467
1468            parent_keys.remove(child_index - 1);
1469            parent_children.remove(child_index);
1470            write_interior_entries(&mut parent, &parent_keys, &parent_children)?;
1471            parent.update_checksum();
1472            self.pager.write_page(parent_id, parent)?;
1473
1474            return Ok(Some(parent_id));
1475        }
1476
1477        if child_index + 1 < parent_children.len() {
1478            let right_id = parent_children[child_index + 1];
1479            let right = self.pager.read_page(right_id)?;
1480            let right_entries = read_leaf_entries(&right)?;
1481
1482            leaf_entries.extend(right_entries);
1483            write_leaf_entries(&mut leaf, &leaf_entries)?;
1484
1485            let next_leaf = read_next_leaf(&right);
1486            set_next_leaf(&mut leaf, next_leaf);
1487            if next_leaf != 0 {
1488                let mut next = self.pager.read_page(next_leaf)?;
1489                set_prev_leaf(&mut next, leaf_id);
1490                next.update_checksum();
1491                self.pager.write_page(next_leaf, next)?;
1492            }
1493
1494            leaf.update_checksum();
1495            self.pager.write_page(leaf_id, leaf)?;
1496            self.pager.free_page(right_id)?;
1497
1498            parent_keys.remove(child_index);
1499            parent_children.remove(child_index + 1);
1500            write_interior_entries(&mut parent, &parent_keys, &parent_children)?;
1501            parent.update_checksum();
1502            self.pager.write_page(parent_id, parent)?;
1503
1504            return Ok(Some(parent_id));
1505        }
1506
1507        Ok(None)
1508    }
1509
1510    fn rebalance_interior(&self, mut node_id: u32, mut path: Vec<u32>) -> BTreeResult<()> {
1511        // Each completed step releases its page buffers before the next level.
1512        while let Some(parent_id) = self.rebalance_interior_step(node_id, &mut path)? {
1513            node_id = parent_id;
1514        }
1515        Ok(())
1516    }
1517
1518    fn rebalance_interior_step(
1519        &self,
1520        node_id: u32,
1521        path: &mut Vec<u32>,
1522    ) -> BTreeResult<Option<u32>> {
1523        let root_id = self.root_page_id();
1524        let mut node = self.pager.read_page(node_id)?;
1525        let (mut node_keys, mut node_children) = read_interior_keys_children(&node)?;
1526        let min_bytes = interior_min_bytes();
1527
1528        if node_id == root_id {
1529            if node_keys.is_empty() {
1530                let next_root = node_children.first().copied().unwrap_or(0);
1531                self.pager.free_page(node_id)?;
1532                *self.root_page_id.write().map_err(|e| {
1533                    BTreeError::LockPoisoned(format!(
1534                        "rebalance_interior: root_page_id write lock: {e}"
1535                    ))
1536                })? = next_root;
1537            }
1538            return Ok(None);
1539        }
1540
1541        if interior_entries_size(&node_keys) >= min_bytes {
1542            return Ok(None);
1543        }
1544
1545        let parent_id = match path.pop() {
1546            Some(id) => id,
1547            None => return Ok(None),
1548        };
1549        let mut parent = self.pager.read_page(parent_id)?;
1550        let (mut parent_keys, mut parent_children) = read_interior_keys_children(&parent)?;
1551
1552        let child_index = parent_children
1553            .iter()
1554            .position(|&id| id == node_id)
1555            .ok_or_else(|| BTreeError::Corrupted("Interior missing from parent".into()))?;
1556
1557        if child_index > 0 {
1558            let left_id = parent_children[child_index - 1];
1559            let mut left = self.pager.read_page(left_id)?;
1560            let (mut left_keys, mut left_children) = read_interior_keys_children(&left)?;
1561
1562            if let Some(borrow_key) = left_keys.last().cloned() {
1563                let borrow_size = interior_key_size(&borrow_key);
1564                if interior_entries_size(&left_keys).saturating_sub(borrow_size) >= min_bytes {
1565                    let parent_key = parent_keys[child_index - 1].clone();
1566                    let borrowed_key = left_keys.pop().ok_or_else(|| {
1567                        BTreeError::Corrupted(
1568                            "rebalance_interior: left_keys empty after check".into(),
1569                        )
1570                    })?;
1571                    let borrowed_child = left_children.pop().ok_or_else(|| {
1572                        BTreeError::Corrupted("rebalance_interior: left_children empty".into())
1573                    })?;
1574
1575                    node_keys.insert(0, parent_key);
1576                    node_children.insert(0, borrowed_child);
1577                    parent_keys[child_index - 1] = borrowed_key;
1578
1579                    write_interior_entries(&mut left, &left_keys, &left_children)?;
1580                    left.update_checksum();
1581                    self.pager.write_page(left_id, left)?;
1582
1583                    write_interior_entries(&mut node, &node_keys, &node_children)?;
1584                    node.update_checksum();
1585                    self.pager.write_page(node_id, node)?;
1586
1587                    write_interior_entries(&mut parent, &parent_keys, &parent_children)?;
1588                    parent.update_checksum();
1589                    self.pager.write_page(parent_id, parent)?;
1590
1591                    return Ok(None);
1592                }
1593            }
1594        }
1595
1596        if child_index + 1 < parent_children.len() {
1597            let right_id = parent_children[child_index + 1];
1598            let mut right = self.pager.read_page(right_id)?;
1599            let (mut right_keys, mut right_children) = read_interior_keys_children(&right)?;
1600
1601            if let Some(borrow_key) = right_keys.first().cloned() {
1602                let borrow_size = interior_key_size(&borrow_key);
1603                if interior_entries_size(&right_keys).saturating_sub(borrow_size) >= min_bytes {
1604                    let parent_key = parent_keys[child_index].clone();
1605                    let new_parent_key = right_keys.remove(0);
1606                    let borrowed_child = right_children.remove(0);
1607
1608                    node_keys.push(parent_key);
1609                    node_children.push(borrowed_child);
1610                    parent_keys[child_index] = new_parent_key;
1611
1612                    write_interior_entries(&mut right, &right_keys, &right_children)?;
1613                    right.update_checksum();
1614                    self.pager.write_page(right_id, right)?;
1615
1616                    write_interior_entries(&mut node, &node_keys, &node_children)?;
1617                    node.update_checksum();
1618                    self.pager.write_page(node_id, node)?;
1619
1620                    write_interior_entries(&mut parent, &parent_keys, &parent_children)?;
1621                    parent.update_checksum();
1622                    self.pager.write_page(parent_id, parent)?;
1623
1624                    return Ok(None);
1625                }
1626            }
1627        }
1628
1629        if child_index > 0 {
1630            let left_id = parent_children[child_index - 1];
1631            let mut left = self.pager.read_page(left_id)?;
1632            let (mut left_keys, mut left_children) = read_interior_keys_children(&left)?;
1633            let parent_key = parent_keys.remove(child_index - 1);
1634            parent_children.remove(child_index);
1635
1636            left_keys.push(parent_key);
1637            left_keys.extend(node_keys);
1638            left_children.extend(node_children);
1639
1640            write_interior_entries(&mut left, &left_keys, &left_children)?;
1641            left.update_checksum();
1642            self.pager.write_page(left_id, left)?;
1643            self.pager.free_page(node_id)?;
1644
1645            write_interior_entries(&mut parent, &parent_keys, &parent_children)?;
1646            parent.update_checksum();
1647            self.pager.write_page(parent_id, parent)?;
1648
1649            return Ok(Some(parent_id));
1650        }
1651
1652        if child_index + 1 < parent_children.len() {
1653            let right_id = parent_children[child_index + 1];
1654            let right = self.pager.read_page(right_id)?;
1655            let (right_keys, right_children) = read_interior_keys_children(&right)?;
1656            let parent_key = parent_keys.remove(child_index);
1657            parent_children.remove(child_index + 1);
1658
1659            node_keys.push(parent_key);
1660            node_keys.extend(right_keys);
1661            node_children.extend(right_children);
1662
1663            write_interior_entries(&mut node, &node_keys, &node_children)?;
1664            node.update_checksum();
1665            self.pager.write_page(node_id, node)?;
1666            self.pager.free_page(right_id)?;
1667
1668            write_interior_entries(&mut parent, &parent_keys, &parent_children)?;
1669            parent.update_checksum();
1670            self.pager.write_page(parent_id, parent)?;
1671
1672            return Ok(Some(parent_id));
1673        }
1674
1675        Ok(None)
1676    }
1677}