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
202impl<P: PageStore> BTreeCursor<P> {
203    /// Copy the position of an immutable cursor without advancing the original.
204    pub(crate) fn fork_immutable(&self) -> Self {
205        assert!(self.immutable, "only immutable cursors may be forked");
206        Self {
207            _retirement_pin: Arc::clone(&self._retirement_pin),
208            leaf_page_id: self.leaf_page_id,
209            position: self.position,
210            pager: Arc::clone(&self.pager),
211            prefetched_next: self.prefetched_next,
212            immutable: true,
213            immutable_leaf: self.immutable_leaf.clone(),
214        }
215    }
216
217    /// Only collection readers whose host pins an immutable published root
218    /// may retain a leaf across calls. This is not a mutable-tree snapshot.
219    pub(crate) fn with_immutable_leaves(mut self) -> Self {
220        self.immutable = true;
221        self
222    }
223
224    fn prepare_immutable_leaf(&mut self) -> BTreeResult<bool> {
225        if self.leaf_page_id == 0 {
226            return Ok(false);
227        }
228        if self.immutable_leaf.is_none() {
229            let page = self.pager.read_page(self.leaf_page_id)?;
230            if page.page_type()? != PageType::BTreeLeaf {
231                return Err(BTreeError::Corrupted(
232                    "cursor reached a non-leaf page".into(),
233                ));
234            }
235            self.immutable_leaf = Some(Box::new(page));
236        }
237        let page = self.immutable_leaf.as_ref().expect("loaded immutable leaf");
238        if self.position < usize::from(page.cell_count()) {
239            return Ok(true);
240        }
241        let next = read_next_leaf(page);
242        if next == 0 {
243            self.leaf_page_id = 0;
244            self.immutable_leaf = None;
245            return Ok(false);
246        }
247        let next_page = self.pager.read_page(next)?;
248        if next_page.page_type()? != PageType::BTreeLeaf || next_page.cell_count() == 0 {
249            return Err(BTreeError::Corrupted(
250                "leaf chain reached an invalid leaf".into(),
251            ));
252        }
253        let first_key = read_leaf_cell_borrowed(&next_page, 0)?.0;
254        if leaf_high_key(page)?
255            .as_ref()
256            .is_some_and(|key| first_key <= key.as_slice())
257        {
258            return Err(BTreeError::Corrupted(
259                "leaf chain does not advance its key range".into(),
260            ));
261        }
262        **self.immutable_leaf.as_mut().expect("loaded immutable leaf") = next_page;
263        self.leaf_page_id = next;
264        self.position = 0;
265        self.prefetched_next = false;
266        Ok(true)
267    }
268
269    /// Inspect the next key without materializing its value or advancing.
270    #[cfg(feature = "full")]
271    pub(crate) fn peek_key_with<T>(
272        &mut self,
273        visit: impl FnOnce(&[u8]) -> T,
274    ) -> BTreeResult<Option<T>> {
275        if self.immutable {
276            if !self.prepare_immutable_leaf()? {
277                return Ok(None);
278            }
279            let page = self.immutable_leaf.as_ref().expect("loaded immutable leaf");
280            return Ok(Some(visit(read_leaf_cell_borrowed(page, self.position)?.0)));
281        }
282        let Some(page) = self.prepare_next_leaf()? else {
283            return Ok(None);
284        };
285        Ok(Some(visit(
286            read_leaf_cell_borrowed(&page, self.position)?.0,
287        )))
288    }
289
290    /// Inspect the next key without materializing its value or advancing.
291    pub fn peek_key(&mut self) -> BTreeResult<Option<Vec<u8>>> {
292        if self.immutable {
293            if !self.prepare_immutable_leaf()? {
294                return Ok(None);
295            }
296            let page = self.immutable_leaf.as_ref().expect("loaded immutable leaf");
297            return Ok(Some(
298                read_leaf_cell_borrowed(page, self.position)?.0.to_vec(),
299            ));
300        }
301        let Some(page) = self.prepare_next_leaf()? else {
302            return Ok(None);
303        };
304        Ok(Some(read_leaf_cell(&page, self.position)?.0))
305    }
306
307    /// Skip a shadowed or deleted base record without reading its overflow value.
308    pub fn skip_next(&mut self) -> BTreeResult<bool> {
309        if self.immutable {
310            if !self.prepare_immutable_leaf()? {
311                return Ok(false);
312            }
313            self.position += 1;
314            return Ok(true);
315        }
316        if self.prepare_next_leaf()?.is_none() {
317            return Ok(false);
318        }
319        self.position += 1;
320        Ok(true)
321    }
322
323    fn prepare_next_leaf(&mut self) -> BTreeResult<Option<Page>> {
324        if self.leaf_page_id == 0 {
325            return Ok(None);
326        }
327        let page = self.pager.read_page(self.leaf_page_id)?;
328        if page.page_type()? != PageType::BTreeLeaf {
329            return Err(BTreeError::Corrupted(
330                "cursor reached a non-leaf page".into(),
331            ));
332        }
333        if self.position < usize::from(page.cell_count()) {
334            return Ok(Some(page));
335        }
336        let next = read_next_leaf(&page);
337        if next == 0 {
338            self.leaf_page_id = 0;
339            return Ok(None);
340        }
341        let next_page = self.pager.read_page(next)?;
342        if next_page.page_type()? != PageType::BTreeLeaf || next_page.cell_count() == 0 {
343            return Err(BTreeError::Corrupted(
344                "leaf chain reached an invalid leaf".into(),
345            ));
346        }
347        let first_key = read_leaf_cell(&next_page, 0)?.0;
348        if leaf_high_key(&page)?
349            .as_ref()
350            .is_some_and(|key| first_key <= *key)
351        {
352            return Err(BTreeError::Corrupted(
353                "leaf chain does not advance its key range".into(),
354            ));
355        }
356        self.leaf_page_id = next;
357        self.position = 0;
358        self.prefetched_next = false;
359        Ok(Some(next_page))
360    }
361
362    /// Read one value within the caller's materialization allowance.
363    pub fn next_with_budget(
364        &mut self,
365        limit_bytes: usize,
366    ) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
367        self.next_impl(limit_bytes)
368    }
369
370    /// Move to next entry
371    pub fn next(&mut self) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
372        self.next_impl(usize::MAX)
373    }
374
375    fn next_impl(&mut self, limit_bytes: usize) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
376        if self.immutable {
377            return self.next_immutable(limit_bytes);
378        }
379        if self.leaf_page_id == 0 {
380            return Ok(None);
381        }
382
383        let page = self.pager.read_page(self.leaf_page_id)?;
384        if page.page_type()? != PageType::BTreeLeaf {
385            return Err(BTreeError::Corrupted(
386                "cursor reached a non-leaf page".into(),
387            ));
388        }
389        let cell_count = page.cell_count() as usize;
390
391        // A6 — prefetch the next leaf when we cross the halfway point of
392        // the current one. The hint fires at most once per leaf (guarded
393        // by `prefetched_next`) so the syscall overhead is amortized over
394        // ~half a leaf's worth of entries. The kernel uses the hint to
395        // start DMA-ing the next page while we finish the current one.
396        if !self.prefetched_next && self.position >= cell_count / 2 && cell_count > 0 {
397            let next_leaf = read_next_leaf(&page);
398            if next_leaf != 0 {
399                self.pager.prefetch_hint(next_leaf);
400            }
401            self.prefetched_next = true;
402        }
403
404        // Check if we have more cells in current page
405        if self.position < cell_count {
406            let (key, stored) = read_leaf_cell(&page, self.position)?;
407            let value =
408                value_layout::decode_with_budget(self.pager.as_ref(), &stored, limit_bytes)?;
409            self.position += 1;
410            return Ok(Some((key, value)));
411        }
412
413        // Move to next leaf
414        let next_leaf = read_next_leaf(&page);
415        if next_leaf == 0 {
416            self.leaf_page_id = 0;
417            return Ok(None);
418        }
419        let previous_high_key = leaf_high_key(&page)?;
420
421        self.leaf_page_id = next_leaf;
422        self.position = 0;
423        self.prefetched_next = false; // reset for the new leaf
424
425        // Read from new leaf
426        let page = self.pager.read_page(self.leaf_page_id)?;
427        if page.page_type()? != PageType::BTreeLeaf {
428            return Err(BTreeError::Corrupted(
429                "leaf chain reached a non-leaf page".into(),
430            ));
431        }
432        if page.cell_count() == 0 {
433            return Ok(None);
434        }
435
436        let (key, stored) = read_leaf_cell(&page, 0)?;
437        // Every leaf transition must advance the key range. This bounds a
438        // corrupt cyclic chain without growing a visited-page set or an
439        // unbounded checkpoint buffer (#2376).
440        if previous_high_key
441            .as_ref()
442            .is_some_and(|previous| key <= *previous)
443        {
444            self.leaf_page_id = 0;
445            return Err(BTreeError::Corrupted(
446                "leaf chain does not advance its key range".into(),
447            ));
448        }
449        let value = value_layout::decode_with_budget(self.pager.as_ref(), &stored, limit_bytes)?;
450        self.position = 1;
451        Ok(Some((key, value)))
452    }
453
454    fn next_immutable(&mut self, limit_bytes: usize) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
455        if !self.prepare_immutable_leaf()? {
456            return Ok(None);
457        }
458        let page = self.immutable_leaf.as_ref().expect("loaded immutable leaf");
459        if !self.prefetched_next && self.position >= usize::from(page.cell_count()) / 2 {
460            let next = read_next_leaf(page);
461            if next != 0 {
462                self.pager.prefetch_hint(next);
463            }
464            self.prefetched_next = true;
465        }
466        let (key, stored) = read_leaf_cell_borrowed(page, self.position)?;
467        let value = value_layout::decode_with_budget(self.pager.as_ref(), stored, limit_bytes)?;
468        self.position += 1;
469        Ok(Some((key.to_vec(), value)))
470    }
471
472    /// Peek at current entry without advancing
473    pub fn peek(&self) -> BTreeResult<Option<(Vec<u8>, Vec<u8>)>> {
474        if self.leaf_page_id == 0 {
475            return Ok(None);
476        }
477
478        let page = self.pager.read_page(self.leaf_page_id)?;
479        let cell_count = page.cell_count() as usize;
480
481        if self.position >= cell_count {
482            return Ok(None);
483        }
484
485        let (key, stored) = read_leaf_cell(&page, self.position)?;
486        let value = value_layout::decode(self.pager.as_ref(), &stored)?;
487        Ok(Some((key, value)))
488    }
489}
490
491/// B+ Tree implementation
492pub struct BTree<P: PageStore> {
493    retirement_pin: Arc<()>,
494    /// Pager for page I/O
495    pager: Arc<page_proofs::TreePageStore<P>>,
496    /// Root page ID (0 = empty tree)
497    root_page_id: RwLock<u32>,
498    /// D2 fastpath: cached rightmost leaf (page_id, high_key).
499    ///
500    /// When the next key to insert is strictly greater than `high_key`,
501    /// skip `find_leaf` (tree descent from root) and go directly to the
502    /// cached page. Invalidated on splits and deletes.
503    ///
504    /// Mirrors `BTPageCacheIsValid` / `BTREE_FASTPATH_MIN_LEVEL` in
505    /// `nbtinsert.c:31`.
506    rightmost_leaf: RwLock<Option<(u32, Vec<u8>)>>,
507    /// Serialises structural writers (insert / upsert / delete / bulk).
508    ///
509    /// Writers copy a page, modify the copy and write it back, and there
510    /// are no page latches, so two writers on one tree would lose each
511    /// other's leaf updates or tear a split (#2376). Reentrant because the
512    /// public mutators call each other (`upsert` -> `insert`, the bulk
513    /// paths -> `insert_encoded`). Readers do not take it.
514    writer: parking_lot::ReentrantMutex<()>,
515}
516
517#[path = "btree/impl.rs"]
518mod btree_impl;
519
520#[path = "btree/reclaim.rs"]
521mod reclaim;
522
523mod page_proofs;
524
525#[cfg(test)]
526#[path = "btree/read_budget_tests.rs"]
527mod read_budget_tests;
528
529#[path = "btree/lehman_yao.rs"]
530pub mod lehman_yao;
531
532#[path = "btree/value_layout.rs"]
533pub mod value_layout;
534// ==================== Search Helpers ====================
535
536enum SearchResult {
537    Found(usize),
538    NotFound(usize),
539}
540
541fn search_leaf(page: &Page, key: &[u8]) -> BTreeResult<SearchResult> {
542    let cell_count = page.cell_count() as usize;
543
544    // Binary search
545    let mut low = 0;
546    let mut high = cell_count;
547
548    while low < high {
549        let mid = (low + high) / 2;
550        let (cell_key, _) = read_leaf_cell_borrowed(page, mid)?;
551
552        match cell_key.cmp(key) {
553            Ordering::Less => low = mid + 1,
554            Ordering::Greater => high = mid,
555            Ordering::Equal => return Ok(SearchResult::Found(mid)),
556        }
557    }
558
559    Ok(SearchResult::NotFound(low))
560}
561
562fn find_child(page: &Page, key: &[u8]) -> BTreeResult<u32> {
563    // The child of the first separator above `key`. Every descent of every
564    // tree operation comes through here: it used to walk the separators in
565    // order and copy each one it looked at.
566    let mut low = 0;
567    let mut high = page.cell_count() as usize;
568    while low < high {
569        let mid = (low + high) / 2;
570        let (cell_key, _) = read_interior_cell_borrowed(page, mid)?;
571        if key < cell_key {
572            high = mid;
573        } else {
574            low = mid + 1;
575        }
576    }
577    if low < page.cell_count() as usize {
578        return Ok(read_interior_cell_borrowed(page, low)?.1);
579    }
580
581    // Key is >= all keys, use right child
582    Ok(page.right_child())
583}
584
585fn find_first_child(page: &Page) -> BTreeResult<u32> {
586    if page.cell_count() == 0 {
587        return Ok(page.right_child());
588    }
589    let (_, child) = read_interior_cell(page, 0)?;
590    Ok(child)
591}
592
593fn leaf_min_bytes() -> usize {
594    (PAGE_SIZE - LEAF_DATA_OFFSET) * MIN_FILL_FACTOR / 100
595}
596
597fn interior_min_bytes() -> usize {
598    (PAGE_SIZE - INTERIOR_DATA_OFFSET) * MIN_FILL_FACTOR / 100
599}
600
601/// Bytes consumed by one leaf entry in the slotted layout: one u16
602/// slot in the pointer array plus the cell itself (`[key_len:u16]
603/// [val_len:u16][key][val]`).
604fn leaf_entry_size(entry: &(Vec<u8>, Vec<u8>)) -> usize {
605    2 + 4 + entry.0.len() + entry.1.len()
606}
607
608fn leaf_entries_size(entries: &[(Vec<u8>, Vec<u8>)]) -> usize {
609    entries.iter().map(leaf_entry_size).sum()
610}
611
612/// What `leaf_entries_size` returns for the page's entries, read from the
613/// slots without copying a cell.
614fn leaf_used_bytes(page: &Page) -> BTreeResult<usize> {
615    let mut bytes = 0;
616    for index in 0..page.cell_count() as usize {
617        let (key, value) = read_leaf_cell_borrowed(page, index)?;
618        bytes += 2 + 4 + key.len() + value.len();
619    }
620    Ok(bytes)
621}
622
623#[inline]
624fn leaf_slot_offset_for(index: usize) -> usize {
625    LEAF_SLOT_ARRAY_OFFSET + index * 2
626}
627
628#[inline]
629fn leaf_read_slot(page: &Page, index: usize) -> BTreeResult<usize> {
630    let data = page.as_bytes();
631    let slot_pos = leaf_slot_offset_for(index);
632    if slot_pos + 2 > PAGE_SIZE {
633        return Err(BTreeError::Corrupted("slot array overflows page".into()));
634    }
635    Ok(u16::from_le_bytes([data[slot_pos], data[slot_pos + 1]]) as usize)
636}
637
638#[inline]
639fn leaf_write_slot(page: &mut Page, index: usize, cell_offset: u16) -> BTreeResult<()> {
640    let data = page.as_bytes_mut();
641    let slot_pos = leaf_slot_offset_for(index);
642    if slot_pos + 2 > PAGE_SIZE {
643        return Err(BTreeError::Corrupted("slot array overflows page".into()));
644    }
645    data[slot_pos..slot_pos + 2].copy_from_slice(&cell_offset.to_le_bytes());
646    Ok(())
647}
648
649#[inline]
650fn leaf_slots_end(page: &Page) -> usize {
651    LEAF_SLOT_ARRAY_OFFSET + (page.cell_count() as usize) * 2
652}
653
654#[inline]
655fn leaf_cells_start(page: &Page) -> usize {
656    let end = page.free_end() as usize;
657    if end == 0 {
658        PAGE_SIZE
659    } else {
660        end
661    }
662}
663
664#[inline]
665fn leaf_free_bytes(page: &Page) -> usize {
666    let slot_end = leaf_slots_end(page);
667    let cells = leaf_cells_start(page);
668    cells.saturating_sub(slot_end)
669}
670
671fn interior_key_size(key: &[u8]) -> usize {
672    2 + key.len() + 4
673}
674
675fn interior_entries_size(keys: &[Vec<u8>]) -> usize {
676    keys.iter().map(|k| interior_key_size(k)).sum()
677}
678
679// ==================== Leaf Page Helpers ====================
680
681/// Read the cell at slot `index` in O(1). Follows the u16 slot pointer
682/// into the cell data area; the cell header is `[key_len:u16][val_len:u16]`
683/// followed by the raw key and value bytes.
684fn read_leaf_cell(page: &Page, index: usize) -> BTreeResult<(Vec<u8>, Vec<u8>)> {
685    let (key, value) = read_leaf_cell_borrowed(page, index)?;
686    Ok((key.to_vec(), value.to_vec()))
687}
688
689fn read_leaf_cell_borrowed(page: &Page, index: usize) -> BTreeResult<(&[u8], &[u8])> {
690    let cell_count = page.cell_count() as usize;
691    if index >= cell_count {
692        return Err(BTreeError::Corrupted("Cell index out of range".into()));
693    }
694    let offset = leaf_read_slot(page, index)?;
695    let data = page.as_bytes();
696    if offset + 4 > PAGE_SIZE {
697        return Err(BTreeError::Corrupted("cell header out of range".into()));
698    }
699    let key_len = u16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
700    let val_len = u16::from_le_bytes([data[offset + 2], data[offset + 3]]) as usize;
701    let end = offset + 4 + key_len + val_len;
702    if end > PAGE_SIZE {
703        return Err(BTreeError::Corrupted("cell body out of range".into()));
704    }
705    let key = &data[offset + 4..offset + 4 + key_len];
706    let value = &data[offset + 4 + key_len..end];
707    Ok((key, value))
708}
709
710fn read_leaf_entries(page: &Page) -> BTreeResult<Vec<(Vec<u8>, Vec<u8>)>> {
711    let cell_count = page.cell_count() as usize;
712    let mut entries = Vec::with_capacity(cell_count);
713    for i in 0..cell_count {
714        entries.push(read_leaf_cell(page, i)?);
715    }
716    Ok(entries)
717}
718
719/// Wipe and re-lay an entire leaf in slotted form. Used by the split
720/// path (which hands us a pre-sorted `entries` vector) and by
721/// `clear_leaf_cells` under the hood. Entries are appended at the end
722/// of the free area so the highest-index slot ends up at the lowest
723/// offset — same shape the single-key insert path produces.
724fn write_leaf_entries(page: &mut Page, entries: &[(Vec<u8>, Vec<u8>)]) -> BTreeResult<()> {
725    clear_leaf_cells(page);
726    for (i, (k, v)) in entries.iter().enumerate() {
727        let cell_size = 4 + k.len() + v.len();
728        let cells_start = leaf_cells_start(page);
729        let slot_end = LEAF_SLOT_ARRAY_OFFSET + (i + 1) * 2;
730        if slot_end + cell_size > cells_start {
731            return Err(BTreeError::Corrupted("leaf rebuild overflowed page".into()));
732        }
733        let cell_offset = cells_start - cell_size;
734        {
735            let data = page.as_bytes_mut();
736            data[cell_offset..cell_offset + 2].copy_from_slice(&(k.len() as u16).to_le_bytes());
737            data[cell_offset + 2..cell_offset + 4].copy_from_slice(&(v.len() as u16).to_le_bytes());
738            data[cell_offset + 4..cell_offset + 4 + k.len()].copy_from_slice(k);
739            data[cell_offset + 4 + k.len()..cell_offset + 4 + k.len() + v.len()].copy_from_slice(v);
740        }
741        page.set_free_end(cell_offset as u16);
742        leaf_write_slot(page, i, cell_offset as u16)?;
743    }
744    page.set_cell_count(entries.len() as u16);
745    page.set_free_start((LEAF_SLOT_ARRAY_OFFSET + entries.len() * 2) as u16);
746    Ok(())
747}
748
749fn can_insert_leaf(page: &Page, key: &[u8], value: &[u8]) -> bool {
750    let needed = 2 + 4 + key.len() + value.len();
751    leaf_free_bytes(page) >= needed
752}
753
754/// Insert `(key, value)` into the slotted leaf in O(log M) search +
755/// O(M) slot-array memmove. Cell data is appended at the tail of the
756/// free area (backward from `free_end`); the slot pointer is inserted
757/// Overwrite the value portion of cell at `index` in-place. Valid when
758/// `new_value.len() <= existing_value.len()` — the caller
759/// (typically `BTree::upsert`) checks this before calling.
760///
761/// Same-length writes are trivial (byte copy). Shrinks update the cell's
762/// `v_len` header and leave the trailing bytes as dead space until the
763/// page is naturally rewritten; the slotted layout keeps cells
764/// addressable by their own offset+len so the gap is harmless.
765///
766/// Fixed-size column updates (SET score = X on a typed schema) hit this
767/// path, avoiding the delete + re-insert + rebalance cycle that
768/// dominates bulk_update.
769pub(crate) fn overwrite_leaf_value(
770    page: &mut Page,
771    index: usize,
772    new_value: &[u8],
773) -> BTreeResult<()> {
774    let cell_offset = leaf_read_slot(page, index)?;
775    let data = page.as_bytes();
776    if cell_offset + 4 > data.len() {
777        return Err(BTreeError::Corrupted(
778            "leaf cell header out of bounds".into(),
779        ));
780    }
781    let k_len = u16::from_le_bytes([data[cell_offset], data[cell_offset + 1]]) as usize;
782    let old_v_len = u16::from_le_bytes([data[cell_offset + 2], data[cell_offset + 3]]) as usize;
783    if new_value.len() > old_v_len {
784        return Err(BTreeError::Corrupted(
785            "overwrite_leaf_value: new value larger than slot".into(),
786        ));
787    }
788    let value_start = cell_offset + 4 + k_len;
789    if value_start + new_value.len() > data.len() {
790        return Err(BTreeError::Corrupted(
791            "leaf cell value out of bounds".into(),
792        ));
793    }
794    let data = page.as_bytes_mut();
795    // Update the v_len header if the value shrank. read_leaf_cell reads
796    // v_len from this header so the shortened value deserializes correctly.
797    if new_value.len() != old_v_len {
798        let new_len = new_value.len() as u16;
799        data[cell_offset + 2..cell_offset + 4].copy_from_slice(&new_len.to_le_bytes());
800    }
801    data[value_start..value_start + new_value.len()].copy_from_slice(new_value);
802    Ok(())
803}
804
805/// at the sorted position.
806fn insert_into_leaf(page: &mut Page, key: &[u8], value: &[u8]) -> BTreeResult<()> {
807    // 1. Binary search the slot array to find the insertion index.
808    let cell_count = page.cell_count() as usize;
809    let mut low = 0;
810    let mut high = cell_count;
811    while low < high {
812        let mid = (low + high) / 2;
813        let (cell_key, _) = read_leaf_cell_borrowed(page, mid)?;
814        match cell_key.cmp(key) {
815            Ordering::Less => low = mid + 1,
816            Ordering::Greater => high = mid,
817            Ordering::Equal => {
818                // Duplicate keys are tolerated by the B-tree (caller
819                // decides semantics); append after the existing run.
820                low = mid + 1;
821                break;
822            }
823        }
824    }
825    let insert_pos = low;
826
827    // 2. Reserve the cell at the tail of the free area.
828    let cell_size = 4 + key.len() + value.len();
829    let slot_end_after = LEAF_SLOT_ARRAY_OFFSET + (cell_count + 1) * 2;
830    let cells_start = leaf_cells_start(page);
831    if slot_end_after + cell_size > cells_start {
832        return Err(BTreeError::Corrupted("leaf page full".into()));
833    }
834    let cell_offset = cells_start - cell_size;
835    {
836        let data = page.as_bytes_mut();
837        data[cell_offset..cell_offset + 2].copy_from_slice(&(key.len() as u16).to_le_bytes());
838        data[cell_offset + 2..cell_offset + 4].copy_from_slice(&(value.len() as u16).to_le_bytes());
839        data[cell_offset + 4..cell_offset + 4 + key.len()].copy_from_slice(key);
840        data[cell_offset + 4 + key.len()..cell_offset + 4 + key.len() + value.len()]
841            .copy_from_slice(value);
842    }
843    page.set_free_end(cell_offset as u16);
844
845    // 3. Shift the slot-array tail right by one slot, then write the
846    //    new pointer into the freed slot. This is a single memmove on
847    //    a couple dozen u16s — far cheaper than the O(M²) rebuild.
848    {
849        let shift_from = leaf_slot_offset_for(insert_pos);
850        let shift_to = shift_from + 2;
851        let shift_len = (cell_count - insert_pos) * 2;
852        if shift_len > 0 {
853            let data = page.as_bytes_mut();
854            data.copy_within(shift_from..shift_from + shift_len, shift_to);
855        }
856    }
857    leaf_write_slot(page, insert_pos, cell_offset as u16)?;
858
859    // 4. Bump counters.
860    page.set_cell_count((cell_count + 1) as u16);
861    page.set_free_start((LEAF_SLOT_ARRAY_OFFSET + (cell_count + 1) * 2) as u16);
862    Ok(())
863}
864
865/// Remove the slot at `index`. Cell bytes are left in place (lazy
866/// compaction); the slot-array tail is shifted left to close the gap.
867/// The caller is expected to call `clear_leaf_cells` + rebuild if the
868/// page wants its free space reclaimed.
869fn delete_from_leaf(page: &mut Page, index: usize) -> BTreeResult<()> {
870    let cell_count = page.cell_count() as usize;
871    if index >= cell_count {
872        return Err(BTreeError::Corrupted("delete index out of range".into()));
873    }
874    if index + 1 < cell_count {
875        let shift_from = leaf_slot_offset_for(index + 1);
876        let shift_to = leaf_slot_offset_for(index);
877        let shift_len = (cell_count - index - 1) * 2;
878        let data = page.as_bytes_mut();
879        data.copy_within(shift_from..shift_from + shift_len, shift_to);
880    }
881    page.set_cell_count((cell_count - 1) as u16);
882    page.set_free_start((LEAF_SLOT_ARRAY_OFFSET + (cell_count - 1) * 2) as u16);
883    Ok(())
884}
885
886/// Reset the leaf to an empty slotted state — cell count 0, free
887/// cursors at the extremes. Zeroes the slot array + cell data area so
888/// stale bytes never leak through a corrupted read.
889fn clear_leaf_cells(page: &mut Page) {
890    {
891        let data = page.as_bytes_mut();
892        for byte in &mut data[LEAF_SLOT_ARRAY_OFFSET..] {
893            *byte = 0;
894        }
895    }
896    page.set_cell_count(0);
897    page.set_free_start(LEAF_SLOT_ARRAY_OFFSET as u16);
898    page.set_free_end(PAGE_SIZE as u16);
899}
900
901fn init_leaf_links(page: &mut Page, prev: u32, next: u32) {
902    let data = page.as_bytes_mut();
903    data[LEAF_PREV_OFFSET..LEAF_PREV_OFFSET + 4].copy_from_slice(&prev.to_le_bytes());
904    data[LEAF_NEXT_OFFSET..LEAF_NEXT_OFFSET + 4].copy_from_slice(&next.to_le_bytes());
905}
906
907fn read_next_leaf(page: &Page) -> u32 {
908    let data = page.as_bytes();
909    u32::from_le_bytes([
910        data[LEAF_NEXT_OFFSET],
911        data[LEAF_NEXT_OFFSET + 1],
912        data[LEAF_NEXT_OFFSET + 2],
913        data[LEAF_NEXT_OFFSET + 3],
914    ])
915}
916
917/// Returns the right-sibling page ID for a leaf page.
918/// 0 means this is the rightmost leaf — used by the D2 fastpath cache.
919#[inline]
920fn leaf_right_sibling(page: &Page) -> u32 {
921    read_next_leaf(page)
922}
923
924/// Returns the maximum (last) key stored in a leaf page, or `None` if empty.
925/// This is the Lehman-Yao "high_key" — any key > this value belongs on a
926/// right-sibling page. Reads only the last slot so it is O(1).
927fn leaf_high_key(page: &Page) -> BTreeResult<Option<Vec<u8>>> {
928    let cell_count = page.cell_count() as usize;
929    if cell_count == 0 {
930        return Ok(None);
931    }
932    let (key, _) = read_leaf_cell(page, cell_count - 1)?;
933    Ok(Some(key))
934}
935
936fn set_prev_leaf(page: &mut Page, prev: u32) {
937    let data = page.as_bytes_mut();
938    data[LEAF_PREV_OFFSET..LEAF_PREV_OFFSET + 4].copy_from_slice(&prev.to_le_bytes());
939}
940
941fn set_next_leaf(page: &mut Page, next: u32) {
942    let data = page.as_bytes_mut();
943    data[LEAF_NEXT_OFFSET..LEAF_NEXT_OFFSET + 4].copy_from_slice(&next.to_le_bytes());
944}
945
946// ==================== Interior Page Helpers ====================
947//
948// Slotted-page layout mirroring the leaf format:
949//
950// ```text
951// [PageHeader 32B]
952// [slot 0: u16][slot 1: u16]...[slot N-1: u16]  ← grows forward
953// ... free space ...
954// [cell N-1][cell N-2]...[cell 0]               ← grows backward from free_end
955// ```
956//
957// Each cell is `[key_len:u16][key][child:u32]`. The right-most child
958// pointer lives in `PageHeader.right_child` exactly as before.
959
960#[inline]
961fn interior_slot_offset_for(index: usize) -> usize {
962    INTERIOR_DATA_OFFSET + index * 2
963}
964
965#[inline]
966fn interior_read_slot(page: &Page, index: usize) -> BTreeResult<usize> {
967    let data = page.as_bytes();
968    let slot_pos = interior_slot_offset_for(index);
969    if slot_pos + 2 > PAGE_SIZE {
970        return Err(BTreeError::Corrupted(
971            "interior slot array overflows page".into(),
972        ));
973    }
974    Ok(u16::from_le_bytes([data[slot_pos], data[slot_pos + 1]]) as usize)
975}
976
977#[inline]
978fn interior_write_slot(page: &mut Page, index: usize, cell_offset: u16) -> BTreeResult<()> {
979    let data = page.as_bytes_mut();
980    let slot_pos = interior_slot_offset_for(index);
981    if slot_pos + 2 > PAGE_SIZE {
982        return Err(BTreeError::Corrupted(
983            "interior slot array overflows page".into(),
984        ));
985    }
986    data[slot_pos..slot_pos + 2].copy_from_slice(&cell_offset.to_le_bytes());
987    Ok(())
988}
989
990#[inline]
991fn interior_cells_start(page: &Page) -> usize {
992    let end = page.free_end() as usize;
993    if end == 0 {
994        PAGE_SIZE
995    } else {
996        end
997    }
998}
999
1000#[inline]
1001fn interior_free_bytes(page: &Page) -> usize {
1002    let slot_end = INTERIOR_DATA_OFFSET + (page.cell_count() as usize) * 2;
1003    interior_cells_start(page).saturating_sub(slot_end)
1004}
1005
1006fn read_interior_cell(page: &Page, index: usize) -> BTreeResult<(Vec<u8>, u32)> {
1007    let (key, child) = read_interior_cell_borrowed(page, index)?;
1008    Ok((key.to_vec(), child))
1009}
1010
1011/// Where `child` sits among an interior page's children, in the order
1012/// `read_interior_keys_children` lists them, with the separator to its left
1013/// (none for the first child). Copies no key.
1014fn interior_child_slot(page: &Page, child: u32) -> BTreeResult<Option<(usize, Option<&[u8]>)>> {
1015    let cell_count = page.cell_count() as usize;
1016    let mut left = None;
1017    for index in 0..cell_count {
1018        let (key, id) = read_interior_cell_borrowed(page, index)?;
1019        if id == child {
1020            return Ok(Some((index, left)));
1021        }
1022        left = Some(key);
1023    }
1024    let right_child = page.right_child();
1025    if right_child == child && (cell_count > 0 || right_child != 0) {
1026        return Ok(Some((cell_count, left)));
1027    }
1028    Ok(None)
1029}
1030
1031fn read_interior_cell_borrowed(page: &Page, index: usize) -> BTreeResult<(&[u8], u32)> {
1032    let cell_count = page.cell_count() as usize;
1033    if index >= cell_count {
1034        return Err(BTreeError::Corrupted("Cell index out of range".into()));
1035    }
1036    let offset = interior_read_slot(page, index)?;
1037    let data = page.as_bytes();
1038    if offset + 2 > PAGE_SIZE {
1039        return Err(BTreeError::Corrupted(
1040            "interior cell header out of range".into(),
1041        ));
1042    }
1043    let key_len = u16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
1044    let end = offset + 2 + key_len + 4;
1045    if end > PAGE_SIZE {
1046        return Err(BTreeError::Corrupted(
1047            "interior cell body out of range".into(),
1048        ));
1049    }
1050    let key = &data[offset + 2..offset + 2 + key_len];
1051    let child = u32::from_le_bytes([
1052        data[offset + 2 + key_len],
1053        data[offset + 2 + key_len + 1],
1054        data[offset + 2 + key_len + 2],
1055        data[offset + 2 + key_len + 3],
1056    ]);
1057    Ok((key, child))
1058}
1059
1060fn read_interior_keys_children(page: &Page) -> BTreeResult<(Vec<Vec<u8>>, Vec<u32>)> {
1061    let cell_count = page.cell_count() as usize;
1062    let mut keys = Vec::with_capacity(cell_count);
1063    let mut children = Vec::with_capacity(cell_count + 1);
1064
1065    for i in 0..cell_count {
1066        let (key, child) = read_interior_cell(page, i)?;
1067        keys.push(key);
1068        children.push(child);
1069    }
1070
1071    if cell_count == 0 {
1072        let right_child = page.right_child();
1073        if right_child != 0 {
1074            children.push(right_child);
1075        }
1076    } else {
1077        children.push(page.right_child());
1078    }
1079
1080    Ok((keys, children))
1081}
1082
1083/// Bulk-write an interior page from scratch in slotted form. Used by
1084/// the split path. `keys` and `children` follow the B+ tree contract:
1085/// `children.len() == keys.len() + 1`, with the last child landing in
1086/// `PageHeader.right_child` (as before).
1087fn write_interior_entries(page: &mut Page, keys: &[Vec<u8>], children: &[u32]) -> BTreeResult<()> {
1088    if !keys.is_empty() && children.len() != keys.len() + 1 {
1089        return Err(BTreeError::Corrupted(
1090            "Interior keys/children length mismatch".into(),
1091        ));
1092    }
1093
1094    clear_interior_cells(page);
1095    if keys.is_empty() {
1096        let right_child = children.first().copied().unwrap_or(0);
1097        page.set_right_child(right_child);
1098        return Ok(());
1099    }
1100
1101    for (i, key) in keys.iter().enumerate() {
1102        let cell_size = 2 + key.len() + 4;
1103        let cells_start = interior_cells_start(page);
1104        let slot_end = INTERIOR_DATA_OFFSET + (i + 1) * 2;
1105        if slot_end + cell_size > cells_start {
1106            return Err(BTreeError::Corrupted(
1107                "interior rebuild overflowed page".into(),
1108            ));
1109        }
1110        let cell_offset = cells_start - cell_size;
1111        {
1112            let data = page.as_bytes_mut();
1113            data[cell_offset..cell_offset + 2].copy_from_slice(&(key.len() as u16).to_le_bytes());
1114            data[cell_offset + 2..cell_offset + 2 + key.len()].copy_from_slice(key);
1115            data[cell_offset + 2 + key.len()..cell_offset + 2 + key.len() + 4]
1116                .copy_from_slice(&children[i].to_le_bytes());
1117        }
1118        page.set_free_end(cell_offset as u16);
1119        interior_write_slot(page, i, cell_offset as u16)?;
1120    }
1121    page.set_cell_count(keys.len() as u16);
1122    page.set_free_start((INTERIOR_DATA_OFFSET + keys.len() * 2) as u16);
1123    page.set_right_child(*children.last().ok_or_else(|| {
1124        BTreeError::Corrupted("write_interior_entries: children empty with non-empty keys".into())
1125    })?);
1126    Ok(())
1127}
1128
1129fn can_insert_interior(page: &Page, key: &[u8]) -> bool {
1130    let needed = 2 + 2 + key.len() + 4;
1131    interior_free_bytes(page) >= needed
1132}
1133
1134/// Insert a `(key, left_child)` separator into the interior page.
1135/// `right_child` replaces whatever child used to sit to the right of
1136/// the inserted key (either a middle child's pointer or the page's
1137/// `right_child` when the key is the new maximum).
1138fn insert_into_interior(
1139    page: &mut Page,
1140    key: &[u8],
1141    left_child: u32,
1142    right_child: u32,
1143) -> BTreeResult<()> {
1144    // 1. Binary search the slot array for the insert position.
1145    let cell_count = page.cell_count() as usize;
1146    let mut low = 0;
1147    let mut high = cell_count;
1148    while low < high {
1149        let mid = (low + high) / 2;
1150        let (cell_key, _) = read_interior_cell_borrowed(page, mid)?;
1151        match cell_key.cmp(key) {
1152            Ordering::Less => low = mid + 1,
1153            Ordering::Greater | Ordering::Equal => high = mid,
1154        }
1155    }
1156    let insert_pos = low;
1157
1158    // 2. Redirect the previous owner of the split to `right_child`.
1159    //    If the insertion is at the tail, the previous owner was the
1160    //    page's right_child pointer; otherwise it was the child slot
1161    //    of the cell currently at `insert_pos`.
1162    if insert_pos < cell_count {
1163        let old_offset = interior_read_slot(page, insert_pos)?;
1164        let data = page.as_bytes();
1165        let key_len = u16::from_le_bytes([data[old_offset], data[old_offset + 1]]) as usize;
1166        let child_pos = old_offset + 2 + key_len;
1167        let data = page.as_bytes_mut();
1168        data[child_pos..child_pos + 4].copy_from_slice(&right_child.to_le_bytes());
1169    } else {
1170        page.set_right_child(right_child);
1171    }
1172
1173    // 3. Reserve the new cell at the tail of the free area.
1174    let cell_size = 2 + key.len() + 4;
1175    let slot_end_after = INTERIOR_DATA_OFFSET + (cell_count + 1) * 2;
1176    let cells_start = interior_cells_start(page);
1177    if slot_end_after + cell_size > cells_start {
1178        return Err(BTreeError::Corrupted("interior page full".into()));
1179    }
1180    let cell_offset = cells_start - cell_size;
1181    {
1182        let data = page.as_bytes_mut();
1183        data[cell_offset..cell_offset + 2].copy_from_slice(&(key.len() as u16).to_le_bytes());
1184        data[cell_offset + 2..cell_offset + 2 + key.len()].copy_from_slice(key);
1185        data[cell_offset + 2 + key.len()..cell_offset + 2 + key.len() + 4]
1186            .copy_from_slice(&left_child.to_le_bytes());
1187    }
1188    page.set_free_end(cell_offset as u16);
1189
1190    // 4. Shift the slot-array tail right by one slot, write the new
1191    //    pointer into the freed slot, bump counters.
1192    {
1193        let shift_from = interior_slot_offset_for(insert_pos);
1194        let shift_to = shift_from + 2;
1195        let shift_len = (cell_count - insert_pos) * 2;
1196        if shift_len > 0 {
1197            let data = page.as_bytes_mut();
1198            data.copy_within(shift_from..shift_from + shift_len, shift_to);
1199        }
1200    }
1201    interior_write_slot(page, insert_pos, cell_offset as u16)?;
1202    page.set_cell_count((cell_count + 1) as u16);
1203    page.set_free_start((INTERIOR_DATA_OFFSET + (cell_count + 1) * 2) as u16);
1204    Ok(())
1205}
1206
1207fn clear_interior_cells(page: &mut Page) {
1208    {
1209        let data = page.as_bytes_mut();
1210        for byte in &mut data[INTERIOR_DATA_OFFSET..] {
1211            *byte = 0;
1212        }
1213    }
1214    page.set_cell_count(0);
1215    page.set_free_start(INTERIOR_DATA_OFFSET as u16);
1216    page.set_free_end(PAGE_SIZE as u16);
1217}