linliu-code commented on code in PR #690:
URL: https://github.com/apache/hudi-rs/pull/690#discussion_r3851554015


##########
crates/core/src/file_group/base_file/hfile.rs:
##########
@@ -0,0 +1,368 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! HFile implementation of [`BaseFileReader`].
+//!
+//! Reads an HFile base file, the base-file format of Hudi's metadata table.
+
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, BinaryArray, RecordBatch, RecordBatchOptions, 
StringArray};
+use arrow_schema::{DataType, Field, Schema, SchemaRef};
+use futures::StreamExt;
+use futures::future::BoxFuture;
+use object_store::path::Path as ObjPath;
+
+use super::reader::{BaseFileReadOptions, BaseFileReader, BaseFileStream};
+use crate::hfile::HFileReader;
+use crate::statistics::{StatisticsContainer, StatsGranularity};
+use crate::storage::Storage;
+use crate::storage::error::{Result, StorageError};
+use crate::storage::file_metadata::FileMetadata;
+use crate::storage::util::join_url_segments;
+
+const DEFAULT_BATCH_SIZE: usize = 8192;
+
+/// An HFile read holds the whole file in memory, because the decoder is
+/// constructed from a byte buffer. That is bounded here rather than left to
+/// exhaust the heap: a key-seeking reader, which reads a block at a time, is a
+/// separate piece of work, and until it exists a base file above this size is
+/// refused instead of being loaded. Only the metadata table's `files` 
partition
+/// is read by full scan today, and its base files are orders of magnitude
+/// smaller than this bound.
+const MAX_BUFFERED_FILE_SIZE: u64 = 256 * 1024 * 1024;

Review Comment:
   No. Java has no equivalent bound, because it never holds the file: 
`HFileReaderImpl(SeekableDataInputStream, long fileSize)` seeks to `fileSize - 
trailerSize` for the trailer, then constructs one 
`HFileBlockReader(startOffset, endOffset)` per block, each allocating only that 
range. The only two limits on that side are a per-range check that `endOffset - 
startOffset` fits in an `int`, and `HFileBlockCache`, which bounds a Caffeine 
cache by entry count plus a TTL, so it bounds retained blocks rather than the 
file.
   
   So the 256 MiB constant had no principled basis. It is being removed along 
with the buffered read.



##########
crates/core/src/file_group/base_file/hfile.rs:
##########
@@ -0,0 +1,368 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! HFile implementation of [`BaseFileReader`].
+//!
+//! Reads an HFile base file, the base-file format of Hudi's metadata table.
+
+use std::sync::Arc;
+
+use arrow::array::{ArrayRef, BinaryArray, RecordBatch, RecordBatchOptions, 
StringArray};
+use arrow_schema::{DataType, Field, Schema, SchemaRef};
+use futures::StreamExt;
+use futures::future::BoxFuture;
+use object_store::path::Path as ObjPath;
+
+use super::reader::{BaseFileReadOptions, BaseFileReader, BaseFileStream};
+use crate::hfile::HFileReader;
+use crate::statistics::{StatisticsContainer, StatsGranularity};
+use crate::storage::Storage;
+use crate::storage::error::{Result, StorageError};
+use crate::storage::file_metadata::FileMetadata;
+use crate::storage::util::join_url_segments;
+
+const DEFAULT_BATCH_SIZE: usize = 8192;
+
+/// An HFile read holds the whole file in memory, because the decoder is
+/// constructed from a byte buffer. That is bounded here rather than left to
+/// exhaust the heap: a key-seeking reader, which reads a block at a time, is a
+/// separate piece of work, and until it exists a base file above this size is
+/// refused instead of being loaded. Only the metadata table's `files` 
partition
+/// is read by full scan today, and its base files are orders of magnitude
+/// smaller than this bound.
+const MAX_BUFFERED_FILE_SIZE: u64 = 256 * 1024 * 1024;
+
+/// The key and the raw record value, as an HFile stores them. The value stays
+/// serialized: decoding it needs the payload's own schema, which the base-file
+/// reader does not resolve.
+const KEY_COLUMN: &str = "key";
+const VALUE_COLUMN: &str = "value";
+
+/// Reads HFile base files.
+#[derive(Debug)]
+pub struct HFileBaseFileReader {
+    storage: Arc<Storage>,
+}
+
+impl HFileBaseFileReader {
+    pub fn new(storage: Arc<Storage>) -> Self {
+        Self { storage }
+    }
+
+    fn schema() -> SchemaRef {
+        Arc::new(Schema::new(vec![
+            Field::new(KEY_COLUMN, DataType::Utf8, false),
+            Field::new(VALUE_COLUMN, DataType::Binary, true),
+        ]))
+    }
+
+    /// The projected schema, or an error naming a column the format does not
+    /// have. An empty projection is the row-count-only request shape.
+    fn project(projection: Option<&[String]>) -> Result<SchemaRef> {
+        let full = Self::schema();
+        match projection {
+            None => Ok(full),
+            Some(names) => {
+                let mut fields = Vec::with_capacity(names.len());
+                for name in names {
+                    let field = full.field_with_name(name).map_err(|_| {
+                        StorageError::InvalidColumn(format!(
+                            "HFile base files have no column {name}"
+                        ))
+                    })?;
+                    fields.push(field.clone());
+                }
+                Ok(Arc::new(Schema::new(fields)))
+            }
+        }
+    }
+
+    async fn file_size(&self, relative_path: &str, known: Option<u64>) -> 
Result<u64> {
+        if let Some(size) = known {
+            return Ok(size);
+        }
+        let obj_url = join_url_segments(&self.storage.base_url, 
&[relative_path])?;
+        let obj_path = ObjPath::from_url_path(obj_url.path())?;
+        Ok(self.storage.object_store.head(&obj_path).await?.size)
+    }
+
+    async fn open_within_bound(
+        &self,
+        relative_path: &str,
+        known_size: Option<u64>,
+    ) -> Result<HFileReader> {
+        let size = self.file_size(relative_path, known_size).await?;
+        if size > MAX_BUFFERED_FILE_SIZE {

Review Comment:
   Yes, and that is the direction now. Working out the cost first changed the 
design twice, so briefly:
   
   The decoder reaches its buffer in only four places. Three read the 
load-on-open region (root index, meta index, file info), which one range 
covers; the fourth, `read_block_at(offset, size)`, reads the data region and is 
also what `load_multi_level_index` uses for leaf index blocks. `TRAILER_SIZE` 
is a fixed 4096 at the tail. So a ranged open is trailer, then load-on-open, 
then blocks, which is exactly the Java shape.
   
   One correction worth recording: per-block fetching is the wrong strategy for 
the read this change performs. Criterion here is a full scan, so every block is 
touched and per-block ranged trades one request for 2+N. The strategy is 
window-coalesced ranged reads instead, reusing `plan_content_windows` and the 
`hoodie.memory.dfs.buffer.max.size` budget that the log-file path already uses, 
fetched through `read_contents` so `get_ranges` coalesces.
   
   That machinery only exists on the async log-read stack, so this work rebases 
onto #689 rather than main. This PR will be replaced by one on that base.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to