This is an automated email from the ASF dual-hosted git repository.

yihua pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/hudi-rs.git


The following commit(s) were added to refs/heads/main by this push:
     new c09fda46 fix(core): keep every hfile data block that starts with the 
same key (#1103)
c09fda46 is described below

commit c09fda46a724c252888349db05d284a68031c72d
Author: Y Ethan Guo <[email protected]>
AuthorDate: Sat Dec 5 11:01:25 2026 -0800

    fix(core): keep every hfile data block that starts with the same key (#1103)
    
    * fix(core): keep every hfile data block that starts with the same key
    
    The data block index was a map keyed by first key, so when one key's cells
    spanned three or more blocks the later blocks overwrote each other and key,
    prefix and full-scan reads skipped them. Keep the index as a vector in
    (first key, offset) order and select by partition point.
    
    * test(core): drop the leaf-index spanning test that repeats the root-index 
cases
---
 crates/core/src/hfile/reader.rs | 269 +++++++++++++++++++++++++---------------
 1 file changed, 169 insertions(+), 100 deletions(-)

diff --git a/crates/core/src/hfile/reader.rs b/crates/core/src/hfile/reader.rs
index bb3e25a8..859fbeb4 100644
--- a/crates/core/src/hfile/reader.rs
+++ b/crates/core/src/hfile/reader.rs
@@ -167,8 +167,10 @@ pub struct HFileReader {
     trailer: HFileTrailer,
     /// Compression codec from trailer
     codec: CompressionCodec,
-    /// Data block index (first key -> entry)
-    data_block_index: BTreeMap<Key, BlockIndexEntry>,
+    /// Data block index in (first key, offset) order. Several blocks share a
+    /// first key when one key's cells span them, so it cannot be keyed by
+    /// first key alone.
+    data_block_index: Vec<BlockIndexEntry>,
     /// Meta block index (name -> entry)
     meta_block_index: BTreeMap<String, BlockIndexEntry>,
     /// File info map
@@ -214,7 +216,7 @@ impl HFileReader {
             source,
             trailer,
             codec,
-            data_block_index: BTreeMap::new(),
+            data_block_index: Vec::new(),
             meta_block_index: BTreeMap::new(),
             file_info: BTreeMap::new(),
             last_key: None,
@@ -513,14 +515,13 @@ impl HFileReader {
     /// costs one block read. `SeekResult::BeforeBlockFirstKey` is the sync 
path
     /// naming the same case.
     ///
-    /// One case needs the block *before* the selected one as well. Row keys 
are
-    /// not required to be unique, and when a key's copies straddle a block
-    /// boundary HBase's midpoint falls back to the right-hand cell, so the
-    /// separator equals the key itself. Selecting only the entry at or below 
the
-    /// key would then take the later block and drop the copies in the earlier
-    /// one. So when the probe lands exactly on a separator, the preceding 
block
-    /// is taken too — one extra block read on an exact hit, against silently
-    /// losing rows.
+    /// One case needs more than one block. Row keys are not required to be
+    /// unique, and when a key's copies straddle a block boundary HBase's 
midpoint
+    /// falls back to the right-hand cell, so the separator equals the key 
itself.
+    /// When the copies span several blocks, every block after the first starts
+    /// with that separator. So when the probe lands exactly on a separator, 
every
+    /// block starting with it is taken, plus the block before them: one extra
+    /// block read on an exact hit, against silently losing rows.
     pub fn blocks_for_keys(&self, keys: &[&str]) -> Vec<BlockIndexEntry> {
         let mut selected: BTreeMap<u64, BlockIndexEntry> = BTreeMap::new();
         for key in keys {
@@ -530,60 +531,55 @@ impl HFileReader {
             let Some(probe) = Key::from_content(key.as_bytes()) else {
                 return self.data_block_entries();
             };
-            // No entry at or below the key means every block starts above it, 
so
-            // no block can hold it. Selecting nothing is correct, not a miss.
-            let mut at_or_below = 
self.data_block_index.range(..=probe.clone()).rev();
-            if let Some((index_key, entry)) = at_or_below.next() {
+            for entry in self.blocks_holding(&probe) {
                 selected.insert(entry.offset, entry.clone());
-                // An exact hit on a separator means the key may also end the
-                // previous block; see the note above on non-unique row keys.
-                if index_key == &probe
-                    && let Some((_, previous)) = at_or_below.next()
-                {
-                    selected.insert(previous.offset, previous.clone());
-                }
             }
         }
         selected.into_values().collect()
     }
 
+    /// The consecutive blocks that can hold `key`: the last block starting 
below
+    /// it, which may end with it, plus every block starting exactly at it.
+    ///
+    /// Empty when every block starts above the key, since no block can hold 
it.
+    fn blocks_holding(&self, key: &Key) -> &[BlockIndexEntry] {
+        let index = &self.data_block_index;
+        let end = index.partition_point(|e| e.first_key <= *key);
+        if end == 0 {
+            return &[];
+        }
+        let start = index
+            .partition_point(|e| e.first_key < *key)
+            .saturating_sub(1);
+        &index[start..end]
+    }
+
     /// The data blocks that can contain keys beginning with `prefix`.
     ///
-    /// The block holding the prefix's lower bound, plus every block whose 
index
-    /// key sorts below the prefix's exclusive upper bound. Over-includes for 
the
-    /// same reason [`Self::blocks_for_keys`] does.
+    /// The last block starting below the prefix, which may hold its first 
keys,
+    /// plus every block whose index key sorts inside the prefix's span.
+    /// Over-includes for the same reason [`Self::blocks_for_keys`] does.
     pub fn blocks_for_prefix(&self, prefix: &str) -> Vec<BlockIndexEntry> {
         let Some(lower) = Key::from_content(prefix.as_bytes()) else {
             return self.data_block_entries();
         };
-        let mut selected: BTreeMap<u64, BlockIndexEntry> = BTreeMap::new();
-
-        // The block the prefix's first possible key falls in. Its index key 
sorts
-        // at or below the prefix, so `range(prefix..)` below would skip it.
-        if let Some((_, entry)) = 
self.data_block_index.range(..=lower.clone()).next_back() {
-            selected.insert(entry.offset, entry.clone());
-        }
-
-        match prefix_upper_bound(prefix.as_bytes()) {
-            // Every block that starts inside the prefix's span.
+        let index = &self.data_block_index;
+        let start = index
+            .partition_point(|e| e.first_key < lower)
+            .saturating_sub(1);
+        let end = match prefix_upper_bound(prefix.as_bytes()) {
             Some(upper) => {
                 // `upper` is never longer than the prefix, and an over-long
                 // prefix already returned above, so this cannot fail.
                 let upper = Key::from_content(&upper).unwrap_or_else(|| {
                     unreachable!("an upper bound is never longer than its 
prefix")
                 });
-                for (_, entry) in self.data_block_index.range(lower..upper) {
-                    selected.insert(entry.offset, entry.clone());
-                }
+                index.partition_point(|e| e.first_key < upper)
             }
             // The prefix is all 0xFF, so nothing sorts above it: take the 
tail.
-            None => {
-                for (_, entry) in self.data_block_index.range(lower..) {
-                    selected.insert(entry.offset, entry.clone());
-                }
-            }
-        }
-        selected.into_values().collect()
+            None => index.len(),
+        };
+        index.get(start..end).map(<[_]>::to_vec).unwrap_or_default()
     }
 
     /// What this reader has actually read from storage, or `None` for a 
resident
@@ -612,7 +608,7 @@ impl HFileReader {
     /// The data blocks in key order, each with the range it occupies, so a
     /// caller can decide how many to read at once.
     pub fn data_block_entries(&self) -> Vec<BlockIndexEntry> {
-        self.data_block_index.values().cloned().collect()
+        self.data_block_index.clone()
     }
 
     /// Decode the records of several data blocks, fetching their ranges in one
@@ -744,10 +740,7 @@ impl HFileReader {
     }
 
     /// Read root index block and return the index entries.
-    fn read_root_index_block(
-        &self,
-        start: usize,
-    ) -> Result<(BTreeMap<Key, BlockIndexEntry>, usize)> {
+    fn read_root_index_block(&self, start: usize) -> 
Result<(Vec<BlockIndexEntry>, usize)> {
         let block = HFileBlock::parse(self.source.metadata_at(start)?, 
self.codec)?;
         if block.block_type() != HFileBlockType::RootIndex {
             return Err(HFileError::UnexpectedBlockType {
@@ -763,29 +756,13 @@ impl HFileReader {
         )?;
         let next_offset = start + block.header.on_disk_size_with_header();
 
-        // Convert entries to BTreeMap
-        let mut index_map = BTreeMap::new();
-        for i in 0..entries.len() {
-            let entry = &entries[i];
-            let next_key = if i + 1 < entries.len() {
-                Some(entries[i + 1].first_key.clone())
-            } else {
-                None
-            };
-            index_map.insert(
-                entry.first_key.clone(),
-                BlockIndexEntry::new(entry.first_key.clone(), next_key, 
entry.offset, entry.size),
-            );
-        }
-
-        Ok((index_map, next_offset))
+        Ok((Self::index_from_leaf_entries(&entries), next_offset))
     }
 
     /// Load multi-level data block index (BFS traversal).
     fn load_multi_level_index(&mut self) -> Result<()> {
         let mut levels_remaining = self.trailer.num_data_index_levels - 1;
-        let mut current_entries: Vec<BlockIndexEntry> =
-            self.data_block_index.values().cloned().collect();
+        let mut current_entries: Vec<BlockIndexEntry> = 
self.data_block_index.clone();
 
         while levels_remaining > 0 {
             let mut next_level_entries = Vec::new();
@@ -806,18 +783,19 @@ impl HFileReader {
         Ok(())
     }
 
-    /// Key-ordered index over leaf entries, each carrying the next entry's
-    /// first key so a seek knows where a block's range ends.
-    fn index_from_leaf_entries(entries: &[BlockIndexEntry]) -> BTreeMap<Key, 
BlockIndexEntry> {
-        let mut index_map = BTreeMap::new();
-        for (i, entry) in entries.iter().enumerate() {
-            let next_key = entries.get(i + 1).map(|next| 
next.first_key.clone());
-            index_map.insert(
-                entry.first_key.clone(),
-                BlockIndexEntry::new(entry.first_key.clone(), next_key, 
entry.offset, entry.size),
-            );
-        }
-        index_map
+    /// Index over leaf entries in (first key, offset) order, each carrying the
+    /// next entry's first key so a seek knows where a block's range ends.
+    fn index_from_leaf_entries(entries: &[BlockIndexEntry]) -> 
Vec<BlockIndexEntry> {
+        let mut sorted: Vec<&BlockIndexEntry> = entries.iter().collect();
+        sorted.sort_by(|a, b| (&a.first_key, a.offset).cmp(&(&b.first_key, 
b.offset)));
+        sorted
+            .iter()
+            .enumerate()
+            .map(|(i, entry)| {
+                let next_key = sorted.get(i + 1).map(|next| 
next.first_key.clone());
+                BlockIndexEntry::new(entry.first_key.clone(), next_key, 
entry.offset, entry.size)
+            })
+            .collect()
     }
 
     /// The multi-level walk for a ranged source: one batched request per level
@@ -825,8 +803,7 @@ impl HFileReader {
     /// that sit close together.
     async fn load_multi_level_index_batched(&mut self) -> Result<()> {
         let mut levels_remaining = self.trailer.num_data_index_levels - 1;
-        let mut current_entries: Vec<BlockIndexEntry> =
-            self.data_block_index.values().cloned().collect();
+        let mut current_entries: Vec<BlockIndexEntry> = 
self.data_block_index.clone();
 
         let budget = match &self.source {
             Source::Ranged { window_budget, .. } => *window_budget,
@@ -1160,8 +1137,8 @@ impl HFileReader {
         }
 
         // Get first data block
-        let first_entry = match self.data_block_index.first_key_value() {
-            Some((_, entry)) => entry.clone(),
+        let first_entry = match self.data_block_index.first() {
+            Some(entry) => entry.clone(),
             None => {
                 self.cursor.eof = true;
                 self.cursor.seeked = true;
@@ -1211,9 +1188,7 @@ impl HFileReader {
                 }
 
                 // Check if before file's first key
-                if self.data_block_index.first_key_value().is_some()
-                    && self.is_at_first_key_of_block()
-                {
+                if !self.data_block_index.is_empty() && 
self.is_at_first_key_of_block() {
                     return Ok(SeekResult::BeforeFileFirstKey);
                 }
 
@@ -1258,12 +1233,8 @@ impl HFileReader {
         let lookup_bytes = lookup_key.as_bytes();
         let fake_key = Key::from_bytes(lookup_bytes.to_vec());
 
-        // Find the entry with greatest key <= lookup_key
-        let entry = self
-            .data_block_index
-            .range(..=fake_key)
-            .next_back()
-            .map(|(_, e)| e.clone());
+        // The first block that can hold the lookup key.
+        let entry = self.blocks_holding(&fake_key).first().cloned();
 
         if let Some(entry) = entry {
             self.current_block_entry = Some(entry.clone());
@@ -1416,13 +1387,10 @@ impl HFileReader {
 
     /// Get the next block index entry.
     fn get_next_block_entry(&self, current: &BlockIndexEntry) -> 
Option<BlockIndexEntry> {
-        self.data_block_index
-            .range((
-                std::ops::Bound::Excluded(&current.first_key),
-                std::ops::Bound::Unbounded,
-            ))
-            .next()
-            .map(|(_, e)| e.clone())
+        let next = self
+            .data_block_index
+            .partition_point(|e| (&e.first_key, e.offset) <= 
(&current.first_key, current.offset));
+        self.data_block_index.get(next).cloned()
     }
 
     /// Get the current key-value pair.
@@ -3652,6 +3620,107 @@ mod key_pushdown_tests {
         assert_eq!(prefix_upper_bound(&[0xFF, 0xFF]), None);
         assert_eq!(prefix_upper_bound(b""), None);
     }
+
+    type Cell = (String, String);
+
+    /// An HFile of two cells per data block: `key-a`, `copies` cells of 
`key-k`,
+    /// then `key-m`, valued `v00`, `v01`, ... in file order. Two copies 
straddle
+    /// two blocks, five span three and seven span four, so one, two or three
+    /// blocks have `key-k` as their index key.
+    fn spanning_key_hfile(copies: usize) -> (Vec<u8>, Vec<Cell>) {
+        let mut cells = vec![("key-a".to_string(), "v00".to_string())];
+        cells.extend((1..=copies).map(|i| ("key-k".to_string(), 
format!("v{i:02}"))));
+        cells.push(("key-m".to_string(), format!("v{:02}", copies + 1)));
+        // A cell is its key and value plus 21 bytes of framing, so this cuts a
+        // block after every second cell.
+        let mut builder = crate::hfile::HFileBuilder::new(2 * ("key-a".len() + 
"v00".len() + 21));
+        for (key, value) in &cells {
+            builder.append(key.as_bytes(), value.as_bytes()).unwrap();
+        }
+        let bytes = builder.finish(BTreeMap::new()).unwrap();
+        let blocks = HFileTrailer::read(&bytes).unwrap().data_index_count as 
usize;
+        assert_eq!(blocks, cells.len().div_ceil(2), "two cells per block");
+        (bytes, cells)
+    }
+
+    fn cells_of(records: &[HFileRecord]) -> Vec<Cell> {
+        records
+            .iter()
+            .map(|r| {
+                let value = String::from_utf8(r.value().to_vec()).unwrap();
+                (r.key_as_str().unwrap().to_string(), value)
+            })
+            .collect()
+    }
+
+    async fn read_cells(
+        reader: &HFileReader,
+        blocks: &[BlockIndexEntry],
+        prefix: &str,
+    ) -> Result<Vec<Cell>> {
+        let records = reader.read_records_batched(blocks).await?;
+        let mut cells = cells_of(&records);
+        cells.retain(|(key, _)| key.starts_with(prefix));
+        Ok(cells)
+    }
+
+    /// A key lookup, a prefix lookup and a full scan each return every cell 
of a
+    /// key spanning several blocks, in file order, so a reader keeping the 
last
+    /// copy keeps the right one. Seeks too, for a resident source.
+    async fn assert_spanning_key_read_whole(reader: &mut HFileReader, cells: 
&[Cell], case: &str) {
+        let spanning: Vec<Cell> = cells.iter().filter(|c| c.0 == 
"key-k").cloned().collect();
+        let by_key = read_cells(reader, &reader.blocks_for_keys(&["key-k"]), 
"key-k").await;
+        assert_eq!(by_key.unwrap(), spanning, "{case}: key lookup");
+        let by_prefix = read_cells(reader, &reader.blocks_for_prefix("key-k"), 
"key-k").await;
+        assert_eq!(by_prefix.unwrap(), spanning, "{case}: prefix lookup");
+        let scan = read_cells(reader, &reader.data_block_entries(), "").await;
+        assert_eq!(scan.unwrap(), cells, "{case}: full scan");
+
+        if reader.window_budget().is_none() {
+            let walked = cells_of(&reader.collect_records().unwrap());
+            assert_eq!(walked, cells, "{case}: iterator");
+            let sought = 
cells_of(&reader.collect_records_by_prefix("key-k").unwrap());
+            assert_eq!(sought, spanning, "{case}: prefix seek");
+        }
+
+        // Each block's next key is its neighbour's, shared first keys 
included.
+        let entries = reader.data_block_entries();
+        assert_eq!(entries.len(), cells.len().div_ceil(2), "{case}");
+        for pair in entries.windows(2) {
+            let next = pair[0].next_block_first_key.as_ref();
+            assert_eq!(next, Some(&pair[1].first_key), "{case}");
+        }
+        assert_eq!(entries.last().unwrap().next_block_first_key, None, 
"{case}");
+    }
+
+    fn ranged_storage(dir: &std::path::Path) -> std::sync::Arc<Storage> {
+        let url = 
url::Url::from_directory_path(std::fs::canonicalize(dir).unwrap()).unwrap();
+        Storage::new_with_base_url(url).unwrap()
+    }
+
+    #[tokio::test]
+    async fn a_key_spanning_several_blocks_reads_whole_resident() -> 
Result<()> {
+        for copies in [2, 5, 7] {
+            let (bytes, cells) = spanning_key_hfile(copies);
+            let mut reader = HFileReader::new(bytes)?;
+            assert_spanning_key_read_whole(&mut reader, &cells, 
&format!("{copies}")).await;
+        }
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn a_key_spanning_several_blocks_reads_whole_ranged() -> Result<()> {
+        let dir = tempfile::tempdir().unwrap();
+        let storage = ranged_storage(dir.path());
+        for copies in [2, 5, 7] {
+            let (bytes, cells) = spanning_key_hfile(copies);
+            let name = format!("spanning_{copies}.hfile");
+            std::fs::write(dir.path().join(&name), bytes).unwrap();
+            let mut reader = HFileReader::open_ranged(&storage, &name).await?;
+            assert_spanning_key_read_whole(&mut reader, &cells, 
&format!("{copies}")).await;
+        }
+        Ok(())
+    }
 }
 
 #[cfg(test)]

Reply via email to