LCOV - code coverage report
Current view: top level - pageserver/src/tenant - disk_btree.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 98.7 % 634 626
Test Date: 2025-07-16 12:29:03 Functions: 86.1 % 201 173

            Line data    Source code
       1              : //!
       2              : //! Simple on-disk B-tree implementation
       3              : //!
       4              : //! This is used as the index structure within image and delta layers
       5              : //!
       6              : //! Features:
       7              : //! - Fixed-width keys
       8              : //! - Fixed-width values (VALUE_SZ)
       9              : //! - The tree is created in a bulk operation. Insert/deletion after creation
      10              : //!   is not supported
      11              : //! - page-oriented
      12              : //!
      13              : //! TODO:
      14              : //! - maybe something like an Adaptive Radix Tree would be more efficient?
      15              : //! - the values stored by image and delta layers are offsets into the file,
      16              : //!   and they are in monotonically increasing order. Prefix compression would
      17              : //!   be very useful for them, too.
      18              : //! - An Iterator interface would be more convenient for the callers than the
      19              : //!   'visit' function
      20              : //!
      21              : use std::cmp::Ordering;
      22              : use std::iter::Rev;
      23              : use std::ops::{Range, RangeInclusive};
      24              : use std::{io, result};
      25              : 
      26              : use async_stream::try_stream;
      27              : use byteorder::{BE, ReadBytesExt};
      28              : use bytes::BufMut;
      29              : use either::Either;
      30              : use futures::{Stream, StreamExt};
      31              : use hex;
      32              : use thiserror::Error;
      33              : use tracing::error;
      34              : 
      35              : use crate::context::RequestContext;
      36              : use crate::tenant::block_io::{BlockReader, BlockWriter};
      37              : use crate::virtual_file::{IoBuffer, IoBufferMut, owned_buffers_io::write::Buffer};
      38              : 
      39              : // The maximum size of a value stored in the B-tree. 5 bytes is enough currently.
      40              : pub const VALUE_SZ: usize = 5;
      41              : pub const MAX_VALUE: u64 = 0x007f_ffff_ffff;
      42              : 
      43              : pub const PAGE_SZ: usize = 8192;
      44              : 
      45              : #[derive(Clone, Copy, Debug)]
      46              : struct Value([u8; VALUE_SZ]);
      47              : 
      48              : impl Value {
      49      4573264 :     fn from_slice(slice: &[u8]) -> Value {
      50      4573264 :         let mut b = [0u8; VALUE_SZ];
      51      4573264 :         b.copy_from_slice(slice);
      52      4573264 :         Value(b)
      53      4573264 :     }
      54              : 
      55      3374337 :     fn from_u64(x: u64) -> Value {
      56      3374337 :         assert!(x <= 0x007f_ffff_ffff);
      57      3374337 :         Value([
      58      3374337 :             (x >> 32) as u8,
      59      3374337 :             (x >> 24) as u8,
      60      3374337 :             (x >> 16) as u8,
      61      3374337 :             (x >> 8) as u8,
      62      3374337 :             x as u8,
      63      3374337 :         ])
      64      3374337 :     }
      65              : 
      66         6246 :     fn from_blknum(x: u32) -> Value {
      67         6246 :         Value([
      68         6246 :             0x80,
      69         6246 :             (x >> 24) as u8,
      70         6246 :             (x >> 16) as u8,
      71         6246 :             (x >> 8) as u8,
      72         6246 :             x as u8,
      73         6246 :         ])
      74         6246 :     }
      75              : 
      76              :     #[allow(dead_code)]
      77            0 :     fn is_offset(self) -> bool {
      78            0 :         self.0[0] & 0x80 != 0
      79            0 :     }
      80              : 
      81      4237253 :     fn to_u64(self) -> u64 {
      82      4237253 :         let b = &self.0;
      83      4237253 :         ((b[0] as u64) << 32)
      84      4237253 :             | ((b[1] as u64) << 24)
      85      4237253 :             | ((b[2] as u64) << 16)
      86      4237253 :             | ((b[3] as u64) << 8)
      87      4237253 :             | b[4] as u64
      88      4237253 :     }
      89              : 
      90       332999 :     fn to_blknum(self) -> u32 {
      91       332999 :         let b = &self.0;
      92       332999 :         assert!(b[0] == 0x80);
      93       332999 :         ((b[1] as u32) << 24) | ((b[2] as u32) << 16) | ((b[3] as u32) << 8) | b[4] as u32
      94       332999 :     }
      95              : }
      96              : 
      97              : #[derive(Error, Debug)]
      98              : pub enum DiskBtreeError {
      99              :     #[error("Attempt to append a value that is too large {0} > {}", MAX_VALUE)]
     100              :     AppendOverflow(u64),
     101              : 
     102              :     #[error("Unsorted input: key {key:?} is <= last_key {last_key:?}")]
     103              :     UnsortedInput { key: Box<[u8]>, last_key: Box<[u8]> },
     104              : 
     105              :     #[error("Could not push to new leaf node")]
     106              :     FailedToPushToNewLeafNode,
     107              : 
     108              :     #[error("IoError: {0}")]
     109              :     Io(#[from] io::Error),
     110              : }
     111              : 
     112              : pub type Result<T> = result::Result<T, DiskBtreeError>;
     113              : 
     114              : /// This is the on-disk representation.
     115              : struct OnDiskNode<'a, const L: usize> {
     116              :     // Fixed-width fields
     117              :     num_children: u16,
     118              :     level: u8,
     119              :     prefix_len: u8,
     120              :     suffix_len: u8,
     121              : 
     122              :     // Variable-length fields. These are stored on-disk after the fixed-width
     123              :     // fields, in this order. In the in-memory representation, these point to
     124              :     // the right parts in the page buffer.
     125              :     prefix: &'a [u8],
     126              :     keys: &'a [u8],
     127              :     values: &'a [u8],
     128              : }
     129              : 
     130              : impl<const L: usize> OnDiskNode<'_, L> {
     131              :     ///
     132              :     /// Interpret a PAGE_SZ page as a node.
     133              :     ///
     134       803221 :     fn deparse(buf: &[u8]) -> Result<OnDiskNode<L>> {
     135       803221 :         let mut cursor = std::io::Cursor::new(buf);
     136       803221 :         let num_children = cursor.read_u16::<BE>()?;
     137       803221 :         let level = cursor.read_u8()?;
     138       803221 :         let prefix_len = cursor.read_u8()?;
     139       803221 :         let suffix_len = cursor.read_u8()?;
     140              : 
     141       803221 :         let mut off = cursor.position();
     142       803221 :         let prefix_off = off as usize;
     143       803221 :         off += prefix_len as u64;
     144              : 
     145       803221 :         let keys_off = off as usize;
     146       803221 :         let keys_len = num_children as usize * suffix_len as usize;
     147       803221 :         off += keys_len as u64;
     148              : 
     149       803221 :         let values_off = off as usize;
     150       803221 :         let values_len = num_children as usize * VALUE_SZ;
     151              :         //off += values_len as u64;
     152              : 
     153       803221 :         let prefix = &buf[prefix_off..prefix_off + prefix_len as usize];
     154       803221 :         let keys = &buf[keys_off..keys_off + keys_len];
     155       803221 :         let values = &buf[values_off..values_off + values_len];
     156              : 
     157       803221 :         Ok(OnDiskNode {
     158       803221 :             num_children,
     159       803221 :             level,
     160       803221 :             prefix_len,
     161       803221 :             suffix_len,
     162       803221 :             prefix,
     163       803221 :             keys,
     164       803221 :             values,
     165       803221 :         })
     166       803221 :     }
     167              : 
     168              :     ///
     169              :     /// Read a value at 'idx'
     170              :     ///
     171      4573264 :     fn value(&self, idx: usize) -> Value {
     172      4573264 :         let value_off = idx * VALUE_SZ;
     173      4573264 :         let value_slice = &self.values[value_off..value_off + VALUE_SZ];
     174      4573264 :         Value::from_slice(value_slice)
     175      4573264 :     }
     176              : 
     177       688012 :     fn binary_search(
     178       688012 :         &self,
     179       688012 :         search_key: &[u8; L],
     180       688012 :         keybuf: &mut [u8],
     181       688012 :     ) -> result::Result<usize, usize> {
     182       688012 :         let mut size = self.num_children as usize;
     183       688012 :         let mut low = 0;
     184       688012 :         let mut high = size;
     185      5130761 :         while low < high {
     186      4579222 :             let mid = low + size / 2;
     187              : 
     188      4579222 :             let key_off = mid * self.suffix_len as usize;
     189      4579222 :             let suffix = &self.keys[key_off..key_off + self.suffix_len as usize];
     190              :             // Does this match?
     191      4579222 :             keybuf[self.prefix_len as usize..].copy_from_slice(suffix);
     192              : 
     193      4579222 :             let cmp = keybuf[..].cmp(search_key);
     194              : 
     195      4579222 :             if cmp == Ordering::Less {
     196      2856854 :                 low = mid + 1;
     197      2856854 :             } else if cmp == Ordering::Greater {
     198      1585895 :                 high = mid;
     199      1585895 :             } else {
     200       136473 :                 return Ok(mid);
     201              :             }
     202      4442749 :             size = high - low;
     203              :         }
     204       551539 :         Err(low)
     205       688012 :     }
     206              : }
     207              : 
     208              : ///
     209              : /// Public reader object, to search the tree.
     210              : ///
     211              : #[derive(Clone)]
     212              : pub struct DiskBtreeReader<R, const L: usize>
     213              : where
     214              :     R: BlockReader,
     215              : {
     216              :     start_blk: u32,
     217              :     root_blk: u32,
     218              :     reader: R,
     219              : }
     220              : 
     221              : #[derive(Clone, Copy, Debug, PartialEq, Eq)]
     222              : pub enum VisitDirection {
     223              :     Forwards,
     224              :     Backwards,
     225              : }
     226              : 
     227              : impl<R, const L: usize> DiskBtreeReader<R, L>
     228              : where
     229              :     R: BlockReader,
     230              : {
     231       139531 :     pub fn new(start_blk: u32, root_blk: u32, reader: R) -> Self {
     232       139531 :         DiskBtreeReader {
     233       139531 :             start_blk,
     234       139531 :             root_blk,
     235       139531 :             reader,
     236       139531 :         }
     237       139531 :     }
     238              : 
     239              :     ///
     240              :     /// Read the value for given key. Returns the value, or None if it doesn't exist.
     241              :     ///
     242       201560 :     pub async fn get(&self, search_key: &[u8; L], ctx: &RequestContext) -> Result<Option<u64>> {
     243       201560 :         let mut result: Option<u64> = None;
     244       201560 :         self.visit(
     245       201560 :             search_key,
     246       201560 :             VisitDirection::Forwards,
     247       101548 :             |key, value| {
     248       101548 :                 if key == search_key {
     249       100545 :                     result = Some(value);
     250       100545 :                 }
     251       101548 :                 false
     252       101548 :             },
     253       201560 :             ctx,
     254              :         )
     255       201560 :         .await?;
     256       201560 :         Ok(result)
     257       201560 :     }
     258              : 
     259          352 :     pub fn iter<'a>(self, start_key: &'a [u8; L], ctx: &'a RequestContext) -> DiskBtreeIterator<'a>
     260          352 :     where
     261          352 :         R: 'a + Send,
     262              :     {
     263          352 :         DiskBtreeIterator {
     264          352 :             stream: Box::pin(self.into_stream(start_key, ctx)),
     265          352 :         }
     266          352 :     }
     267              : 
     268              :     /// Return a stream which yields all key, value pairs from the index
     269              :     /// starting from the first key greater or equal to `start_key`.
     270              :     ///
     271              :     /// Note 1: that this is a copy of [`Self::visit`].
     272              :     /// TODO: Once the sequential read path is removed this will become
     273              :     /// the only index traversal method.
     274              :     ///
     275              :     /// Note 2: this function used to take `&self` but it now consumes `self`. This is due to
     276              :     /// the lifetime constraints of the reader and the stream / iterator it creates. Using `&self`
     277              :     /// requires the reader to be present when the stream is used, and this creates a lifetime
     278              :     /// dependency between the reader and the stream. Now if we want to create an iterator that
     279              :     /// holds the stream, someone will need to keep a reference to the reader, which is inconvenient
     280              :     /// to use from the image/delta layer APIs.
     281              :     ///
     282              :     /// Feel free to add the `&self` variant back if it's necessary.
     283       149227 :     pub fn into_stream<'a>(
     284       149227 :         self,
     285       149227 :         start_key: &'a [u8; L],
     286       149227 :         ctx: &'a RequestContext,
     287       149227 :     ) -> impl Stream<Item = std::result::Result<(Vec<u8>, u64), DiskBtreeError>> + 'a
     288       149227 :     where
     289       149227 :         R: 'a,
     290              :     {
     291       149227 :         try_stream! {
     292              :             let mut stack = Vec::new();
     293              :             stack.push((self.root_blk, None));
     294              :             let block_cursor = self.reader.block_cursor();
     295              :             let mut node_buf = [0_u8; PAGE_SZ];
     296              :             while let Some((node_blknum, opt_iter)) = stack.pop() {
     297              :                 // Read the node, through the PS PageCache, into local variable `node_buf`.
     298              :                 // We could keep the page cache read guard alive, but, at the time of writing,
     299              :                 // we run quite small PS PageCache s => can't risk running out of
     300              :                 // PageCache space because this stream isn't consumed fast enough.
     301              :                 let page_read_guard = block_cursor
     302              :                     .read_blk(self.start_blk + node_blknum, ctx)
     303              :                     .await?;
     304              :                 node_buf.copy_from_slice(page_read_guard.as_ref());
     305              :                 drop(page_read_guard); // drop page cache read guard early
     306              : 
     307              :                 let node = OnDiskNode::deparse(&node_buf)?;
     308              :                 let prefix_len = node.prefix_len as usize;
     309              :                 let suffix_len = node.suffix_len as usize;
     310              : 
     311              :                 assert!(node.num_children > 0);
     312              : 
     313              :                 let mut keybuf = Vec::new();
     314              :                 keybuf.extend(node.prefix);
     315              :                 keybuf.resize(prefix_len + suffix_len, 0);
     316              : 
     317              :                 let mut iter: Either<Range<usize>, Rev<RangeInclusive<usize>>> = if let Some(iter) = opt_iter {
     318              :                     iter
     319              :                 } else {
     320              :                     // Locate the first match
     321              :                     let idx = match node.binary_search(start_key, keybuf.as_mut_slice()) {
     322              :                         Ok(idx) => idx,
     323              :                         Err(idx) => {
     324              :                             if node.level == 0 {
     325              :                                 // Imagine that the node contains the following keys:
     326              :                                 //
     327              :                                 // 1
     328              :                                 // 3  <-- idx
     329              :                                 // 5
     330              :                                 //
     331              :                                 // If the search key is '2' and there is exact match,
     332              :                                 // the binary search would return the index of key
     333              :                                 // '3'. That's cool, '3' is the first key to return.
     334              :                                 idx
     335              :                             } else {
     336              :                                 // This is an internal page, so each key represents a lower
     337              :                                 // bound for what's in the child page. If there is no exact
     338              :                                 // match, we have to return the *previous* entry.
     339              :                                 //
     340              :                                 // 1  <-- return this
     341              :                                 // 3  <-- idx
     342              :                                 // 5
     343              :                                 idx.saturating_sub(1)
     344              :                             }
     345              :                         }
     346              :                     };
     347              :                     Either::Left(idx..node.num_children.into())
     348              :                 };
     349              : 
     350              : 
     351              :                 // idx points to the first match now. Keep going from there
     352              :                 while let Some(idx) = iter.next() {
     353              :                     let key_off = idx * suffix_len;
     354              :                     let suffix = &node.keys[key_off..key_off + suffix_len];
     355              :                     keybuf[prefix_len..].copy_from_slice(suffix);
     356              :                     let value = node.value(idx);
     357              :                     #[allow(clippy::collapsible_if)]
     358              :                     if node.level == 0 {
     359              :                         // leaf
     360              :                         yield (keybuf.clone(), value.to_u64());
     361              :                     } else {
     362              :                         stack.push((node_blknum, Some(iter)));
     363              :                         stack.push((value.to_blknum(), None));
     364              :                         break;
     365              :                     }
     366              :                 }
     367              :             }
     368              :         }
     369       149227 :     }
     370              : 
     371              :     ///
     372              :     /// Scan the tree, starting from 'search_key', in the given direction. 'visitor'
     373              :     /// will be called for every key >= 'search_key' (or <= 'search_key', if scanning
     374              :     /// backwards)
     375              :     ///
     376       205790 :     pub async fn visit<V>(
     377       205790 :         &self,
     378       205790 :         search_key: &[u8; L],
     379       205790 :         dir: VisitDirection,
     380       205790 :         mut visitor: V,
     381       205790 :         ctx: &RequestContext,
     382       205790 :     ) -> Result<bool>
     383       205790 :     where
     384       205790 :         V: FnMut(&[u8], u64) -> bool,
     385       205790 :     {
     386       205790 :         let mut stack = Vec::new();
     387       205790 :         stack.push((self.root_blk, None));
     388       205790 :         let block_cursor = self.reader.block_cursor();
     389       609493 :         while let Some((node_blknum, opt_iter)) = stack.pop() {
     390              :             // Locate the node.
     391       509226 :             let node_buf = block_cursor
     392       509226 :                 .read_blk(self.start_blk + node_blknum, ctx)
     393       509226 :                 .await?;
     394              : 
     395       509226 :             let node = OnDiskNode::deparse(node_buf.as_ref())?;
     396       509226 :             let prefix_len = node.prefix_len as usize;
     397       509226 :             let suffix_len = node.suffix_len as usize;
     398              : 
     399       509226 :             assert!(node.num_children > 0);
     400              : 
     401       509226 :             let mut keybuf = Vec::new();
     402       509226 :             keybuf.extend(node.prefix);
     403       509226 :             keybuf.resize(prefix_len + suffix_len, 0);
     404              : 
     405       509226 :             let mut iter = if let Some(iter) = opt_iter {
     406       101949 :                 iter
     407       407277 :             } else if dir == VisitDirection::Forwards {
     408              :                 // Locate the first match
     409       405264 :                 let idx = match node.binary_search(search_key, keybuf.as_mut_slice()) {
     410       101648 :                     Ok(idx) => idx,
     411       303616 :                     Err(idx) => {
     412       303616 :                         if node.level == 0 {
     413              :                             // Imagine that the node contains the following keys:
     414              :                             //
     415              :                             // 1
     416              :                             // 3  <-- idx
     417              :                             // 5
     418              :                             //
     419              :                             // If the search key is '2' and there is exact match,
     420              :                             // the binary search would return the index of key
     421              :                             // '3'. That's cool, '3' is the first key to return.
     422       104058 :                             idx
     423              :                         } else {
     424              :                             // This is an internal page, so each key represents a lower
     425              :                             // bound for what's in the child page. If there is no exact
     426              :                             // match, we have to return the *previous* entry.
     427              :                             //
     428              :                             // 1  <-- return this
     429              :                             // 3  <-- idx
     430              :                             // 5
     431       199558 :                             idx.saturating_sub(1)
     432              :                         }
     433              :                     }
     434              :                 };
     435       405264 :                 Either::Left(idx..node.num_children.into())
     436              :             } else {
     437         2013 :                 let idx = match node.binary_search(search_key, keybuf.as_mut_slice()) {
     438         1001 :                     Ok(idx) => {
     439              :                         // Exact match. That's the first entry to return, and walk
     440              :                         // backwards from there.
     441         1001 :                         idx
     442              :                     }
     443         1012 :                     Err(idx) => {
     444              :                         // No exact match. The binary search returned the index of the
     445              :                         // first key that's > search_key. Back off by one, and walk
     446              :                         // backwards from there.
     447         1012 :                         if let Some(idx) = idx.checked_sub(1) {
     448         1010 :                             idx
     449              :                         } else {
     450            2 :                             return Ok(false);
     451              :                         }
     452              :                     }
     453              :                 };
     454         2011 :                 Either::Right((0..=idx).rev())
     455              :             };
     456              : 
     457              :             // idx points to the first match now. Keep going from there
     458      1581201 :             while let Some(idx) = iter.next() {
     459      1378985 :                 let key_off = idx * suffix_len;
     460      1378985 :                 let suffix = &node.keys[key_off..key_off + suffix_len];
     461      1378985 :                 keybuf[prefix_len..].copy_from_slice(suffix);
     462      1378985 :                 let value = node.value(idx);
     463              :                 #[allow(clippy::collapsible_if)]
     464      1378985 :                 if node.level == 0 {
     465              :                     // leaf
     466      1177498 :                     if !visitor(&keybuf, value.to_u64()) {
     467       105521 :                         return Ok(false);
     468      1071977 :                     }
     469              :                 } else {
     470       201487 :                     stack.push((node_blknum, Some(iter)));
     471       201487 :                     stack.push((value.to_blknum(), None));
     472       201487 :                     break;
     473              :                 }
     474              :             }
     475              :         }
     476       100267 :         Ok(true)
     477       205790 :     }
     478              : 
     479              :     #[allow(dead_code)]
     480            5 :     pub async fn dump(&self, ctx: &RequestContext) -> Result<()> {
     481            5 :         let mut stack = Vec::new();
     482              : 
     483            5 :         stack.push((self.root_blk, String::new(), 0, 0, 0));
     484              : 
     485            5 :         let block_cursor = self.reader.block_cursor();
     486              : 
     487         3021 :         while let Some((blknum, path, depth, child_idx, key_off)) = stack.pop() {
     488         3016 :             let blk = block_cursor.read_blk(self.start_blk + blknum, ctx).await?;
     489         3016 :             let buf: &[u8] = blk.as_ref();
     490         3016 :             let node = OnDiskNode::<L>::deparse(buf)?;
     491              : 
     492         3016 :             if child_idx == 0 {
     493            9 :                 print!("{:indent$}", "", indent = depth * 2);
     494            9 :                 let path_prefix = stack
     495            9 :                     .iter()
     496            9 :                     .map(|(_blknum, path, ..)| path.as_str())
     497            9 :                     .collect::<String>();
     498            9 :                 println!(
     499            9 :                     "blk #{blknum}: path {path_prefix}{path}: prefix {}, suffix_len {}",
     500            9 :                     hex::encode(node.prefix),
     501              :                     node.suffix_len
     502              :                 );
     503         3007 :             }
     504              : 
     505         3016 :             if child_idx + 1 < node.num_children {
     506         3007 :                 let key_off = key_off + node.suffix_len as usize;
     507         3007 :                 stack.push((blknum, path.clone(), depth, child_idx + 1, key_off));
     508         3007 :             }
     509         3016 :             let key = &node.keys[key_off..key_off + node.suffix_len as usize];
     510         3016 :             let val = node.value(child_idx as usize);
     511              : 
     512         3016 :             print!("{:indent$}", "", indent = depth * 2 + 2);
     513         3016 :             println!("{}: {}", hex::encode(key), hex::encode(val.0));
     514              : 
     515         3016 :             if node.level > 0 {
     516            4 :                 stack.push((val.to_blknum(), hex::encode(node.prefix), depth + 1, 0, 0));
     517         3012 :             }
     518              :         }
     519            5 :         Ok(())
     520            5 :     }
     521              : }
     522              : 
     523              : pub struct DiskBtreeIterator<'a> {
     524              :     #[allow(clippy::type_complexity)]
     525              :     stream: std::pin::Pin<
     526              :         Box<dyn Stream<Item = std::result::Result<(Vec<u8>, u64), DiskBtreeError>> + 'a + Send>,
     527              :     >,
     528              : }
     529              : 
     530              : impl DiskBtreeIterator<'_> {
     531      1161890 :     pub async fn next(&mut self) -> Option<std::result::Result<(Vec<u8>, u64), DiskBtreeError>> {
     532      1161890 :         self.stream.next().await
     533      1161890 :     }
     534              : }
     535              : 
     536              : ///
     537              : /// Public builder object, for creating a new tree.
     538              : ///
     539              : /// Usage: Create a builder object by calling 'new', load all the data into the
     540              : /// tree by calling 'append' for each key-value pair, and then call 'finish'
     541              : ///
     542              : /// 'L' is the key length in bytes
     543              : pub struct DiskBtreeBuilder<W, const L: usize>
     544              : where
     545              :     W: BlockWriter,
     546              : {
     547              :     writer: W,
     548              : 
     549              :     ///
     550              :     /// `stack[0]` is the current root page, `stack.last()` is the leaf.
     551              :     ///
     552              :     /// We maintain the length of the stack to be always greater than zero.
     553              :     /// Two exceptions are:
     554              :     /// 1. `Self::flush_node`. The method will push the new node if it extracted the last one.
     555              :     ///    So because other methods cannot see the intermediate state invariant still holds.
     556              :     /// 2. `Self::finish`. It consumes self and does not return it back,
     557              :     ///    which means that this is where the structure is destroyed.
     558              :     ///    Thus stack of zero length cannot be observed by other methods.
     559              :     stack: Vec<BuildNode<L>>,
     560              : 
     561              :     /// Last key that was appended to the tree. Used to sanity check that append
     562              :     /// is called in increasing key order.
     563              :     last_key: Option<[u8; L]>,
     564              : }
     565              : 
     566              : impl<W, const L: usize> DiskBtreeBuilder<W, L>
     567              : where
     568              :     W: BlockWriter,
     569              : {
     570         1123 :     pub fn new(writer: W) -> Self {
     571         1123 :         DiskBtreeBuilder {
     572         1123 :             writer,
     573         1123 :             last_key: None,
     574         1123 :             stack: vec![BuildNode::new(0)],
     575         1123 :         }
     576         1123 :     }
     577              : 
     578      3374338 :     pub fn append(&mut self, key: &[u8; L], value: u64) -> Result<()> {
     579      3374338 :         if value > MAX_VALUE {
     580            0 :             return Err(DiskBtreeError::AppendOverflow(value));
     581      3374338 :         }
     582      3374338 :         if let Some(last_key) = &self.last_key {
     583      3373379 :             if key <= last_key {
     584            1 :                 return Err(DiskBtreeError::UnsortedInput {
     585            1 :                     key: key.as_slice().into(),
     586            1 :                     last_key: last_key.as_slice().into(),
     587            1 :                 });
     588      3373378 :             }
     589          959 :         }
     590      3374337 :         self.last_key = Some(*key);
     591              : 
     592      3374337 :         self.append_internal(key, Value::from_u64(value))
     593      3374338 :     }
     594              : 
     595      3380583 :     fn append_internal(&mut self, key: &[u8; L], value: Value) -> Result<()> {
     596              :         // Try to append to the current leaf buffer
     597      3380583 :         let last = self
     598      3380583 :             .stack
     599      3380583 :             .last_mut()
     600      3380583 :             .expect("should always have at least one item");
     601      3380583 :         let level = last.level;
     602      3380583 :         if last.push(key, value) {
     603      3368725 :             return Ok(());
     604        11858 :         }
     605              : 
     606              :         // It did not fit. Try to compress, and if it succeeds to make
     607              :         // some room on the node, try appending to it again.
     608              :         #[allow(clippy::collapsible_if)]
     609        11858 :         if last.compress() {
     610         6024 :             if last.push(key, value) {
     611         6023 :                 return Ok(());
     612            1 :             }
     613         5834 :         }
     614              : 
     615              :         // Could not append to the current leaf. Flush it and create a new one.
     616         5835 :         self.flush_node()?;
     617              : 
     618              :         // Replace the node we flushed with an empty one and append the new
     619              :         // key to it.
     620         5835 :         let mut last = BuildNode::new(level);
     621         5835 :         if !last.push(key, value) {
     622            0 :             return Err(DiskBtreeError::FailedToPushToNewLeafNode);
     623         5835 :         }
     624              : 
     625         5835 :         self.stack.push(last);
     626              : 
     627         5835 :         Ok(())
     628      3380583 :     }
     629              : 
     630              :     /// Flush the bottommost node in the stack to disk. Appends a downlink to its parent,
     631              :     /// and recursively flushes the parent too, if it becomes full. If the root page becomes full,
     632              :     /// creates a new root page, increasing the height of the tree.
     633         6246 :     fn flush_node(&mut self) -> Result<()> {
     634              :         // Get the current bottommost node in the stack and flush it to disk.
     635         6246 :         let last = self
     636         6246 :             .stack
     637         6246 :             .pop()
     638         6246 :             .expect("should always have at least one item");
     639         6246 :         let buf = last.pack();
     640         6246 :         let downlink_key = last.first_key();
     641         6246 :         let downlink_ptr = self.writer.write_blk(buf)?;
     642              : 
     643              :         // Append the downlink to the parent. If there is no parent, ie. this was the root page,
     644              :         // create a new root page, increasing the height of the tree.
     645         6246 :         if self.stack.is_empty() {
     646          411 :             self.stack.push(BuildNode::new(last.level + 1));
     647         5835 :         }
     648         6246 :         self.append_internal(&downlink_key, Value::from_blknum(downlink_ptr))
     649         6246 :     }
     650              : 
     651              :     ///
     652              :     /// Flushes everything to disk, and returns the block number of the root page.
     653              :     /// The caller must store the root block number "out-of-band", and pass it
     654              :     /// to the DiskBtreeReader::new() when you want to read the tree again.
     655              :     /// (In the image and delta layers, it is stored in the beginning of the file,
     656              :     /// in the summary header)
     657              :     ///
     658          934 :     pub fn finish(mut self) -> Result<(u32, W)> {
     659              :         // flush all levels, except the root.
     660         1345 :         while self.stack.len() > 1 {
     661          411 :             self.flush_node()?;
     662              :         }
     663              : 
     664          934 :         let root = self
     665          934 :             .stack
     666          934 :             .first()
     667          934 :             .expect("by the check above we left one item there");
     668          934 :         let buf = root.pack();
     669          934 :         let root_blknum = self.writer.write_blk(buf)?;
     670              : 
     671          934 :         Ok((root_blknum, self.writer))
     672          934 :     }
     673              : 
     674      1029527 :     pub fn borrow_writer(&self) -> &W {
     675      1029527 :         &self.writer
     676      1029527 :     }
     677              : }
     678              : 
     679              : ///
     680              : /// BuildNode represesnts an incomplete page that we are appending to.
     681              : ///
     682              : #[derive(Clone, Debug)]
     683              : struct BuildNode<const L: usize> {
     684              :     num_children: u16,
     685              :     level: u8,
     686              :     prefix: Vec<u8>,
     687              :     suffix_len: usize,
     688              : 
     689              :     keys: Vec<u8>,
     690              :     values: Vec<u8>,
     691              : 
     692              :     size: usize, // physical size of this node, if it was written to disk like this
     693              : }
     694              : 
     695              : const NODE_SIZE: usize = PAGE_SZ;
     696              : 
     697              : const NODE_HDR_SIZE: usize = 2 + 1 + 1 + 1;
     698              : 
     699              : impl<const L: usize> BuildNode<L> {
     700         7369 :     fn new(level: u8) -> Self {
     701         7369 :         BuildNode {
     702         7369 :             num_children: 0,
     703         7369 :             level,
     704         7369 :             prefix: Vec::new(),
     705         7369 :             suffix_len: 0,
     706         7369 :             keys: Vec::new(),
     707         7369 :             values: Vec::new(),
     708         7369 :             size: NODE_HDR_SIZE,
     709         7369 :         }
     710         7369 :     }
     711              : 
     712              :     /// Try to append a key-value pair to this node. Returns 'true' on
     713              :     /// success, 'false' if the page was full or the key was
     714              :     /// incompatible with the prefix of the existing keys.
     715      3392442 :     fn push(&mut self, key: &[u8; L], value: Value) -> bool {
     716              :         // If we have already performed prefix-compression on the page,
     717              :         // check that the incoming key has the same prefix.
     718      3392442 :         if self.num_children > 0 {
     719              :             // does the prefix allow it?
     720      3385237 :             if !key.starts_with(&self.prefix) {
     721          104 :                 return false;
     722      3385133 :             }
     723         7205 :         } else {
     724         7205 :             self.suffix_len = key.len();
     725         7205 :         }
     726              : 
     727              :         // Is the node too full?
     728      3392338 :         if self.size + self.suffix_len + VALUE_SZ >= NODE_SIZE {
     729        11755 :             return false;
     730      3380583 :         }
     731              : 
     732              :         // All clear
     733      3380583 :         self.num_children += 1;
     734      3380583 :         self.keys.extend(&key[self.prefix.len()..]);
     735      3380583 :         self.values.extend(value.0);
     736              : 
     737      3380583 :         assert!(self.keys.len() == self.num_children as usize * self.suffix_len);
     738      3380583 :         assert!(self.values.len() == self.num_children as usize * VALUE_SZ);
     739              : 
     740      3380583 :         self.size += self.suffix_len + VALUE_SZ;
     741              : 
     742      3380583 :         true
     743      3392442 :     }
     744              : 
     745              :     ///
     746              :     /// Perform prefix-compression.
     747              :     ///
     748              :     /// Returns 'true' on success, 'false' if no compression was possible.
     749              :     ///
     750        11858 :     fn compress(&mut self) -> bool {
     751        11858 :         let first_suffix = self.first_suffix();
     752        11858 :         let last_suffix = self.last_suffix();
     753              : 
     754              :         // Find the common prefix among all keys
     755        11858 :         let mut prefix_len = 0;
     756       107947 :         while prefix_len < self.suffix_len {
     757       107947 :             if first_suffix[prefix_len] != last_suffix[prefix_len] {
     758        11858 :                 break;
     759        96089 :             }
     760        96089 :             prefix_len += 1;
     761              :         }
     762        11858 :         if prefix_len == 0 {
     763         5834 :             return false;
     764         6024 :         }
     765              : 
     766              :         // Can compress. Rewrite the keys without the common prefix.
     767         6024 :         self.prefix.extend(&self.keys[..prefix_len]);
     768              : 
     769         6024 :         let mut new_keys = Vec::new();
     770         6024 :         let mut key_off = 0;
     771      1611489 :         while key_off < self.keys.len() {
     772      1605465 :             let next_key_off = key_off + self.suffix_len;
     773      1605465 :             new_keys.extend(&self.keys[key_off + prefix_len..next_key_off]);
     774      1605465 :             key_off = next_key_off;
     775      1605465 :         }
     776         6024 :         self.keys = new_keys;
     777         6024 :         self.suffix_len -= prefix_len;
     778              : 
     779         6024 :         self.size -= prefix_len * self.num_children as usize;
     780         6024 :         self.size += prefix_len;
     781              : 
     782         6024 :         assert!(self.keys.len() == self.num_children as usize * self.suffix_len);
     783         6024 :         assert!(self.values.len() == self.num_children as usize * VALUE_SZ);
     784              : 
     785         6024 :         true
     786        11858 :     }
     787              : 
     788              :     ///
     789              :     /// Serialize the node to on-disk format.
     790              :     ///
     791         7180 :     fn pack(&self) -> IoBuffer {
     792         7180 :         assert!(self.keys.len() == self.num_children as usize * self.suffix_len);
     793         7180 :         assert!(self.values.len() == self.num_children as usize * VALUE_SZ);
     794         7180 :         assert!(self.num_children > 0);
     795              : 
     796         7180 :         let mut buf = IoBufferMut::with_capacity(PAGE_SZ);
     797              : 
     798         7180 :         buf.put_u16(self.num_children);
     799         7180 :         buf.put_u8(self.level);
     800         7180 :         buf.put_u8(self.prefix.len() as u8);
     801         7180 :         buf.put_u8(self.suffix_len as u8);
     802         7180 :         buf.put(&self.prefix[..]);
     803         7180 :         buf.put(&self.keys[..]);
     804         7180 :         buf.put(&self.values[..]);
     805              : 
     806         7180 :         assert!(buf.len() == self.size);
     807              : 
     808         7180 :         assert!(buf.len() <= PAGE_SZ);
     809         7180 :         buf.extend_with(0, PAGE_SZ - buf.len());
     810         7180 :         buf.freeze()
     811         7180 :     }
     812              : 
     813        18104 :     fn first_suffix(&self) -> &[u8] {
     814        18104 :         &self.keys[..self.suffix_len]
     815        18104 :     }
     816        11858 :     fn last_suffix(&self) -> &[u8] {
     817        11858 :         &self.keys[self.keys.len() - self.suffix_len..]
     818        11858 :     }
     819              : 
     820              :     /// Return the full first key of the page, including the prefix
     821         6246 :     fn first_key(&self) -> [u8; L] {
     822         6246 :         let mut key = [0u8; L];
     823         6246 :         key[..self.prefix.len()].copy_from_slice(&self.prefix);
     824         6246 :         key[self.prefix.len()..].copy_from_slice(self.first_suffix());
     825         6246 :         key
     826         6246 :     }
     827              : }
     828              : 
     829              : #[cfg(test)]
     830              : pub(crate) mod tests {
     831              :     use std::collections::BTreeMap;
     832              :     use std::sync::atomic::{AtomicUsize, Ordering};
     833              : 
     834              :     use rand::Rng;
     835              : 
     836              :     use super::*;
     837              :     use crate::context::DownloadBehavior;
     838              :     use crate::task_mgr::TaskKind;
     839              :     use crate::tenant::block_io::{BlockCursor, BlockLease, BlockReaderRef};
     840              : 
     841              :     #[derive(Clone, Default)]
     842              :     pub(crate) struct TestDisk {
     843              :         blocks: Vec<IoBuffer>,
     844              :     }
     845              :     impl TestDisk {
     846            5 :         fn new() -> Self {
     847            5 :             Self::default()
     848            5 :         }
     849       508346 :         pub(crate) fn read_blk(&self, blknum: u32) -> io::Result<BlockLease> {
     850       508346 :             let mut buf = [0u8; PAGE_SZ];
     851       508346 :             buf.copy_from_slice(&self.blocks[blknum as usize]);
     852       508346 :             Ok(std::sync::Arc::new(buf).into())
     853       508346 :         }
     854              :     }
     855              :     impl BlockReader for TestDisk {
     856       205593 :         fn block_cursor(&self) -> BlockCursor<'_> {
     857       205593 :             BlockCursor::new(BlockReaderRef::TestDisk(self))
     858       205593 :         }
     859              :     }
     860              :     impl BlockWriter for &mut TestDisk {
     861          107 :         fn write_blk(&mut self, buf: IoBuffer) -> io::Result<u32> {
     862          107 :             let blknum = self.blocks.len();
     863          107 :             self.blocks.push(buf);
     864          107 :             Ok(blknum as u32)
     865          107 :         }
     866              :     }
     867              : 
     868              :     #[tokio::test]
     869            1 :     async fn basic() -> Result<()> {
     870            1 :         let mut disk = TestDisk::new();
     871            1 :         let mut writer = DiskBtreeBuilder::<_, 6>::new(&mut disk);
     872              : 
     873            1 :         let ctx =
     874            1 :             RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error).with_scope_unit_test();
     875              : 
     876            1 :         let all_keys: Vec<&[u8; 6]> = vec![
     877            1 :             b"xaaaaa", b"xaaaba", b"xaaaca", b"xabaaa", b"xababa", b"xabaca", b"xabada", b"xabadb",
     878              :         ];
     879            1 :         let all_data: Vec<(&[u8; 6], u64)> = all_keys
     880            1 :             .iter()
     881            1 :             .enumerate()
     882            8 :             .map(|(idx, key)| (*key, idx as u64))
     883            1 :             .collect();
     884            8 :         for (key, val) in all_data.iter() {
     885            8 :             writer.append(key, *val)?;
     886              :         }
     887              : 
     888            1 :         let (root_offset, _writer) = writer.finish()?;
     889              : 
     890            1 :         let reader = DiskBtreeReader::new(0, root_offset, disk);
     891              : 
     892            1 :         reader.dump(&ctx).await?;
     893              : 
     894              :         // Test the `get` function on all the keys.
     895            8 :         for (key, val) in all_data.iter() {
     896            8 :             assert_eq!(reader.get(key, &ctx).await?, Some(*val));
     897              :         }
     898              :         // And on some keys that don't exist
     899            1 :         assert_eq!(reader.get(b"aaaaaa", &ctx).await?, None);
     900            1 :         assert_eq!(reader.get(b"zzzzzz", &ctx).await?, None);
     901            1 :         assert_eq!(reader.get(b"xaaabx", &ctx).await?, None);
     902              : 
     903              :         // Test search with `visit` function
     904            1 :         let search_key = b"xabaaa";
     905            1 :         let expected: Vec<(Vec<u8>, u64)> = all_data
     906            1 :             .iter()
     907            8 :             .filter(|(key, _value)| key[..] >= search_key[..])
     908            5 :             .map(|(key, value)| (key.to_vec(), *value))
     909            1 :             .collect();
     910              : 
     911            1 :         let mut data = Vec::new();
     912            1 :         reader
     913            1 :             .visit(
     914            1 :                 search_key,
     915            1 :                 VisitDirection::Forwards,
     916            5 :                 |key, value| {
     917            5 :                     data.push((key.to_vec(), value));
     918            5 :                     true
     919            5 :                 },
     920            1 :                 &ctx,
     921              :             )
     922            1 :             .await?;
     923            1 :         assert_eq!(data, expected);
     924              : 
     925              :         // Test a backwards scan
     926            1 :         let mut expected: Vec<(Vec<u8>, u64)> = all_data
     927            1 :             .iter()
     928            8 :             .filter(|(key, _value)| key[..] <= search_key[..])
     929            4 :             .map(|(key, value)| (key.to_vec(), *value))
     930            1 :             .collect();
     931            1 :         expected.reverse();
     932            1 :         let mut data = Vec::new();
     933            1 :         reader
     934            1 :             .visit(
     935            1 :                 search_key,
     936            1 :                 VisitDirection::Backwards,
     937            4 :                 |key, value| {
     938            4 :                     data.push((key.to_vec(), value));
     939            4 :                     true
     940            4 :                 },
     941            1 :                 &ctx,
     942              :             )
     943            1 :             .await?;
     944            1 :         assert_eq!(data, expected);
     945              : 
     946              :         // Backward scan where nothing matches
     947            1 :         reader
     948            1 :             .visit(
     949            1 :                 b"aaaaaa",
     950            1 :                 VisitDirection::Backwards,
     951            0 :                 |key, value| {
     952            0 :                     panic!("found unexpected key {}: {}", hex::encode(key), value);
     953              :                 },
     954            1 :                 &ctx,
     955              :             )
     956            1 :             .await?;
     957              : 
     958              :         // Full scan
     959            1 :         let expected: Vec<(Vec<u8>, u64)> = all_data
     960            1 :             .iter()
     961            8 :             .map(|(key, value)| (key.to_vec(), *value))
     962            1 :             .collect();
     963            1 :         let mut data = Vec::new();
     964            1 :         reader
     965            1 :             .visit(
     966            1 :                 &[0u8; 6],
     967            1 :                 VisitDirection::Forwards,
     968            8 :                 |key, value| {
     969            8 :                     data.push((key.to_vec(), value));
     970            8 :                     true
     971            8 :                 },
     972            1 :                 &ctx,
     973              :             )
     974            1 :             .await?;
     975            1 :         assert_eq!(data, expected);
     976              : 
     977            2 :         Ok(())
     978            1 :     }
     979              : 
     980              :     #[tokio::test]
     981            1 :     async fn lots_of_keys() -> Result<()> {
     982            1 :         let mut disk = TestDisk::new();
     983            1 :         let mut writer = DiskBtreeBuilder::<_, 8>::new(&mut disk);
     984            1 :         let ctx =
     985            1 :             RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error).with_scope_unit_test();
     986              : 
     987              :         const NUM_KEYS: u64 = 1000;
     988              : 
     989            1 :         let mut all_data: BTreeMap<u64, u64> = BTreeMap::new();
     990              : 
     991         1001 :         for idx in 0..NUM_KEYS {
     992         1000 :             let key_int: u64 = 1 + idx * 2;
     993         1000 :             let key = u64::to_be_bytes(key_int);
     994         1000 :             writer.append(&key, idx)?;
     995              : 
     996         1000 :             all_data.insert(key_int, idx);
     997              :         }
     998              : 
     999            1 :         let (root_offset, _writer) = writer.finish()?;
    1000              : 
    1001            1 :         let reader = DiskBtreeReader::new(0, root_offset, disk);
    1002              : 
    1003            1 :         reader.dump(&ctx).await?;
    1004              : 
    1005              :         use std::sync::Mutex;
    1006              : 
    1007            1 :         let result = Mutex::new(Vec::new());
    1008            1 :         let limit: AtomicUsize = AtomicUsize::new(10);
    1009        41910 :         let take_ten = |key: &[u8], value: u64| {
    1010        41910 :             let mut keybuf = [0u8; 8];
    1011        41910 :             keybuf.copy_from_slice(key);
    1012        41910 :             let key_int = u64::from_be_bytes(keybuf);
    1013              : 
    1014        41910 :             let mut result = result.lock().unwrap();
    1015        41910 :             result.push((key_int, value));
    1016              : 
    1017              :             // keep going until we have 10 matches
    1018        41910 :             result.len() < limit.load(Ordering::Relaxed)
    1019        41910 :         };
    1020              : 
    1021         2010 :         for search_key_int in 0..(NUM_KEYS * 2 + 10) {
    1022         2010 :             let search_key = u64::to_be_bytes(search_key_int);
    1023         2010 :             assert_eq!(
    1024         2010 :                 reader.get(&search_key, &ctx).await?,
    1025         2010 :                 all_data.get(&search_key_int).cloned()
    1026              :             );
    1027              : 
    1028              :             // Test a forward scan starting with this key
    1029         2010 :             result.lock().unwrap().clear();
    1030         2010 :             reader
    1031         2010 :                 .visit(&search_key, VisitDirection::Forwards, take_ten, &ctx)
    1032         2010 :                 .await?;
    1033         2010 :             let expected = all_data
    1034         2010 :                 .range(search_key_int..)
    1035         2010 :                 .take(10)
    1036        19910 :                 .map(|(&key, &val)| (key, val))
    1037         2010 :                 .collect::<Vec<(u64, u64)>>();
    1038         2010 :             assert_eq!(*result.lock().unwrap(), expected);
    1039              : 
    1040              :             // And a backwards scan
    1041         2010 :             result.lock().unwrap().clear();
    1042         2010 :             reader
    1043         2010 :                 .visit(&search_key, VisitDirection::Backwards, take_ten, &ctx)
    1044         2010 :                 .await?;
    1045         2010 :             let expected = all_data
    1046         2010 :                 .range(..=search_key_int)
    1047         2010 :                 .rev()
    1048         2010 :                 .take(10)
    1049        20000 :                 .map(|(&key, &val)| (key, val))
    1050         2010 :                 .collect::<Vec<(u64, u64)>>();
    1051         2010 :             assert_eq!(*result.lock().unwrap(), expected);
    1052              :         }
    1053              : 
    1054              :         // full scan
    1055            1 :         let search_key = u64::to_be_bytes(0);
    1056            1 :         limit.store(usize::MAX, Ordering::Relaxed);
    1057            1 :         result.lock().unwrap().clear();
    1058            1 :         reader
    1059            1 :             .visit(&search_key, VisitDirection::Forwards, take_ten, &ctx)
    1060            1 :             .await?;
    1061            1 :         let expected = all_data
    1062            1 :             .iter()
    1063         1000 :             .map(|(&key, &val)| (key, val))
    1064            1 :             .collect::<Vec<(u64, u64)>>();
    1065            1 :         assert_eq!(*result.lock().unwrap(), expected);
    1066              : 
    1067              :         // full scan
    1068            1 :         let search_key = u64::to_be_bytes(u64::MAX);
    1069            1 :         limit.store(usize::MAX, Ordering::Relaxed);
    1070            1 :         result.lock().unwrap().clear();
    1071            1 :         reader
    1072            1 :             .visit(&search_key, VisitDirection::Backwards, take_ten, &ctx)
    1073            1 :             .await?;
    1074            1 :         let expected = all_data
    1075            1 :             .iter()
    1076            1 :             .rev()
    1077         1000 :             .map(|(&key, &val)| (key, val))
    1078            1 :             .collect::<Vec<(u64, u64)>>();
    1079            1 :         assert_eq!(*result.lock().unwrap(), expected);
    1080              : 
    1081            2 :         Ok(())
    1082            1 :     }
    1083              : 
    1084              :     #[tokio::test]
    1085            1 :     async fn random_data() -> Result<()> {
    1086            1 :         let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
    1087              : 
    1088              :         // Generate random keys with exponential distribution, to
    1089              :         // exercise the prefix compression
    1090              :         const NUM_KEYS: usize = 100000;
    1091            1 :         let mut all_data: BTreeMap<u128, u64> = BTreeMap::new();
    1092       100001 :         for idx in 0..NUM_KEYS {
    1093       100000 :             let u: f64 = rand::thread_rng().gen_range(0.0..1.0);
    1094       100000 :             let t = -(f64::ln(u));
    1095       100000 :             let key_int = (t * 1000000.0) as u128;
    1096       100000 : 
    1097       100000 :             all_data.insert(key_int, idx as u64);
    1098       100000 :         }
    1099              : 
    1100              :         // Build a tree from it
    1101            1 :         let mut disk = TestDisk::new();
    1102            1 :         let mut writer = DiskBtreeBuilder::<_, 16>::new(&mut disk);
    1103              : 
    1104        97537 :         for (&key, &val) in all_data.iter() {
    1105        97537 :             writer.append(&u128::to_be_bytes(key), val)?;
    1106              :         }
    1107            1 :         let (root_offset, _writer) = writer.finish()?;
    1108              : 
    1109            1 :         let reader = DiskBtreeReader::new(0, root_offset, disk);
    1110              : 
    1111              :         // Test get() operation on all the keys
    1112        97537 :         for (&key, &val) in all_data.iter() {
    1113        97537 :             let search_key = u128::to_be_bytes(key);
    1114        97537 :             assert_eq!(reader.get(&search_key, &ctx).await?, Some(val));
    1115              :         }
    1116              : 
    1117              :         // Test get() operations on random keys, most of which will not exist
    1118       100001 :         for _ in 0..100000 {
    1119       100000 :             let key_int = rand::thread_rng().r#gen::<u128>();
    1120       100000 :             let search_key = u128::to_be_bytes(key_int);
    1121       100000 :             assert!(reader.get(&search_key, &ctx).await? == all_data.get(&key_int).cloned());
    1122              :         }
    1123              : 
    1124              :         // Test boundary cases
    1125            1 :         assert!(
    1126            1 :             reader.get(&u128::to_be_bytes(u128::MIN), &ctx).await?
    1127            1 :                 == all_data.get(&u128::MIN).cloned()
    1128              :         );
    1129            1 :         assert!(
    1130            1 :             reader.get(&u128::to_be_bytes(u128::MAX), &ctx).await?
    1131            1 :                 == all_data.get(&u128::MAX).cloned()
    1132              :         );
    1133              : 
    1134              :         // Test iterator and get_stream API
    1135            1 :         let mut iter = reader.iter(&[0; 16], &ctx);
    1136            1 :         let mut cnt = 0;
    1137        97538 :         while let Some(res) = iter.next().await {
    1138        97537 :             let (key, val) = res?;
    1139        97537 :             let key = u128::from_be_bytes(key.as_slice().try_into().unwrap());
    1140        97537 :             assert_eq!(val, *all_data.get(&key).unwrap());
    1141        97537 :             cnt += 1;
    1142              :         }
    1143            1 :         assert_eq!(cnt, all_data.len());
    1144              : 
    1145            2 :         Ok(())
    1146            1 :     }
    1147              : 
    1148              :     #[test]
    1149            1 :     fn unsorted_input() {
    1150            1 :         let mut disk = TestDisk::new();
    1151            1 :         let mut writer = DiskBtreeBuilder::<_, 2>::new(&mut disk);
    1152              : 
    1153            1 :         let _ = writer.append(b"ba", 1);
    1154            1 :         let _ = writer.append(b"bb", 2);
    1155            1 :         let err = writer.append(b"aa", 3).expect_err("should've failed");
    1156            1 :         match err {
    1157            1 :             DiskBtreeError::UnsortedInput { key, last_key } => {
    1158            1 :                 assert_eq!(key.as_ref(), b"aa".as_slice());
    1159            1 :                 assert_eq!(last_key.as_ref(), b"bb".as_slice());
    1160              :             }
    1161            0 :             _ => panic!("unexpected error variant, expected DiskBtreeError::UnsortedInput"),
    1162              :         }
    1163            1 :     }
    1164              : 
    1165              :     ///
    1166              :     /// This test contains a particular data set, see disk_btree_test_data.rs
    1167              :     ///
    1168              :     #[tokio::test]
    1169            1 :     async fn particular_data() -> Result<()> {
    1170              :         // Build a tree from it
    1171            1 :         let mut disk = TestDisk::new();
    1172            1 :         let mut writer = DiskBtreeBuilder::<_, 26>::new(&mut disk);
    1173            1 :         let ctx =
    1174            1 :             RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error).with_scope_unit_test();
    1175              : 
    1176         2001 :         for (key, val) in disk_btree_test_data::TEST_DATA {
    1177         2000 :             writer.append(&key, val)?;
    1178              :         }
    1179            1 :         let (root_offset, writer) = writer.finish()?;
    1180              : 
    1181            1 :         println!("SIZE: {} blocks", writer.blocks.len());
    1182              : 
    1183            1 :         let reader = DiskBtreeReader::new(0, root_offset, disk);
    1184              : 
    1185              :         // Test get() operation on all the keys
    1186         2001 :         for (key, val) in disk_btree_test_data::TEST_DATA {
    1187         2000 :             assert_eq!(reader.get(&key, &ctx).await?, Some(val));
    1188              :         }
    1189              : 
    1190              :         // Test full scan
    1191            1 :         let mut count = 0;
    1192            1 :         reader
    1193            1 :             .visit(
    1194            1 :                 &[0u8; 26],
    1195            1 :                 VisitDirection::Forwards,
    1196         2000 :                 |_key, _value| {
    1197         2000 :                     count += 1;
    1198         2000 :                     true
    1199         2000 :                 },
    1200            1 :                 &ctx,
    1201              :             )
    1202            1 :             .await?;
    1203            1 :         assert_eq!(count, disk_btree_test_data::TEST_DATA.len());
    1204              : 
    1205            1 :         reader.dump(&ctx).await?;
    1206              : 
    1207            2 :         Ok(())
    1208            1 :     }
    1209              : }
    1210              : 
    1211              : #[cfg(test)]
    1212              : #[path = "disk_btree_test_data.rs"]
    1213              : mod disk_btree_test_data;
        

Generated by: LCOV version 2.1-beta