Skip to main content

reddb_engine/storage/
btree.rs

1//! B+ Tree Implementation for Page-Based Storage
2//!
3//! A B+ tree optimized for disk I/O with the following properties:
4//! - All values stored in leaf nodes
5//! - Interior nodes only contain keys and child pointers
6//! - Leaf nodes form a doubly-linked list for range scans
7//! - Each node fits in a single 16 KiB page
8//!
9//! # Page Layout
10//!
11//! Interior Node:
12//! ```text
13//! ┌────────────────────────────────────────────────────────────┐
14//! │ PageHeader (32 bytes)                                      │
15//! ├────────────────────────────────────────────────────────────┤
16//! │ right_child: u32 - Rightmost child pointer                 │
17//! │ cells: [key_len: u16, key: [u8], child: u32]...           │
18//! └────────────────────────────────────────────────────────────┘
19//! ```
20//!
21//! Leaf Node:
22//! ```text
23//! ┌────────────────────────────────────────────────────────────┐
24//! │ PageHeader (32 bytes)                                      │
25//! ├────────────────────────────────────────────────────────────┤
26//! │ prev_leaf: u32 - Previous leaf (0 = none)                  │
27//! │ next_leaf: u32 - Next leaf (0 = none)                      │
28//! │ cells: [key_len: u16, val_len: u16, key: [u8], val: [u8]] │
29//! └────────────────────────────────────────────────────────────┘
30//! ```
31
32use std::cmp::Ordering;
33use std::sync::{Arc, RwLock};
34
35use super::page::{Page, PageType, HEADER_SIZE, PAGE_SIZE};
36use super::page_store::PageStore;
37use super::pager::PagerError;
38
39/// Maximum key size (to ensure at least 2 keys per node)
40pub const MAX_KEY_SIZE: usize = 1024;
41
42/// Hard upper bound on logical value size.
43///
44/// Per ADR 0023 (large-value overflow), values up to 256 MiB are stored
45/// transparently — inline below [`value_layout::OVERFLOW_THRESHOLD`],
46/// inline+compressed when LZ4 shrinks them under the same threshold, or
47/// spilled into an [`overflow::OverflowChain`] otherwise. Values above
48/// this ceiling are rejected with [`BTreeError::ValueTooLarge`] before
49/// any compression or page allocation runs.
50///
51/// Re-exported from [`value_layout::MAX_VALUE_SIZE`] so callers that
52/// historically read this constant (`unified::store::impl_pages`,
53/// `query::planner::stats_catalog`) continue to compile.
54pub const MAX_VALUE_SIZE: usize = value_layout::MAX_VALUE_SIZE;
55
56/// Minimum fill factor before merge (as percentage)
57pub const MIN_FILL_FACTOR: usize = 25;
58
59/// Offset of prev_leaf in leaf page
60const LEAF_PREV_OFFSET: usize = HEADER_SIZE;
61
62/// Offset of next_leaf in leaf page
63const LEAF_NEXT_OFFSET: usize = HEADER_SIZE + 4;
64
65/// Start of the slot array in leaf pages.
66///
67/// Slotted-page layout:
68/// ```text
69/// [PageHeader 32B][prev u32 | next u32 | 8B]
70/// [slot 0: u16][slot 1: u16]...[slot N-1: u16]  ← grows forward
71/// ... free space ...
72/// [cell N-1][cell N-2]...[cell 0]               ← grows backward from free_end
73/// ```
74/// Each cell is laid out as `[key_len:u16][val_len:u16][key][val]`.
75/// `page.cell_count()` is N; `page.free_end()` is the offset of the
76/// lowest (most recently written) cell. The slot array lives right
77/// after the leaf-chain links and each u16 slot is the absolute page
78/// offset of its cell.
79const LEAF_SLOT_ARRAY_OFFSET: usize = HEADER_SIZE + 8;
80
81// A split must still fit two maximum-key inline cells, including the value
82// flag, cell headers and slot pointers, after the native page-size change.
83const _: () = assert!(
84    2 * (MAX_KEY_SIZE + value_layout::OVERFLOW_THRESHOLD + 1 + 4 + 2)
85        <= PAGE_SIZE - LEAF_SLOT_ARRAY_OFFSET
86);
87
88/// Kept for source-compat with older code paths (e.g. interior-node
89/// helpers); equivalent to `LEAF_SLOT_ARRAY_OFFSET` for leaves.
90const LEAF_DATA_OFFSET: usize = LEAF_SLOT_ARRAY_OFFSET;
91
92/// Start of cell data in interior pages (right_child is in header)
93const INTERIOR_DATA_OFFSET: usize = HEADER_SIZE;
94
95/// B+ Tree error types
96#[derive(Debug, Clone)]
97pub enum BTreeError {
98    /// Key not found
99    NotFound,
100    /// Key already exists
101    DuplicateKey,
102    /// Key too large
103    KeyTooLarge(usize),
104    /// Value too large
105    ValueTooLarge(usize),
106    /// Tree is corrupted
107    Corrupted(String),
108    /// Pager error
109    Pager(String),
110    /// Internal lock was poisoned by a panicked thread
111    LockPoisoned(String),
112    /// Large-value layout encode/decode failed (overflow chain or LZ4).
113    ValueLayout(String),
114    /// Materializing a value would exceed the caller's read memory allowance.
115    ReadLimitExceeded {
116        required_bytes: usize,
117        limit_bytes: usize,
118    },
119}
120
121impl std::fmt::Display for BTreeError {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        match self {
124            Self::NotFound => write!(f, "Key not found"),
125            Self::DuplicateKey => write!(f, "Key already exists"),
126            Self::KeyTooLarge(size) => {
127                write!(f, "Key too large: {} bytes (max {})", size, MAX_KEY_SIZE)
128            }
129            Self::ValueTooLarge(size) => write!(
130                f,
131                "Value too large: {} bytes (max {})",
132                size, MAX_VALUE_SIZE
133            ),
134            Self::Corrupted(msg) => write!(f, "B-tree corrupted: {}", msg),
135            Self::Pager(msg) => write!(f, "Pager error: {}", msg),
136            Self::LockPoisoned(msg) => write!(f, "Lock poisoned: {}", msg),
137            Self::ValueLayout(msg) => write!(f, "Value layout: {}", msg),
138            Self::ReadLimitExceeded {
139                required_bytes,
140                limit_bytes,
141            } => write!(
142                f,
143                "B-tree read needs {required_bytes} bytes over read memory limit {limit_bytes}"
144            ),
145        }
146    }
147}
148
149impl From<value_layout::ValueLayoutError> for BTreeError {
150    fn from(e: value_layout::ValueLayoutError) -> Self {
151        match e {
152            value_layout::ValueLayoutError::ValueTooLarge(n) => Self::ValueTooLarge(n),
153            value_layout::ValueLayoutError::ReadLimitExceeded {
154                required_bytes,
155                limit_bytes,
156            } => Self::ReadLimitExceeded {
157                required_bytes,
158                limit_bytes,
159            },
160            other => Self::ValueLayout(other.to_string()),
161        }
162    }
163}
164
165impl std::error::Error for BTreeError {}
166
167impl From<PagerError> for BTreeError {
168    fn from(e: PagerError) -> Self {
169        Self::Pager(e.to_string())
170    }
171}
172
173impl From<super::page::PageError> for BTreeError {
174    fn from(e: super::page::PageError) -> Self {
175        Self::Corrupted(e.to_string())
176    }
177}
178
179/// Result type for B+ tree operations
180pub type BTreeResult<T> = Result<T, BTreeError>;
181
182/// B+ Tree cursor for iteration
183pub struct BTreeCursor<P: PageStore> {
184    /// A cursor can outlive the tree handle that created it.
185    _retirement_pin: Arc<()>,
186    /// Current leaf page ID
187    leaf_page_id: u32,
188    /// Current position within leaf
189    position: usize,
190    /// Pager reference
191    pager: Arc<page_proofs::TreePageStore<P>>,
192    /// A6 — true once we've issued a prefetch hint for the next leaf on
193    /// this leaf. Reset to false every time we move to a new leaf so the
194    /// hint fires once per leaf, at the halfway point.
195    prefetched_next: bool,
196    /// Published collection generations are immutable. Retain at most one
197    /// leaf while walking them; mutable-tree cursors keep re-reading pages.
198    immutable: bool,
199    immutable_leaf: Option<Box<Page>>,
200}
201
202/// Point lookups in ascending key order that keep the leaf of the last one.
203///
204/// `get` walks from the root for every key. A checkpoint asks about
205/// thousands of keys of one tree in order, most of them neighbours: this
206/// answers from the leaf in hand while the next key can only be there.
207/// It reads the tree as each leaf was when it was read, so it is for a caller
208/// that owns the tree's writes while it asks, as a checkpoint does.
209pub struct SortedProbe<'a, P: PageStore> {
210    tree: &'a BTree<P>,
211    leaf: Option<Page>,
212    last: Vec<u8>,
213}
214
215impl<P: PageStore> SortedProbe<'_, P> {
216    /// The value under `key`, which is not lower than the previous call's.
217    pub fn get(&mut self, key: &[u8], limit_bytes: usize) -> BTreeResult<Option<Vec<u8>>> {
218        if !self.holds(key)? {
219            self.leaf = self.tree.leaf_for(key)?;
220        }
221        let Some(page) = &self.leaf else {
222            return Ok(None);
223        };
224        match search_leaf(page, key)? {
225            SearchResult::Found(position) => {
226                let (_, stored) = read_leaf_cell_borrowed(page, position)?;
227                Ok(Some(value_layout::decode_with_budget(
228                    self.tree.pager.as_ref(),
229                    stored,
230                    limit_bytes,
231                )?))
232            }
233            SearchResult::NotFound(_) => Ok(None),
234        }
235    }
236
237    /// Whether `key` is in the tree; see [`Self::get`] for the order of keys.
238    pub fn contains(&mut self, key: &[u8]) -> BTreeResult<bool> {
239        if !self.holds(key)? {
240            self.leaf = self.tree.leaf_for(key)?;
241        }
242        Ok(match &self.leaf {
243            Some(page) => matches!(search_leaf(page, key)?, SearchResult::Found(_)),
244            None => false,
245        })
246    }
247
248    /// Whether the leaf in hand is the only one `key` can be in. Keys ascend,
249    /// so `key` is not before this leaf; it is not after it if the leaf holds
250    /// a key at least as high, or is the last one. A key that does not ascend
251    /// is looked up from the root like any first one.
252    fn holds(&mut self, key: &[u8]) -> BTreeResult<bool> {
253        let ascends = key >= self.last.as_slice();
254        self.last.clear();
255        self.last.extend_from_slice(key);
256        match &self.leaf {
257            Some(page) if ascends => leaf_holds_ascending(page, key),
258            _ => Ok(false),
259        }
260    }
261}
262
263/// Whether `key`, not lower than a key already routed to `page`, belongs to
264/// that leaf too: the leaf has a key at least as high, or no leaf follows it.
265fn leaf_holds_ascending(page: &Page, key: &[u8]) -> BTreeResult<bool> {
266    if leaf_right_sibling(page) == 0 {
267        return Ok(true);
268    }
269    let cells = usize::from(page.cell_count());
270    Ok(cells > 0 && key <= read_leaf_cell_borrowed(page, cells - 1)?.0)
271}
272
273impl<P: PageStore> BTreeCursor<P> {
274    /// Copy the position of an immutable cursor without advancing the original.
275    pub(crate) fn fork_immutable(&self) -> Self {
276        assert!(self.immutable, "only immutable cursors may be forked");
277        Self {
278            _retirement_pin: Arc::clone(&self._retirement_pin),
279            leaf_page_id: self.leaf_page_id,
280            position: self.position,
281            pager: Arc::clone(&self.pager),
282            prefetched_next: self.prefetched_next,
283            immutable: true,
284            immutable_leaf: self.immutable_leaf.clone(),
285        }
286    }
287
288    /// Only collection readers whose host pins an immutable published root
289    /// may retain a leaf across calls. This is not a mutable-tree snapshot.
290    pub(crate) fn with_immutable_leaves(mut self) -> Self {
291        self.immutable = true;
292        self
293    }
294
295    fn prepare_immutable_leaf(&mut self) -> BTreeResult<bool> {
296        if self.leaf_page_id == 0 {
297            return Ok(false);
298        }
299        if self.immutable_leaf.is_none() {
300            let page = self.pager.read_page(self.leaf_page_id)?;
301            if page.page_type()? != PageType::BTreeLeaf {
302                return Err(BTreeError::Corrupted(
303                    "cursor reached a non-leaf page".into(),
304                ));
305            }
306            self.immutable_leaf = Some(Box::new(page));
307        }
308        let page = self.immutable_leaf.as_ref().expect("loaded immutable leaf");
309        if self.position < usize::from(page.cell_count()) {
310            return Ok(true);
311        }
312        let next = read_next_leaf(page);
313        if next == 0 {
314            self.leaf_page_id = 0;
315            self.immutable_leaf = None;
316            return Ok(false);
317        }
318        let next_page = self.pager.read_page(next)?;
319        if next_page.page_type()? != PageType::BTreeLeaf || next_page.cell_count() == 0 {
320            return Err(BTreeError::Corrupted(
321                "leaf chain reached an invalid leaf".into(),
322            ));
323        }
324        let first_key = read_leaf_cell_borrowed(&next_page, 0)?.0;
325        if leaf_high_key(page)?
326            .as_ref()
327            .is_some_and(|key| first_key <= key.as_slice())
328        {
329            return Err(BTreeError::Corrupted(
330                "leaf chain does not advance its key range".into(),
331            ));
332        }
333        **self.immutable_leaf.as_mut().expect("loaded immutable leaf") = next_page;
334        self.leaf_page_id = next;
335        self.position = 0;
336        self.prefetched_next = false;
337        Ok(true)
338    }
339
340    /// Inspect the next key without materializing its value or advancing.
341    #[cfg(feature = "full")]
342    pub(crate) fn peek_key_with<T>(
343        &mut self,
344        visit: impl FnOnce(&[u8]) -> T,
345    ) -> BTreeResult<Option<T>> {
346        if self.immutable {
347            if !self.prepare_immutable_leaf()? {
348                return Ok(None);
349            }
350            let page = self.immutable_leaf.as_ref().expect("loaded immutable leaf");
351            return Ok(Some(visit(read_leaf_cell_borrowed(page, self.position)?.0)));
352        }
353        let Some(page) = self.prepare_next_leaf()? else {
354            return Ok(None);
355        };
356        Ok(Some(visit(
357            read_leaf_cell_borrowed(&page, self.position)?.0,
358        )))
359    }
360
361    /// Inspect the next key without materializing its value or advancing.
362    pub fn peek_key(&mut self) -> BTreeResult<Option<Vec<u8>>> {
363        if self.immutable {
364            if !self.prepare_immutable_leaf()? {
365                return Ok(None);
366            }
367            let page = self.immutable_leaf.as_ref().expect("loaded immutable leaf");
368            return Ok(Some(
369                read_leaf_cell_borrowed(page, self.position)?.0.to_vec(),
370            ));
371        }
372        let Some(page) = self.prepare_next_leaf()? else {
373            return Ok(None);
374        };
375        Ok(Some(read_leaf_cell(&page, self.position)?.0))
376    }
377
378    /// Skip a shadowed or deleted base record without reading its overflow value.
379    pub fn skip_next(&mut self) -> BTreeResult<bool> {
380        if self.immutable {
381            if !self.prepare_immutable_leaf()? {
382                return Ok(false);
383            }
384            self.position += 1;
385            return Ok(true);
386        }
387        if self.prepare_next_leaf()?.is_none() {
388            return Ok(false);
389        }
390        self.position += 1;
391        Ok(true)
392    }
393
394    fn prepare_next_leaf(&mut self) -> BTreeResult<Option<Page>> {
395        if self.leaf_page_id == 0 {
396            return Ok(None);
397        }
398        let page = self.pager.read_page(self.leaf_page_id)?;
399        if page.page_type()? != PageType::BTreeLeaf {
400            return Err(BTreeError::Corrupted(
401                "cursor reached a non-leaf page".into(),
402            ));
403        }
404        if self.position < usize::from(page.cell_count()) {
405            return Ok(Some(page));
406        }
407        let next = read_next_leaf(&page);
408        if next == 0 {
409            self.leaf_page_id = 0;
410            return Ok(None);
411        }
412        let next_page = self.pager.read_page(next)?;
413        if next_page.page_type()? != PageType::BTreeLeaf || next_page.cell_count() == 0 {
414            return Err(BTreeError::Corrupted(
415                "leaf chain reached an invalid leaf".into(),
416            ));
417        }
418        let first_key = read_leaf_cell(&next_page, 0)?.0;
419        if leaf_high_key(&page)?
420            .as_ref()
421            .is_some_and(|key| first_key <= *key)
422        {
423            return Err(BTreeError::Corrupted(
424                "leaf chain does not advance its key range".into(),
425            ));
426        }
427        self.leaf_page_id = next;
428        self.position = 0;
429        self.prefetched_next = false;
430        Ok(Some(next_page))
431    }
432
433    /// Read one value within the caller's materialization allowance.
434    pub fn next_with_budget(
435        &mut self,
436        limit_bytes: usize,
437    ) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
438        self.next_impl(limit_bytes)
439    }
440
441    /// Move to next entry
442    pub fn next(&mut self) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
443        self.next_impl(usize::MAX)
444    }
445
446    fn next_impl(&mut self, limit_bytes: usize) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
447        if self.immutable {
448            return self.next_immutable(limit_bytes);
449        }
450        if self.leaf_page_id == 0 {
451            return Ok(None);
452        }
453
454        let page = self.pager.read_page(self.leaf_page_id)?;
455        if page.page_type()? != PageType::BTreeLeaf {
456            return Err(BTreeError::Corrupted(
457                "cursor reached a non-leaf page".into(),
458            ));
459        }
460        let cell_count = page.cell_count() as usize;
461
462        // A6 — prefetch the next leaf when we cross the halfway point of
463        // the current one. The hint fires at most once per leaf (guarded
464        // by `prefetched_next`) so the syscall overhead is amortized over
465        // ~half a leaf's worth of entries. The kernel uses the hint to
466        // start DMA-ing the next page while we finish the current one.
467        if !self.prefetched_next && self.position >= cell_count / 2 && cell_count > 0 {
468            let next_leaf = read_next_leaf(&page);
469            if next_leaf != 0 {
470                self.pager.prefetch_hint(next_leaf);
471            }
472            self.prefetched_next = true;
473        }
474
475        // Check if we have more cells in current page
476        if self.position < cell_count {
477            let (key, stored) = read_leaf_cell(&page, self.position)?;
478            let value =
479                value_layout::decode_with_budget(self.pager.as_ref(), &stored, limit_bytes)?;
480            self.position += 1;
481            return Ok(Some((key, value)));
482        }
483
484        // Move to next leaf
485        let next_leaf = read_next_leaf(&page);
486        if next_leaf == 0 {
487            self.leaf_page_id = 0;
488            return Ok(None);
489        }
490        let previous_high_key = leaf_high_key(&page)?;
491
492        self.leaf_page_id = next_leaf;
493        self.position = 0;
494        self.prefetched_next = false; // reset for the new leaf
495
496        // Read from new leaf
497        let page = self.pager.read_page(self.leaf_page_id)?;
498        if page.page_type()? != PageType::BTreeLeaf {
499            return Err(BTreeError::Corrupted(
500                "leaf chain reached a non-leaf page".into(),
501            ));
502        }
503        if page.cell_count() == 0 {
504            return Ok(None);
505        }
506
507        let (key, stored) = read_leaf_cell(&page, 0)?;
508        // Every leaf transition must advance the key range. This bounds a
509        // corrupt cyclic chain without growing a visited-page set or an
510        // unbounded checkpoint buffer (#2376).
511        if previous_high_key
512            .as_ref()
513            .is_some_and(|previous| key <= *previous)
514        {
515            self.leaf_page_id = 0;
516            return Err(BTreeError::Corrupted(
517                "leaf chain does not advance its key range".into(),
518            ));
519        }
520        let value = value_layout::decode_with_budget(self.pager.as_ref(), &stored, limit_bytes)?;
521        self.position = 1;
522        Ok(Some((key, value)))
523    }
524
525    fn next_immutable(&mut self, limit_bytes: usize) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
526        if !self.prepare_immutable_leaf()? {
527            return Ok(None);
528        }
529        let page = self.immutable_leaf.as_ref().expect("loaded immutable leaf");
530        if !self.prefetched_next && self.position >= usize::from(page.cell_count()) / 2 {
531            let next = read_next_leaf(page);
532            if next != 0 {
533                self.pager.prefetch_hint(next);
534            }
535            self.prefetched_next = true;
536        }
537        let (key, stored) = read_leaf_cell_borrowed(page, self.position)?;
538        let value = value_layout::decode_with_budget(self.pager.as_ref(), stored, limit_bytes)?;
539        self.position += 1;
540        Ok(Some((key.to_vec(), value)))
541    }
542
543    /// Peek at current entry without advancing
544    pub fn peek(&self) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
545        if self.leaf_page_id == 0 {
546            return Ok(None);
547        }
548
549        let page = self.pager.read_page(self.leaf_page_id)?;
550        let cell_count = page.cell_count() as usize;
551
552        if self.position >= cell_count {
553            return Ok(None);
554        }
555
556        let (key, stored) = read_leaf_cell(&page, self.position)?;
557        let value = value_layout::decode(self.pager.as_ref(), &stored)?;
558        Ok(Some((key, value)))
559    }
560}
561
562/// B+ Tree implementation
563pub struct BTree<P: PageStore> {
564    retirement_pin: Arc<()>,
565    /// Pager for page I/O
566    pager: Arc<page_proofs::TreePageStore<P>>,
567    /// Root page ID (0 = empty tree)
568    root_page_id: RwLock<u32>,
569    /// D2 fastpath: cached rightmost leaf (page_id, high_key).
570    ///
571    /// When the next key to insert is strictly greater than `high_key`,
572    /// skip `find_leaf` (tree descent from root) and go directly to the
573    /// cached page. Invalidated on splits and deletes.
574    ///
575    /// Mirrors `BTPageCacheIsValid` / `BTREE_FASTPATH_MIN_LEVEL` in
576    /// `nbtinsert.c:31`.
577    rightmost_leaf: RwLock<Option<(u32, Vec<u8>)>>,
578    /// Serialises structural writers (insert / upsert / delete / bulk).
579    ///
580    /// Writers copy a page, modify the copy and write it back, and there
581    /// are no page latches, so two writers on one tree would lose each
582    /// other's leaf updates or tear a split (#2376). Reentrant because the
583    /// public mutators call each other (`upsert` -> `insert`, the bulk
584    /// paths -> `insert_encoded`). Readers do not take it.
585    writer: parking_lot::ReentrantMutex<()>,
586}
587
588#[path = "btree/impl.rs"]
589mod btree_impl;
590
591#[path = "btree/reclaim.rs"]
592mod reclaim;
593
594mod page_proofs;
595
596#[cfg(test)]
597#[path = "btree/read_budget_tests.rs"]
598mod read_budget_tests;
599
600#[path = "btree/lehman_yao.rs"]
601pub mod lehman_yao;
602
603#[path = "btree/value_layout.rs"]
604pub mod value_layout;
605// ==================== Search Helpers ====================
606
607enum SearchResult {
608    Found(usize),
609    NotFound(usize),
610}
611
612fn search_leaf(page: &Page, key: &[u8]) -> BTreeResult<SearchResult> {
613    let cell_count = page.cell_count() as usize;
614
615    // Binary search
616    let mut low = 0;
617    let mut high = cell_count;
618
619    while low < high {
620        let mid = (low + high) / 2;
621        let (cell_key, _) = read_leaf_cell_borrowed(page, mid)?;
622
623        match cell_key.cmp(key) {
624            Ordering::Less => low = mid + 1,
625            Ordering::Greater => high = mid,
626            Ordering::Equal => return Ok(SearchResult::Found(mid)),
627        }
628    }
629
630    Ok(SearchResult::NotFound(low))
631}
632
633fn find_child(page: &Page, key: &[u8]) -> BTreeResult<u32> {
634    // The child of the first separator above `key`. Every descent of every
635    // tree operation comes through here: it used to walk the separators in
636    // order and copy each one it looked at.
637    let mut low = 0;
638    let mut high = page.cell_count() as usize;
639    while low < high {
640        let mid = (low + high) / 2;
641        let (cell_key, _) = read_interior_cell_borrowed(page, mid)?;
642        if key < cell_key {
643            high = mid;
644        } else {
645            low = mid + 1;
646        }
647    }
648    if low < page.cell_count() as usize {
649        return Ok(read_interior_cell_borrowed(page, low)?.1);
650    }
651
652    // Key is >= all keys, use right child
653    Ok(page.right_child())
654}
655
656fn find_first_child(page: &Page) -> BTreeResult<u32> {
657    if page.cell_count() == 0 {
658        return Ok(page.right_child());
659    }
660    let (_, child) = read_interior_cell(page, 0)?;
661    Ok(child)
662}
663
664fn leaf_min_bytes() -> usize {
665    (PAGE_SIZE - LEAF_DATA_OFFSET) * MIN_FILL_FACTOR / 100
666}
667
668fn interior_min_bytes() -> usize {
669    (PAGE_SIZE - INTERIOR_DATA_OFFSET) * MIN_FILL_FACTOR / 100
670}
671
672/// Bytes consumed by one leaf entry in the slotted layout: one u16
673/// slot in the pointer array plus the cell itself (`[key_len:u16]
674/// [val_len:u16][key][val]`).
675fn leaf_entry_size(entry: &(Vec<u8>, Vec<u8>)) -> usize {
676    2 + 4 + entry.0.len() + entry.1.len()
677}
678
679fn leaf_entries_size(entries: &[(Vec<u8>, Vec<u8>)]) -> usize {
680    entries.iter().map(leaf_entry_size).sum()
681}
682
683/// What `leaf_entries_size` returns for the page's entries, read from the
684/// slots without copying a cell.
685fn leaf_used_bytes(page: &Page) -> BTreeResult<usize> {
686    let mut bytes = 0;
687    for index in 0..page.cell_count() as usize {
688        let (key, value) = read_leaf_cell_borrowed(page, index)?;
689        bytes += 2 + 4 + key.len() + value.len();
690    }
691    Ok(bytes)
692}
693
694#[inline]
695fn leaf_slot_offset_for(index: usize) -> usize {
696    LEAF_SLOT_ARRAY_OFFSET + index * 2
697}
698
699#[inline]
700fn leaf_read_slot(page: &Page, index: usize) -> BTreeResult<usize> {
701    let data = page.as_bytes();
702    let slot_pos = leaf_slot_offset_for(index);
703    if slot_pos + 2 > PAGE_SIZE {
704        return Err(BTreeError::Corrupted("slot array overflows page".into()));
705    }
706    Ok(u16::from_le_bytes([data[slot_pos], data[slot_pos + 1]]) as usize)
707}
708
709#[inline]
710fn leaf_write_slot(page: &mut Page, index: usize, cell_offset: u16) -> BTreeResult<()> {
711    let data = page.as_bytes_mut();
712    let slot_pos = leaf_slot_offset_for(index);
713    if slot_pos + 2 > PAGE_SIZE {
714        return Err(BTreeError::Corrupted("slot array overflows page".into()));
715    }
716    data[slot_pos..slot_pos + 2].copy_from_slice(&cell_offset.to_le_bytes());
717    Ok(())
718}
719
720#[inline]
721fn leaf_slots_end(page: &Page) -> usize {
722    LEAF_SLOT_ARRAY_OFFSET + (page.cell_count() as usize) * 2
723}
724
725#[inline]
726fn leaf_cells_start(page: &Page) -> usize {
727    let end = page.free_end() as usize;
728    if end == 0 {
729        PAGE_SIZE
730    } else {
731        end
732    }
733}
734
735#[inline]
736fn leaf_free_bytes(page: &Page) -> usize {
737    let slot_end = leaf_slots_end(page);
738    let cells = leaf_cells_start(page);
739    cells.saturating_sub(slot_end)
740}
741
742fn interior_key_size(key: &[u8]) -> usize {
743    2 + key.len() + 4
744}
745
746fn interior_entries_size(keys: &[Vec<u8>]) -> usize {
747    keys.iter().map(|k| interior_key_size(k)).sum()
748}
749
750// ==================== Leaf Page Helpers ====================
751
752/// Read the cell at slot `index` in O(1). Follows the u16 slot pointer
753/// into the cell data area; the cell header is `[key_len:u16][val_len:u16]`
754/// followed by the raw key and value bytes.
755fn read_leaf_cell(page: &Page, index: usize) -> BTreeResult<(Vec<u8>, Vec<u8>)> {
756    let (key, value) = read_leaf_cell_borrowed(page, index)?;
757    Ok((key.to_vec(), value.to_vec()))
758}
759
760fn read_leaf_cell_borrowed(page: &Page, index: usize) -> BTreeResult<(&[u8], &[u8])> {
761    let cell_count = page.cell_count() as usize;
762    if index >= cell_count {
763        return Err(BTreeError::Corrupted("Cell index out of range".into()));
764    }
765    let offset = leaf_read_slot(page, index)?;
766    let data = page.as_bytes();
767    if offset + 4 > PAGE_SIZE {
768        return Err(BTreeError::Corrupted("cell header out of range".into()));
769    }
770    let key_len = u16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
771    let val_len = u16::from_le_bytes([data[offset + 2], data[offset + 3]]) as usize;
772    let end = offset + 4 + key_len + val_len;
773    if end > PAGE_SIZE {
774        return Err(BTreeError::Corrupted("cell body out of range".into()));
775    }
776    let key = &data[offset + 4..offset + 4 + key_len];
777    let value = &data[offset + 4 + key_len..end];
778    Ok((key, value))
779}
780
781fn read_leaf_entries(page: &Page) -> BTreeResult<Vec<(Vec<u8>, Vec<u8>)>> {
782    let cell_count = page.cell_count() as usize;
783    let mut entries = Vec::with_capacity(cell_count);
784    for i in 0..cell_count {
785        entries.push(read_leaf_cell(page, i)?);
786    }
787    Ok(entries)
788}
789
790/// Wipe and re-lay an entire leaf in slotted form. Used by the split
791/// path (which hands us a pre-sorted `entries` vector) and by
792/// `clear_leaf_cells` under the hood. Entries are appended at the end
793/// of the free area so the highest-index slot ends up at the lowest
794/// offset — same shape the single-key insert path produces.
795fn write_leaf_entries(page: &mut Page, entries: &[(Vec<u8>, Vec<u8>)]) -> BTreeResult<()> {
796    clear_leaf_cells(page);
797    for (i, (k, v)) in entries.iter().enumerate() {
798        let cell_size = 4 + k.len() + v.len();
799        let cells_start = leaf_cells_start(page);
800        let slot_end = LEAF_SLOT_ARRAY_OFFSET + (i + 1) * 2;
801        if slot_end + cell_size > cells_start {
802            return Err(BTreeError::Corrupted("leaf rebuild overflowed page".into()));
803        }
804        let cell_offset = cells_start - cell_size;
805        {
806            let data = page.as_bytes_mut();
807            data[cell_offset..cell_offset + 2].copy_from_slice(&(k.len() as u16).to_le_bytes());
808            data[cell_offset + 2..cell_offset + 4].copy_from_slice(&(v.len() as u16).to_le_bytes());
809            data[cell_offset + 4..cell_offset + 4 + k.len()].copy_from_slice(k);
810            data[cell_offset + 4 + k.len()..cell_offset + 4 + k.len() + v.len()].copy_from_slice(v);
811        }
812        page.set_free_end(cell_offset as u16);
813        leaf_write_slot(page, i, cell_offset as u16)?;
814    }
815    page.set_cell_count(entries.len() as u16);
816    page.set_free_start((LEAF_SLOT_ARRAY_OFFSET + entries.len() * 2) as u16);
817    Ok(())
818}
819
820fn can_insert_leaf(page: &Page, key: &[u8], value: &[u8]) -> bool {
821    let needed = 2 + 4 + key.len() + value.len();
822    leaf_free_bytes(page) >= needed
823}
824
825/// Insert `(key, value)` into the slotted leaf in O(log M) search +
826/// O(M) slot-array memmove. Cell data is appended at the tail of the
827/// free area (backward from `free_end`); the slot pointer is inserted
828/// Overwrite the value portion of cell at `index` in-place. Valid when
829/// `new_value.len() <= existing_value.len()` — the caller
830/// (typically `BTree::upsert`) checks this before calling.
831///
832/// Same-length writes are trivial (byte copy). Shrinks update the cell's
833/// `v_len` header and leave the trailing bytes as dead space until the
834/// page is naturally rewritten; the slotted layout keeps cells
835/// addressable by their own offset+len so the gap is harmless.
836///
837/// Fixed-size column updates (SET score = X on a typed schema) hit this
838/// path, avoiding the delete + re-insert + rebalance cycle that
839/// dominates bulk_update.
840pub(crate) fn overwrite_leaf_value(
841    page: &mut Page,
842    index: usize,
843    new_value: &[u8],
844) -> BTreeResult<()> {
845    let cell_offset = leaf_read_slot(page, index)?;
846    let data = page.as_bytes();
847    if cell_offset + 4 > data.len() {
848        return Err(BTreeError::Corrupted(
849            "leaf cell header out of bounds".into(),
850        ));
851    }
852    let k_len = u16::from_le_bytes([data[cell_offset], data[cell_offset + 1]]) as usize;
853    let old_v_len = u16::from_le_bytes([data[cell_offset + 2], data[cell_offset + 3]]) as usize;
854    if new_value.len() > old_v_len {
855        return Err(BTreeError::Corrupted(
856            "overwrite_leaf_value: new value larger than slot".into(),
857        ));
858    }
859    let value_start = cell_offset + 4 + k_len;
860    if value_start + new_value.len() > data.len() {
861        return Err(BTreeError::Corrupted(
862            "leaf cell value out of bounds".into(),
863        ));
864    }
865    let data = page.as_bytes_mut();
866    // Update the v_len header if the value shrank. read_leaf_cell reads
867    // v_len from this header so the shortened value deserializes correctly.
868    if new_value.len() != old_v_len {
869        let new_len = new_value.len() as u16;
870        data[cell_offset + 2..cell_offset + 4].copy_from_slice(&new_len.to_le_bytes());
871    }
872    data[value_start..value_start + new_value.len()].copy_from_slice(new_value);
873    Ok(())
874}
875
876/// at the sorted position.
877fn insert_into_leaf(page: &mut Page, key: &[u8], value: &[u8]) -> BTreeResult<()> {
878    // 1. Binary search the slot array to find the insertion index.
879    let cell_count = page.cell_count() as usize;
880    let mut low = 0;
881    let mut high = cell_count;
882    while low < high {
883        let mid = (low + high) / 2;
884        let (cell_key, _) = read_leaf_cell_borrowed(page, mid)?;
885        match cell_key.cmp(key) {
886            Ordering::Less => low = mid + 1,
887            Ordering::Greater => high = mid,
888            Ordering::Equal => {
889                // Duplicate keys are tolerated by the B-tree (caller
890                // decides semantics); append after the existing run.
891                low = mid + 1;
892                break;
893            }
894        }
895    }
896    let insert_pos = low;
897
898    // 2. Reserve the cell at the tail of the free area.
899    let cell_size = 4 + key.len() + value.len();
900    let slot_end_after = LEAF_SLOT_ARRAY_OFFSET + (cell_count + 1) * 2;
901    let cells_start = leaf_cells_start(page);
902    if slot_end_after + cell_size > cells_start {
903        return Err(BTreeError::Corrupted("leaf page full".into()));
904    }
905    let cell_offset = cells_start - cell_size;
906    {
907        let data = page.as_bytes_mut();
908        data[cell_offset..cell_offset + 2].copy_from_slice(&(key.len() as u16).to_le_bytes());
909        data[cell_offset + 2..cell_offset + 4].copy_from_slice(&(value.len() as u16).to_le_bytes());
910        data[cell_offset + 4..cell_offset + 4 + key.len()].copy_from_slice(key);
911        data[cell_offset + 4 + key.len()..cell_offset + 4 + key.len() + value.len()]
912            .copy_from_slice(value);
913    }
914    page.set_free_end(cell_offset as u16);
915
916    // 3. Shift the slot-array tail right by one slot, then write the
917    //    new pointer into the freed slot. This is a single memmove on
918    //    a couple dozen u16s — far cheaper than the O(M²) rebuild.
919    {
920        let shift_from = leaf_slot_offset_for(insert_pos);
921        let shift_to = shift_from + 2;
922        let shift_len = (cell_count - insert_pos) * 2;
923        if shift_len > 0 {
924            let data = page.as_bytes_mut();
925            data.copy_within(shift_from..shift_from + shift_len, shift_to);
926        }
927    }
928    leaf_write_slot(page, insert_pos, cell_offset as u16)?;
929
930    // 4. Bump counters.
931    page.set_cell_count((cell_count + 1) as u16);
932    page.set_free_start((LEAF_SLOT_ARRAY_OFFSET + (cell_count + 1) * 2) as u16);
933    Ok(())
934}
935
936/// Remove the slot at `index`. Cell bytes are left in place (lazy
937/// compaction); the slot-array tail is shifted left to close the gap.
938/// The caller is expected to call `clear_leaf_cells` + rebuild if the
939/// page wants its free space reclaimed.
940fn delete_from_leaf(page: &mut Page, index: usize) -> BTreeResult<()> {
941    let cell_count = page.cell_count() as usize;
942    if index >= cell_count {
943        return Err(BTreeError::Corrupted("delete index out of range".into()));
944    }
945    if index + 1 < cell_count {
946        let shift_from = leaf_slot_offset_for(index + 1);
947        let shift_to = leaf_slot_offset_for(index);
948        let shift_len = (cell_count - index - 1) * 2;
949        let data = page.as_bytes_mut();
950        data.copy_within(shift_from..shift_from + shift_len, shift_to);
951    }
952    page.set_cell_count((cell_count - 1) as u16);
953    page.set_free_start((LEAF_SLOT_ARRAY_OFFSET + (cell_count - 1) * 2) as u16);
954    Ok(())
955}
956
957/// Reset the leaf to an empty slotted state — cell count 0, free
958/// cursors at the extremes. Zeroes the slot array + cell data area so
959/// stale bytes never leak through a corrupted read.
960fn clear_leaf_cells(page: &mut Page) {
961    {
962        let data = page.as_bytes_mut();
963        for byte in &mut data[LEAF_SLOT_ARRAY_OFFSET..] {
964            *byte = 0;
965        }
966    }
967    page.set_cell_count(0);
968    page.set_free_start(LEAF_SLOT_ARRAY_OFFSET as u16);
969    page.set_free_end(PAGE_SIZE as u16);
970}
971
972fn init_leaf_links(page: &mut Page, prev: u32, next: u32) {
973    let data = page.as_bytes_mut();
974    data[LEAF_PREV_OFFSET..LEAF_PREV_OFFSET + 4].copy_from_slice(&prev.to_le_bytes());
975    data[LEAF_NEXT_OFFSET..LEAF_NEXT_OFFSET + 4].copy_from_slice(&next.to_le_bytes());
976}
977
978fn read_next_leaf(page: &Page) -> u32 {
979    let data = page.as_bytes();
980    u32::from_le_bytes([
981        data[LEAF_NEXT_OFFSET],
982        data[LEAF_NEXT_OFFSET + 1],
983        data[LEAF_NEXT_OFFSET + 2],
984        data[LEAF_NEXT_OFFSET + 3],
985    ])
986}
987
988/// Returns the right-sibling page ID for a leaf page.
989/// 0 means this is the rightmost leaf — used by the D2 fastpath cache.
990#[inline]
991fn leaf_right_sibling(page: &Page) -> u32 {
992    read_next_leaf(page)
993}
994
995/// Returns the maximum (last) key stored in a leaf page, or `None` if empty.
996/// This is the Lehman-Yao "high_key" — any key > this value belongs on a
997/// right-sibling page. Reads only the last slot so it is O(1).
998fn leaf_high_key(page: &Page) -> BTreeResult<Option<Vec<u8>>> {
999    let cell_count = page.cell_count() as usize;
1000    if cell_count == 0 {
1001        return Ok(None);
1002    }
1003    let (key, _) = read_leaf_cell(page, cell_count - 1)?;
1004    Ok(Some(key))
1005}
1006
1007fn set_prev_leaf(page: &mut Page, prev: u32) {
1008    let data = page.as_bytes_mut();
1009    data[LEAF_PREV_OFFSET..LEAF_PREV_OFFSET + 4].copy_from_slice(&prev.to_le_bytes());
1010}
1011
1012fn set_next_leaf(page: &mut Page, next: u32) {
1013    let data = page.as_bytes_mut();
1014    data[LEAF_NEXT_OFFSET..LEAF_NEXT_OFFSET + 4].copy_from_slice(&next.to_le_bytes());
1015}
1016
1017// ==================== Interior Page Helpers ====================
1018//
1019// Slotted-page layout mirroring the leaf format:
1020//
1021// ```text
1022// [PageHeader 32B]
1023// [slot 0: u16][slot 1: u16]...[slot N-1: u16]  ← grows forward
1024// ... free space ...
1025// [cell N-1][cell N-2]...[cell 0]               ← grows backward from free_end
1026// ```
1027//
1028// Each cell is `[key_len:u16][key][child:u32]`. The right-most child
1029// pointer lives in `PageHeader.right_child` exactly as before.
1030
1031#[inline]
1032fn interior_slot_offset_for(index: usize) -> usize {
1033    INTERIOR_DATA_OFFSET + index * 2
1034}
1035
1036#[inline]
1037fn interior_read_slot(page: &Page, index: usize) -> BTreeResult<usize> {
1038    let data = page.as_bytes();
1039    let slot_pos = interior_slot_offset_for(index);
1040    if slot_pos + 2 > PAGE_SIZE {
1041        return Err(BTreeError::Corrupted(
1042            "interior slot array overflows page".into(),
1043        ));
1044    }
1045    Ok(u16::from_le_bytes([data[slot_pos], data[slot_pos + 1]]) as usize)
1046}
1047
1048#[inline]
1049fn interior_write_slot(page: &mut Page, index: usize, cell_offset: u16) -> BTreeResult<()> {
1050    let data = page.as_bytes_mut();
1051    let slot_pos = interior_slot_offset_for(index);
1052    if slot_pos + 2 > PAGE_SIZE {
1053        return Err(BTreeError::Corrupted(
1054            "interior slot array overflows page".into(),
1055        ));
1056    }
1057    data[slot_pos..slot_pos + 2].copy_from_slice(&cell_offset.to_le_bytes());
1058    Ok(())
1059}
1060
1061#[inline]
1062fn interior_cells_start(page: &Page) -> usize {
1063    let end = page.free_end() as usize;
1064    if end == 0 {
1065        PAGE_SIZE
1066    } else {
1067        end
1068    }
1069}
1070
1071#[inline]
1072fn interior_free_bytes(page: &Page) -> usize {
1073    let slot_end = INTERIOR_DATA_OFFSET + (page.cell_count() as usize) * 2;
1074    interior_cells_start(page).saturating_sub(slot_end)
1075}
1076
1077fn read_interior_cell(page: &Page, index: usize) -> BTreeResult<(Vec<u8>, u32)> {
1078    let (key, child) = read_interior_cell_borrowed(page, index)?;
1079    Ok((key.to_vec(), child))
1080}
1081
1082/// Where `child` sits among an interior page's children, in the order
1083/// `read_interior_keys_children` lists them, with the separator to its left
1084/// (none for the first child). Copies no key.
1085fn interior_child_slot(page: &Page, child: u32) -> BTreeResult<Option<(usize, Option<&[u8]>)>> {
1086    let cell_count = page.cell_count() as usize;
1087    let mut left = None;
1088    for index in 0..cell_count {
1089        let (key, id) = read_interior_cell_borrowed(page, index)?;
1090        if id == child {
1091            return Ok(Some((index, left)));
1092        }
1093        left = Some(key);
1094    }
1095    let right_child = page.right_child();
1096    if right_child == child && (cell_count > 0 || right_child != 0) {
1097        return Ok(Some((cell_count, left)));
1098    }
1099    Ok(None)
1100}
1101
1102fn read_interior_cell_borrowed(page: &Page, index: usize) -> BTreeResult<(&[u8], u32)> {
1103    let cell_count = page.cell_count() as usize;
1104    if index >= cell_count {
1105        return Err(BTreeError::Corrupted("Cell index out of range".into()));
1106    }
1107    let offset = interior_read_slot(page, index)?;
1108    let data = page.as_bytes();
1109    if offset + 2 > PAGE_SIZE {
1110        return Err(BTreeError::Corrupted(
1111            "interior cell header out of range".into(),
1112        ));
1113    }
1114    let key_len = u16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
1115    let end = offset + 2 + key_len + 4;
1116    if end > PAGE_SIZE {
1117        return Err(BTreeError::Corrupted(
1118            "interior cell body out of range".into(),
1119        ));
1120    }
1121    let key = &data[offset + 2..offset + 2 + key_len];
1122    let child = u32::from_le_bytes([
1123        data[offset + 2 + key_len],
1124        data[offset + 2 + key_len + 1],
1125        data[offset + 2 + key_len + 2],
1126        data[offset + 2 + key_len + 3],
1127    ]);
1128    Ok((key, child))
1129}
1130
1131fn read_interior_keys_children(page: &Page) -> BTreeResult<(Vec<Vec<u8>>, Vec<u32>)> {
1132    let cell_count = page.cell_count() as usize;
1133    let mut keys = Vec::with_capacity(cell_count);
1134    let mut children = Vec::with_capacity(cell_count + 1);
1135
1136    for i in 0..cell_count {
1137        let (key, child) = read_interior_cell(page, i)?;
1138        keys.push(key);
1139        children.push(child);
1140    }
1141
1142    if cell_count == 0 {
1143        let right_child = page.right_child();
1144        if right_child != 0 {
1145            children.push(right_child);
1146        }
1147    } else {
1148        children.push(page.right_child());
1149    }
1150
1151    Ok((keys, children))
1152}
1153
1154/// Bulk-write an interior page from scratch in slotted form. Used by
1155/// the split path. `keys` and `children` follow the B+ tree contract:
1156/// `children.len() == keys.len() + 1`, with the last child landing in
1157/// `PageHeader.right_child` (as before).
1158fn write_interior_entries(page: &mut Page, keys: &[Vec<u8>], children: &[u32]) -> BTreeResult<()> {
1159    if !keys.is_empty() && children.len() != keys.len() + 1 {
1160        return Err(BTreeError::Corrupted(
1161            "Interior keys/children length mismatch".into(),
1162        ));
1163    }
1164
1165    clear_interior_cells(page);
1166    if keys.is_empty() {
1167        let right_child = children.first().copied().unwrap_or(0);
1168        page.set_right_child(right_child);
1169        return Ok(());
1170    }
1171
1172    for (i, key) in keys.iter().enumerate() {
1173        let cell_size = 2 + key.len() + 4;
1174        let cells_start = interior_cells_start(page);
1175        let slot_end = INTERIOR_DATA_OFFSET + (i + 1) * 2;
1176        if slot_end + cell_size > cells_start {
1177            return Err(BTreeError::Corrupted(
1178                "interior rebuild overflowed page".into(),
1179            ));
1180        }
1181        let cell_offset = cells_start - cell_size;
1182        {
1183            let data = page.as_bytes_mut();
1184            data[cell_offset..cell_offset + 2].copy_from_slice(&(key.len() as u16).to_le_bytes());
1185            data[cell_offset + 2..cell_offset + 2 + key.len()].copy_from_slice(key);
1186            data[cell_offset + 2 + key.len()..cell_offset + 2 + key.len() + 4]
1187                .copy_from_slice(&children[i].to_le_bytes());
1188        }
1189        page.set_free_end(cell_offset as u16);
1190        interior_write_slot(page, i, cell_offset as u16)?;
1191    }
1192    page.set_cell_count(keys.len() as u16);
1193    page.set_free_start((INTERIOR_DATA_OFFSET + keys.len() * 2) as u16);
1194    page.set_right_child(*children.last().ok_or_else(|| {
1195        BTreeError::Corrupted("write_interior_entries: children empty with non-empty keys".into())
1196    })?);
1197    Ok(())
1198}
1199
1200fn can_insert_interior(page: &Page, key: &[u8]) -> bool {
1201    let needed = 2 + 2 + key.len() + 4;
1202    interior_free_bytes(page) >= needed
1203}
1204
1205/// Insert a `(key, left_child)` separator into the interior page.
1206/// `right_child` replaces whatever child used to sit to the right of
1207/// the inserted key (either a middle child's pointer or the page's
1208/// `right_child` when the key is the new maximum).
1209fn insert_into_interior(
1210    page: &mut Page,
1211    key: &[u8],
1212    left_child: u32,
1213    right_child: u32,
1214) -> BTreeResult<()> {
1215    // 1. Binary search the slot array for the insert position.
1216    let cell_count = page.cell_count() as usize;
1217    let mut low = 0;
1218    let mut high = cell_count;
1219    while low < high {
1220        let mid = (low + high) / 2;
1221        let (cell_key, _) = read_interior_cell_borrowed(page, mid)?;
1222        match cell_key.cmp(key) {
1223            Ordering::Less => low = mid + 1,
1224            Ordering::Greater | Ordering::Equal => high = mid,
1225        }
1226    }
1227    let insert_pos = low;
1228
1229    // 2. Redirect the previous owner of the split to `right_child`.
1230    //    If the insertion is at the tail, the previous owner was the
1231    //    page's right_child pointer; otherwise it was the child slot
1232    //    of the cell currently at `insert_pos`.
1233    if insert_pos < cell_count {
1234        let old_offset = interior_read_slot(page, insert_pos)?;
1235        let data = page.as_bytes();
1236        let key_len = u16::from_le_bytes([data[old_offset], data[old_offset + 1]]) as usize;
1237        let child_pos = old_offset + 2 + key_len;
1238        let data = page.as_bytes_mut();
1239        data[child_pos..child_pos + 4].copy_from_slice(&right_child.to_le_bytes());
1240    } else {
1241        page.set_right_child(right_child);
1242    }
1243
1244    // 3. Reserve the new cell at the tail of the free area.
1245    let cell_size = 2 + key.len() + 4;
1246    let slot_end_after = INTERIOR_DATA_OFFSET + (cell_count + 1) * 2;
1247    let cells_start = interior_cells_start(page);
1248    if slot_end_after + cell_size > cells_start {
1249        return Err(BTreeError::Corrupted("interior page full".into()));
1250    }
1251    let cell_offset = cells_start - cell_size;
1252    {
1253        let data = page.as_bytes_mut();
1254        data[cell_offset..cell_offset + 2].copy_from_slice(&(key.len() as u16).to_le_bytes());
1255        data[cell_offset + 2..cell_offset + 2 + key.len()].copy_from_slice(key);
1256        data[cell_offset + 2 + key.len()..cell_offset + 2 + key.len() + 4]
1257            .copy_from_slice(&left_child.to_le_bytes());
1258    }
1259    page.set_free_end(cell_offset as u16);
1260
1261    // 4. Shift the slot-array tail right by one slot, write the new
1262    //    pointer into the freed slot, bump counters.
1263    {
1264        let shift_from = interior_slot_offset_for(insert_pos);
1265        let shift_to = shift_from + 2;
1266        let shift_len = (cell_count - insert_pos) * 2;
1267        if shift_len > 0 {
1268            let data = page.as_bytes_mut();
1269            data.copy_within(shift_from..shift_from + shift_len, shift_to);
1270        }
1271    }
1272    interior_write_slot(page, insert_pos, cell_offset as u16)?;
1273    page.set_cell_count((cell_count + 1) as u16);
1274    page.set_free_start((INTERIOR_DATA_OFFSET + (cell_count + 1) * 2) as u16);
1275    Ok(())
1276}
1277
1278fn clear_interior_cells(page: &mut Page) {
1279    {
1280        let data = page.as_bytes_mut();
1281        for byte in &mut data[INTERIOR_DATA_OFFSET..] {
1282            *byte = 0;
1283        }
1284    }
1285    page.set_cell_count(0);
1286    page.set_free_start(INTERIOR_DATA_OFFSET as u16);
1287    page.set_free_end(PAGE_SIZE as u16);
1288}