You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hudi.apache.org by "xushiyan (via GitHub)" <gi...@apache.org> on 2026/01/04 04:06:58 UTC
[PR] feat: add streaming table and file group APIs [hudi-rs]
xushiyan opened a new pull request, #508:
URL: https://github.com/apache/hudi-rs/pull/508
## Description
<!--- Describe your changes in detail -->
<!--- If it fixes an open issue, please link to the issue here. -->
<!--- Please link any related issues and PRs as well. -->
## How are the changes test-covered
- [ ] N/A
- [ ] Automated tests (unit and/or integration tests)
- [ ] Manual tests
- [ ] Details are described below
--
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: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat: add streaming table and file group APIs [hudi-rs]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #508:
URL: https://github.com/apache/hudi-rs/pull/508#discussion_r2659455386
##########
crates/core/src/table/read_options.rs:
##########
@@ -0,0 +1,160 @@
+/*
+ * 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.
+ */
+//! Read options for streaming reads.
+
+use arrow_array::{BooleanArray, RecordBatch};
+
+/// A row-level predicate function for filtering records.
+pub type RowPredicate = Box<dyn Fn(&RecordBatch) -> crate::Result<BooleanArray> + Send + Sync>;
+
+/// A partition filter tuple: (field_name, operator, value).
+/// Example: ("city", "=", "san_francisco")
+pub type PartitionFilter = (String, String, String);
+
+/// Options for reading file slices with streaming APIs.
+///
+/// This struct provides configuration for:
+/// - Partition filters (filtering partitions)
+/// - Column projection (which columns to read)
+/// - Row-level predicates (filtering rows)
+/// - Batch size control (rows per batch)
+/// - Time travel (as-of timestamp)
+///
+/// # Current Limitations
+///
+/// Not all options are fully supported in streaming APIs:
+/// - `batch_size` and `partition_filters` are fully supported.
+/// - `projection` is passed through to the streaming implementation but is not yet
+/// applied at the parquet read level. This is because projection requires mapping
+/// column names to column indices via schema lookup, which is not yet implemented.
+/// - `row_predicate` is not yet implemented in streaming reads. The predicate function
+/// is accepted but will be ignored.
+///
+/// # Example
+///
+/// ```ignore
+/// use hudi::table::ReadOptions;
+///
+/// let options = ReadOptions::new()
+/// .with_filters([("city", "=", "san_francisco")])
+/// .with_batch_size(4096);
+/// ```
+#[derive(Default)]
+pub struct ReadOptions {
+ /// Partition filters. Each filter is a tuple of (field, operator, value).
+ pub partition_filters: Vec<PartitionFilter>,
+
+ /// Column names to project (select). If None, all columns are read.
+ pub projection: Option<Vec<String>>,
+
+ /// Row-level filter predicate. Applied after reading each batch.
+ pub row_predicate: Option<RowPredicate>,
+
+ /// Target number of rows per batch.
+ pub batch_size: Option<usize>,
+
+ /// Timestamp for time travel queries (as-of).
+ pub as_of_timestamp: Option<String>,
+}
Review Comment:
The `ReadOptions` struct fields are public, but in the documentation at lines 39-47, there's a discrepancy. The documentation states that "projection" and "row_predicate" are "not yet implemented," but the struct allows them to be set. This could lead to confusion. Consider either:
1. Making these fields private with getter methods to prevent misuse, or
2. Adding runtime validation that returns an error if these unimplemented options are used, or
3. More prominently documenting that these fields are accepted but silently ignored
The current approach of silently ignoring options is not ideal from an API design perspective, as users may set these options expecting them to work.
##########
crates/core/src/storage/mod.rs:
##########
@@ -47,6 +49,62 @@ pub mod file_metadata;
pub mod reader;
pub mod util;
+/// Options for reading Parquet files with streaming.
+#[derive(Clone, Debug, Default)]
+pub struct ParquetReadOptions {
+ /// Target batch size (number of rows per batch).
+ pub batch_size: Option<usize>,
+ /// Column projection (indices of columns to read).
+ pub projection: Option<Vec<usize>>,
+}
+
+impl ParquetReadOptions {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn with_batch_size(mut self, batch_size: usize) -> Self {
+ self.batch_size = Some(batch_size);
+ self
+ }
+
+ pub fn with_projection(mut self, projection: Vec<usize>) -> Self {
+ self.projection = Some(projection);
+ self
+ }
+}
+
+/// A stream of record batches from a Parquet file with its schema.
+pub struct ParquetFileStream {
+ schema: SchemaRef,
+ stream: BoxStream<'static, std::result::Result<RecordBatch, parquet::errors::ParquetError>>,
+}
Review Comment:
The `ParquetFileStream` struct owns a `BoxStream` which requires heap allocation for each file. For high-performance scenarios with many small files, this could add overhead. Consider documenting this trade-off, or potentially providing a non-boxed variant in the future if performance profiling shows this to be a bottleneck. This is not a blocking issue, but worth noting for future optimization.
##########
crates/core/src/file_group/reader.rs:
##########
@@ -325,6 +323,173 @@ impl FileGroupReader {
.block_on(self.read_file_slice_from_paths(base_file_path, log_file_paths))
}
+ // =========================================================================
+ // Streaming Read APIs
+ // =========================================================================
+
+ /// Reads a file slice as a stream of record batches.
+ ///
+ /// This is the streaming version of [FileGroupReader::read_file_slice].
+ /// It returns a stream that yields record batches as they are read.
+ ///
+ /// For COW tables or read-optimized mode (base file only), this returns a true
+ /// streaming iterator from the underlying parquet file, yielding batches as they
+ /// are read without loading all data into memory.
+ ///
+ /// For MOR tables with log files, this falls back to the collect-and-merge approach
+ /// and yields the merged result as a single batch. This limitation exists because
+ /// streaming merge of base files with log files is not yet implemented.
+ ///
+ /// # Limitations
+ ///
+ /// - The `projection` and `row_predicate` fields in [ReadOptions] are not yet
+ /// implemented for streaming reads. Only `batch_size` is currently supported.
+ ///
+ /// # Arguments
+ /// * `file_slice` - The file slice to read.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches. The stream owns all necessary data and is `'static`.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ ///
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ /// let mut stream = reader.read_file_slice_stream(&file_slice, &options).await?;
+ ///
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// // Process batch...
+ /// }
+ /// ```
+ pub async fn read_file_slice_stream(
+ &self,
+ file_slice: &FileSlice,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>> {
+ let base_file_path = file_slice.base_file_relative_path()?;
+ let log_file_paths: Vec<String> = if file_slice.has_log_file() {
+ file_slice
+ .log_files
+ .iter()
+ .map(|log_file| file_slice.log_file_relative_path(log_file))
+ .collect::<Result<Vec<String>>>()?
+ } else {
+ vec![]
+ };
+
+ self.read_file_slice_from_paths_stream(&base_file_path, log_file_paths, options)
+ .await
+ }
+
+ /// Reads a file slice from paths as a stream of record batches.
+ ///
+ /// This is the streaming version of [FileGroupReader::read_file_slice_from_paths].
+ ///
+ /// # Arguments
+ /// * `base_file_path` - Relative path to the base file.
+ /// * `log_file_paths` - Iterator of relative paths to log files.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches.
+ pub async fn read_file_slice_from_paths_stream<I, S>(
+ &self,
+ base_file_path: &str,
+ log_file_paths: I,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>>
+ where
+ I: IntoIterator<Item = S>,
+ S: AsRef<str>,
+ {
+ let use_read_optimized: bool = self
+ .hudi_configs
+ .get_or_default(HudiReadConfig::UseReadOptimizedMode)
+ .into();
+
+ if use_read_optimized {
+ return self.read_base_file_stream(base_file_path, options).await;
+ }
+
+ let log_file_paths: Vec<String> = log_file_paths
+ .into_iter()
+ .map(|s| s.as_ref().to_string())
+ .collect();
+
+ if log_file_paths.is_empty() {
+ self.read_base_file_stream(base_file_path, options).await
+ } else {
+ // Fallback: collect + merge, then yield as single-item stream
+ let batch = self
+ .read_file_slice_from_paths(base_file_path, log_file_paths)
+ .await?;
+ Ok(Box::pin(futures::stream::once(async { Ok(batch) })))
+ }
+ }
+
+ /// Reads a base file as a stream of record batches.
+ ///
+ /// # Limitations
+ ///
+ /// Currently only `batch_size` from [ReadOptions] is used. The `projection` and
+ /// `row_predicate` fields are not yet implemented.
+ async fn read_base_file_stream(
+ &self,
+ relative_path: &str,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>> {
+ use crate::config::table::BaseFileFormatValue;
+
+ // Validate base file format is parquet
+ let base_file_format: String = self
+ .hudi_configs
+ .get_or_default(HudiTableConfig::BaseFileFormat)
+ .into();
+ if !base_file_format.eq_ignore_ascii_case(BaseFileFormatValue::Parquet.as_ref()) {
+ return Err(ReadFileSliceError(format!(
+ "Streaming read only supports parquet format, got: {base_file_format}"
+ )));
+ }
+
+ let default_batch_size: usize = self
+ .hudi_configs
+ .get_or_default(HudiReadConfig::StreamBatchSize)
+ .into();
+ let batch_size = options.batch_size.unwrap_or(default_batch_size);
+ let parquet_options = ParquetReadOptions::new().with_batch_size(batch_size);
+
+ let hudi_configs = self.hudi_configs.clone();
+ let path = relative_path.to_string();
+
+ let parquet_stream = self
+ .storage
+ .get_parquet_file_stream(&path, parquet_options)
+ .map_err(|e| ReadFileSliceError(format!("Failed to read path {path}: {e:?}")))
+ .await?;
+
+ // Apply the same filtering logic as read_file_slice_by_base_file_path
+ let stream = parquet_stream.into_stream().filter_map(move |result| {
+ let hudi_configs = hudi_configs.clone();
+ async move {
+ match result {
+ Err(e) => Some(Err(ReadFileSliceError(format!(
+ "Failed to read batch: {e:?}"
+ )))),
+ Ok(batch) => match apply_commit_time_filter(&hudi_configs, batch) {
+ Err(e) => Some(Err(e)),
+ Ok(filtered) if filtered.num_rows() > 0 => Some(Ok(filtered)),
+ Ok(_) => None,
+ },
+ }
+ }
+ });
Review Comment:
The `filter_map` closure at line 474 clones `hudi_configs` (an `Arc`) for every batch processed. While `Arc::clone` is cheap (just incrementing a reference count), this pattern could be avoided by using `Arc` directly in the closure. However, the current implementation is correct and the overhead is minimal. Consider this a minor optimization opportunity rather than a required change.
##########
crates/core/tests/table_read_tests.rs:
##########
@@ -555,6 +555,229 @@ mod v8_tables {
}
}
+/// Test module for streaming read APIs.
+/// These tests verify the streaming versions of snapshot and file slice reads.
+mod streaming_queries {
+ use super::*;
+ use futures::StreamExt;
+ use hudi_core::table::ReadOptions;
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_empty_table() -> Result<()> {
+ for base_url in SampleTable::V6Empty.urls() {
+ let hudi_table = Table::new(base_url.path()).await?;
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+ assert!(batches.is_empty(), "Empty table should produce no batches");
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_basic() -> Result<()> {
+ for base_url in SampleTable::V6Nonpartitioned.urls() {
+ let hudi_table = Table::new(base_url.path()).await?;
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(!batches.is_empty(), "Should produce at least one batch");
+
+ // Concatenate batches and verify data
+ let schema = &batches[0].schema();
+ let records = concat_batches(schema, &batches)?;
+
+ let sample_data = SampleTable::sample_data_order_by_id(&records);
+ assert_eq!(
+ sample_data,
+ vec![
+ (1, "Alice", false),
+ (2, "Bob", false),
+ (3, "Carol", true),
+ (4, "Diana", true),
+ ]
+ );
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_with_batch_size() -> Result<()> {
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ // Request small batch size
+ let options = ReadOptions::new().with_batch_size(1);
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ // With batch_size=1 and 4 rows, we expect multiple batches, but the
+ // exact number depends on both the batch_size setting and the Parquet
+ // file's internal row group structure.
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(total_rows, 4, "Total rows should match expected count");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_with_partition_filters() -> Result<()> {
+ let base_url = SampleTable::V6ComplexkeygenHivestyle.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let options = ReadOptions::new().with_filters([
+ ("byteField", ">=", "10"),
+ ("byteField", "<", "20"),
+ ("shortField", "!=", "100"),
+ ]);
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(
+ !batches.is_empty(),
+ "Should produce at least one batch for the given partition filters"
+ );
+ let schema = &batches[0].schema();
+ let records = concat_batches(schema, &batches)?;
+
+ let sample_data = SampleTable::sample_data_order_by_id(&records);
+ assert_eq!(sample_data, vec![(1, "Alice", false), (3, "Carol", true),]);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_file_slice_stream_basic() -> Result<()> {
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ // Get file slices first
+ let file_slices = hudi_table.get_file_slices(empty_filters()).await?;
+ assert!(
+ !file_slices.is_empty(),
+ "Should have at least one file slice"
+ );
+
+ let options = ReadOptions::new();
+ let file_slice = &file_slices[0];
+ let mut stream = hudi_table
+ .read_file_slice_stream(file_slice, &options)
+ .await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(!batches.is_empty(), "Should produce at least one batch");
+
+ // Verify we got records
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert!(total_rows > 0, "Should read at least one row");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_file_slice_stream_with_batch_size() -> Result<()> {
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let file_slices = hudi_table.get_file_slices(empty_filters()).await?;
+ let file_slice = &file_slices[0];
+
+ // Test with small batch size
+ let options = ReadOptions::new().with_batch_size(1);
+ let mut stream = hudi_table
+ .read_file_slice_stream(file_slice, &options)
+ .await?;
+
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(total_rows, 4, "Should read all 4 rows");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_mor_with_log_files() -> Result<()> {
+ // Test MOR table with log files - should still work (falls back to collect+merge)
+ let base_url = QuickstartTripsTable::V6Trips8I1U.url_to_mor_avro();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(!batches.is_empty(), "Should produce batches from MOR table");
+
+ // Verify total row count
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(total_rows, 8, "Should have 8 rows (8 inserts)");
+ Ok(())
+ }
Review Comment:
The test `test_read_snapshot_stream_mor_with_log_files` (line 725) verifies that MOR tables with log files work by falling back to collect-and-merge. However, the comment on line 726 says "falls back to collect+merge" but the test doesn't actually verify this behavior - it only checks that the result is correct. Consider adding assertions to verify that only a single batch is returned (indicating the fallback occurred) or add a comment explaining that this fallback behavior is tested implicitly.
##########
crates/core/src/file_group/reader.rs:
##########
@@ -425,6 +590,60 @@ impl FileGroupReader {
}
}
+/// Apply commit time filtering to a record batch.
+///
+/// This function mirrors the filtering logic in `FileGroupReader::create_filtering_mask_for_base_file_records`
+/// but takes `HudiConfigs` directly so it can be used in streaming contexts where `&self` is not available.
+fn apply_commit_time_filter(hudi_configs: &HudiConfigs, batch: RecordBatch) -> Result<RecordBatch> {
+ let populates_meta_fields: bool = hudi_configs
+ .get_or_default(HudiTableConfig::PopulatesMetaFields)
+ .into();
+ if !populates_meta_fields {
+ return Ok(batch);
+ }
+
+ let start_ts = hudi_configs
+ .try_get(HudiReadConfig::FileGroupStartTimestamp)
+ .map(|v| -> String { v.into() });
+ if start_ts.is_none() {
+ // If start timestamp is not provided, the query is snapshot or time-travel
+ return Ok(batch);
+ }
+
+ let mut and_filters: Vec<SchemableFilter> = Vec::new();
+ let schema = MetaField::schema();
+
+ if let Some(start) = start_ts {
+ let filter = Filter::try_from((MetaField::CommitTime.as_ref(), ">", start.as_str()))?;
+ and_filters.push(SchemableFilter::try_from((filter, schema.as_ref()))?);
+ }
+
+ if let Some(end) = hudi_configs
+ .try_get(HudiReadConfig::FileGroupEndTimestamp)
+ .map(|v| -> String { v.into() })
+ {
+ let filter = Filter::try_from((MetaField::CommitTime.as_ref(), "<=", end.as_str()))?;
+ and_filters.push(SchemableFilter::try_from((filter, schema.as_ref()))?);
+ }
+
+ if and_filters.is_empty() {
+ return Ok(batch);
+ }
+
+ let mut mask = BooleanArray::from(vec![true; batch.num_rows()]);
+ for filter in &and_filters {
+ let col_name = filter.field.name().as_str();
+ let col_values = batch
+ .column_by_name(col_name)
+ .ok_or_else(|| ReadFileSliceError(format!("Column {col_name} not found")))?;
+ let comparison = filter.apply_comparison(col_values)?;
+ mask = and(&mask, &comparison)?;
+ }
+
Review Comment:
The `apply_commit_time_filter` function creates a new `BooleanArray` mask with all `true` values (line 633) even when no filtering is needed. This allocation could be avoided by checking if `and_filters` is empty before creating the mask. This is a minor optimization but could improve performance when processing many batches without commit time filters.
```suggestion
let mut mask: Option<BooleanArray> = None;
for filter in &and_filters {
let col_name = filter.field.name().as_str();
let col_values = batch
.column_by_name(col_name)
.ok_or_else(|| ReadFileSliceError(format!("Column {col_name} not found")))?;
let comparison = filter.apply_comparison(col_values)?;
mask = Some(match mask {
None => comparison,
Some(existing) => and(&existing, &comparison)?,
});
}
let mask = match mask {
Some(m) => m,
None => return Ok(batch),
};
```
--
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: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat: add streaming table and file group APIs [hudi-rs]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #508:
URL: https://github.com/apache/hudi-rs/pull/508#discussion_r2659409268
##########
crates/core/src/table/read_options.rs:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.
+ */
+//! Read options for streaming reads.
+
+use arrow_array::{BooleanArray, RecordBatch};
+
+/// A row-level predicate function for filtering records.
+pub type RowPredicate = Box<dyn Fn(&RecordBatch) -> crate::Result<BooleanArray> + Send + Sync>;
+
+/// A partition filter tuple: (field_name, operator, value).
+/// Example: ("city", "=", "san_francisco")
+pub type PartitionFilter = (String, String, String);
+
+/// Options for reading file slices with streaming APIs.
+///
+/// This struct provides configuration for:
+/// - Partition filters (filtering partitions)
+/// - Column projection (which columns to read)
+/// - Row-level predicates (filtering rows)
+/// - Batch size control (rows per batch)
+/// - Time travel (as-of timestamp)
+///
+/// # Current Limitations
+///
+/// Not all options are supported in all streaming APIs:
+/// - `batch_size` and `partition_filters` are fully supported.
+/// - `projection` is passed through but not yet applied at the parquet read level.
+/// - `row_predicate` is not yet implemented in streaming reads.
Review Comment:
The documentation states that `projection` is "passed through but not yet applied at the parquet read level", but looking at the implementation in `read_base_file_stream`, there's no code to apply the projection even when building the parquet reader. The `ParquetReadOptions` struct has a `projection` field that accepts column indices, but the `ReadOptions::projection` field is column names. This mismatch means projection cannot be easily passed through without a schema lookup to map column names to indices. Consider either implementing the projection functionality or removing the projection field from ReadOptions in this PR since it's not implemented.
##########
crates/core/tests/table_read_tests.rs:
##########
@@ -555,6 +555,228 @@ mod v8_tables {
}
}
+/// Test module for streaming read APIs.
+/// These tests verify the streaming versions of snapshot and file slice reads.
+mod streaming_queries {
+ use super::*;
+ use futures::StreamExt;
+ use hudi_core::table::ReadOptions;
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_empty_table() -> Result<()> {
+ for base_url in SampleTable::V6Empty.urls() {
+ let hudi_table = Table::new(base_url.path()).await?;
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+ assert!(batches.is_empty(), "Empty table should produce no batches");
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_basic() -> Result<()> {
+ for base_url in SampleTable::V6Nonpartitioned.urls() {
+ let hudi_table = Table::new(base_url.path()).await?;
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(!batches.is_empty(), "Should produce at least one batch");
+
+ // Concatenate batches and verify data
+ let schema = &batches[0].schema();
+ let records = concat_batches(schema, &batches)?;
+
+ let sample_data = SampleTable::sample_data_order_by_id(&records);
+ assert_eq!(
+ sample_data,
+ vec![
+ (1, "Alice", false),
+ (2, "Bob", false),
+ (3, "Carol", true),
+ (4, "Diana", true),
+ ]
+ );
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_with_batch_size() -> Result<()> {
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ // Request small batch size
+ let options = ReadOptions::new().with_batch_size(1);
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ // With batch_size=1 and 4 rows, we should get multiple batches
+ // (exact number depends on parquet row groups)
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(total_rows, 4, "Total rows should match expected count");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_with_partition_filters() -> Result<()> {
+ let base_url = SampleTable::V6ComplexkeygenHivestyle.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let options = ReadOptions::new().with_filters([
+ ("byteField", ">=", "10"),
+ ("byteField", "<", "20"),
+ ("shortField", "!=", "100"),
+ ]);
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
Review Comment:
This test accesses `batches[0]` without checking if the batches vector is empty. If the partition filters exclude all data, this will panic with an index out of bounds error. Add a check to ensure batches is not empty before accessing the first element, similar to the pattern used in `test_read_snapshot_stream_basic`.
```suggestion
assert!(
!batches.is_empty(),
"Should produce at least one batch for the given partition filters"
);
```
##########
crates/core/src/table/read_options.rs:
##########
@@ -0,0 +1,154 @@
+/*
+ * 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.
+ */
+//! Read options for streaming reads.
+
+use arrow_array::{BooleanArray, RecordBatch};
+
+/// A row-level predicate function for filtering records.
+pub type RowPredicate = Box<dyn Fn(&RecordBatch) -> crate::Result<BooleanArray> + Send + Sync>;
+
+/// A partition filter tuple: (field_name, operator, value).
+/// Example: ("city", "=", "san_francisco")
+pub type PartitionFilter = (String, String, String);
+
+/// Options for reading file slices with streaming APIs.
+///
+/// This struct provides configuration for:
+/// - Partition filters (filtering partitions)
+/// - Column projection (which columns to read)
+/// - Row-level predicates (filtering rows)
+/// - Batch size control (rows per batch)
+/// - Time travel (as-of timestamp)
+///
+/// # Current Limitations
+///
+/// Not all options are supported in all streaming APIs:
+/// - `batch_size` and `partition_filters` are fully supported.
+/// - `projection` is passed through but not yet applied at the parquet read level.
+/// - `row_predicate` is not yet implemented in streaming reads.
+///
+/// # Example
+///
+/// ```ignore
+/// use hudi::table::ReadOptions;
+///
+/// let options = ReadOptions::new()
+/// .with_filters([("city", "=", "san_francisco")])
+/// .with_batch_size(4096);
+/// ```
+#[derive(Default)]
+pub struct ReadOptions {
+ /// Partition filters. Each filter is a tuple of (field, operator, value).
+ pub partition_filters: Vec<PartitionFilter>,
+
+ /// Column names to project (select). If None, all columns are read.
+ pub projection: Option<Vec<String>>,
+
+ /// Row-level filter predicate. Applied after reading each batch.
+ pub row_predicate: Option<RowPredicate>,
Review Comment:
The documentation claims that `row_predicate` is "not yet implemented in streaming reads", but this field is actually included in the `ReadOptions` struct and has an accessor method. Users may try to use this field expecting it to work. Consider either implementing row_predicate support or documenting more clearly in the struct-level docs and the `with_row_predicate` method doc that this feature is not yet supported in streaming contexts, to prevent confusion.
##########
crates/core/tests/table_read_tests.rs:
##########
@@ -555,6 +555,228 @@ mod v8_tables {
}
}
+/// Test module for streaming read APIs.
+/// These tests verify the streaming versions of snapshot and file slice reads.
+mod streaming_queries {
+ use super::*;
+ use futures::StreamExt;
+ use hudi_core::table::ReadOptions;
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_empty_table() -> Result<()> {
+ for base_url in SampleTable::V6Empty.urls() {
+ let hudi_table = Table::new(base_url.path()).await?;
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+ assert!(batches.is_empty(), "Empty table should produce no batches");
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_basic() -> Result<()> {
+ for base_url in SampleTable::V6Nonpartitioned.urls() {
+ let hudi_table = Table::new(base_url.path()).await?;
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(!batches.is_empty(), "Should produce at least one batch");
+
+ // Concatenate batches and verify data
+ let schema = &batches[0].schema();
+ let records = concat_batches(schema, &batches)?;
+
+ let sample_data = SampleTable::sample_data_order_by_id(&records);
+ assert_eq!(
+ sample_data,
+ vec![
+ (1, "Alice", false),
+ (2, "Bob", false),
+ (3, "Carol", true),
+ (4, "Diana", true),
+ ]
+ );
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_with_batch_size() -> Result<()> {
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ // Request small batch size
+ let options = ReadOptions::new().with_batch_size(1);
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ // With batch_size=1 and 4 rows, we should get multiple batches
+ // (exact number depends on parquet row groups)
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(total_rows, 4, "Total rows should match expected count");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_with_partition_filters() -> Result<()> {
+ let base_url = SampleTable::V6ComplexkeygenHivestyle.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let options = ReadOptions::new().with_filters([
+ ("byteField", ">=", "10"),
+ ("byteField", "<", "20"),
+ ("shortField", "!=", "100"),
+ ]);
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ let schema = &batches[0].schema();
+ let records = concat_batches(schema, &batches)?;
+
+ let sample_data = SampleTable::sample_data_order_by_id(&records);
+ assert_eq!(sample_data, vec![(1, "Alice", false), (3, "Carol", true),]);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_file_slice_stream_basic() -> Result<()> {
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ // Get file slices first
+ let file_slices = hudi_table.get_file_slices(empty_filters()).await?;
+ assert!(
+ !file_slices.is_empty(),
+ "Should have at least one file slice"
+ );
+
+ let options = ReadOptions::new();
+ let file_slice = &file_slices[0];
+ let mut stream = hudi_table
+ .read_file_slice_stream(file_slice, &options)
+ .await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(!batches.is_empty(), "Should produce at least one batch");
+
+ // Verify we got records
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert!(total_rows > 0, "Should read at least one row");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_file_slice_stream_with_batch_size() -> Result<()> {
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let file_slices = hudi_table.get_file_slices(empty_filters()).await?;
+ let file_slice = &file_slices[0];
+
+ // Test with small batch size
+ let options = ReadOptions::new().with_batch_size(1);
+ let mut stream = hudi_table
+ .read_file_slice_stream(file_slice, &options)
+ .await?;
+
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(total_rows, 4, "Should read all 4 rows");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_mor_with_log_files() -> Result<()> {
+ // Test MOR table with log files - should still work (falls back to collect+merge)
+ let base_url = QuickstartTripsTable::V6Trips8I1U.url_to_mor_avro();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(!batches.is_empty(), "Should produce batches from MOR table");
+
+ // Verify total row count
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(total_rows, 8, "Should have 8 rows (8 inserts)");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_error_propagation() -> Result<()> {
+ // This test verifies that if we read from a valid table, no errors are propagated
+ // (We can't easily trigger file read errors in a unit test without mocking)
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // All reads should succeed without error
+ while let Some(result) = stream.next().await {
+ assert!(result.is_ok(), "Reading should not produce errors");
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_file_slice_stream_no_timestamp_error() -> Result<()> {
+ // For an empty table, read_file_slice_stream should error if called with
+ // a file slice that doesn't have a valid timestamp context
+ let base_url = SampleTable::V6Empty.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ // Create a dummy file slice - this should fail because there's no commit timestamp
+ // Note: We can't easily test this without creating an invalid file slice
+ // So we verify the empty table returns empty stream from read_snapshot_stream
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ let mut count = 0;
+ while (stream.next().await).is_some() {
+ count += 1;
+ }
+ assert_eq!(count, 0, "Empty table should produce no batches");
+ Ok(())
+ }
Review Comment:
The test name `test_read_file_slice_stream_no_timestamp_error` and its comment suggest it's testing error handling for file slices without valid timestamps. However, the test actually just verifies that an empty table produces no batches - it doesn't create or test an invalid file slice. Either rename the test to accurately reflect what it tests (e.g., `test_read_snapshot_stream_empty_table_produces_no_batches`) or implement the actual timestamp error test case as described in the comment.
##########
crates/core/tests/table_read_tests.rs:
##########
@@ -555,6 +555,228 @@ mod v8_tables {
}
}
+/// Test module for streaming read APIs.
+/// These tests verify the streaming versions of snapshot and file slice reads.
+mod streaming_queries {
+ use super::*;
+ use futures::StreamExt;
+ use hudi_core::table::ReadOptions;
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_empty_table() -> Result<()> {
+ for base_url in SampleTable::V6Empty.urls() {
+ let hudi_table = Table::new(base_url.path()).await?;
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+ assert!(batches.is_empty(), "Empty table should produce no batches");
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_basic() -> Result<()> {
+ for base_url in SampleTable::V6Nonpartitioned.urls() {
+ let hudi_table = Table::new(base_url.path()).await?;
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(!batches.is_empty(), "Should produce at least one batch");
+
+ // Concatenate batches and verify data
+ let schema = &batches[0].schema();
+ let records = concat_batches(schema, &batches)?;
+
+ let sample_data = SampleTable::sample_data_order_by_id(&records);
+ assert_eq!(
+ sample_data,
+ vec![
+ (1, "Alice", false),
+ (2, "Bob", false),
+ (3, "Carol", true),
+ (4, "Diana", true),
+ ]
+ );
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_with_batch_size() -> Result<()> {
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ // Request small batch size
+ let options = ReadOptions::new().with_batch_size(1);
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ // With batch_size=1 and 4 rows, we should get multiple batches
+ // (exact number depends on parquet row groups)
Review Comment:
The comment states "the exact number depends on parquet row groups", but this is misleading. The batch size setting controls how many rows are returned per batch during streaming reads, but Parquet's internal row group structure will still be respected. With batch_size=1, the actual batch sizes may vary depending on how the Parquet reader handles row groups - it typically won't split a row group across batches. Consider clarifying this comment to explain that the exact number of batches depends on both the batch_size setting and the Parquet file's internal row group structure.
```suggestion
// With batch_size=1 and 4 rows, we expect multiple batches, but the
// exact number and boundaries depend on both the batch_size setting
// and the Parquet file's internal row group structure.
```
--
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: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat: add streaming table and file group APIs [hudi-rs]
Posted by "xushiyan (via GitHub)" <gi...@apache.org>.
xushiyan merged PR #508:
URL: https://github.com/apache/hudi-rs/pull/508
--
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: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat: add streaming table and file group APIs [hudi-rs]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #508:
URL: https://github.com/apache/hudi-rs/pull/508#discussion_r2659311067
##########
crates/core/src/file_group/reader.rs:
##########
@@ -425,6 +604,54 @@ impl FileGroupReader {
}
}
+/// Helper function to create a commit time filter mask for a record batch.
+/// This is used by the streaming read APIs.
+fn create_commit_time_filter(
+ hudi_configs: &HudiConfigs,
+ records: &RecordBatch,
+) -> Result<Option<BooleanArray>> {
+ let mut and_filters: Vec<SchemableFilter> = Vec::new();
+ let schema = MetaField::schema();
+
+ if let Some(start) = hudi_configs
+ .try_get(HudiReadConfig::FileGroupStartTimestamp)
+ .map(|v| -> String { v.into() })
+ {
+ let filter: Filter =
+ Filter::try_from((MetaField::CommitTime.as_ref(), ">", start.as_str()))?;
+ let filter = SchemableFilter::try_from((filter, schema.as_ref()))?;
+ and_filters.push(filter);
+ } else {
+ // If start timestamp is not provided, no filtering needed
+ return Ok(None);
+ }
+
+ if let Some(end) = hudi_configs
+ .try_get(HudiReadConfig::FileGroupEndTimestamp)
+ .map(|v| -> String { v.into() })
+ {
+ let filter = Filter::try_from((MetaField::CommitTime.as_ref(), "<=", end.as_str()))?;
+ let filter = SchemableFilter::try_from((filter, schema.as_ref()))?;
+ and_filters.push(filter);
+ }
+
+ if and_filters.is_empty() {
+ return Ok(None);
+ }
+
+ let mut mask = BooleanArray::from(vec![true; records.num_rows()]);
+ for filter in &and_filters {
+ let col_name = filter.field.name().as_str();
+ let col_values = records
+ .column_by_name(col_name)
+ .ok_or_else(|| ReadFileSliceError(format!("Column {col_name} not found")))?;
+
+ let comparison = filter.apply_comparsion(col_values)?;
Review Comment:
Typo in method name: 'apply_comparsion' should be 'apply_comparison'. This typo exists in the existing codebase (line 165) and is propagated here.
##########
crates/core/src/file_group/reader.rs:
##########
@@ -325,6 +327,183 @@ impl FileGroupReader {
.block_on(self.read_file_slice_from_paths(base_file_path, log_file_paths))
}
+ // =========================================================================
+ // Streaming Read APIs
+ // =========================================================================
+
+ /// Reads a file slice as a stream of record batches.
+ ///
+ /// This is the streaming version of [FileGroupReader::read_file_slice].
+ /// It returns a stream that yields record batches as they are read.
+ ///
+ /// For COW tables or read-optimized mode (base file only), this returns a true
+ /// streaming iterator from the underlying parquet file, yielding batches as they
+ /// are read without loading all data into memory.
+ ///
+ /// For MOR tables with log files, this falls back to the collect-and-merge approach
+ /// and yields the merged result as a single batch.
+ ///
+ /// # Arguments
+ /// * `file_slice` - The file slice to read.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches. The stream owns all necessary data and is `'static`.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ ///
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ /// let mut stream = reader.read_file_slice_stream(&file_slice, &options).await?;
+ ///
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// // Process batch...
+ /// }
+ /// ```
+ pub async fn read_file_slice_stream(
+ &self,
+ file_slice: &FileSlice,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>> {
+ let base_file_path = file_slice.base_file_relative_path()?;
+ let log_file_paths: Vec<String> = if file_slice.has_log_file() {
+ file_slice
+ .log_files
+ .iter()
+ .map(|log_file| file_slice.log_file_relative_path(log_file))
+ .collect::<Result<Vec<String>>>()?
+ } else {
+ vec![]
+ };
+
+ self.read_file_slice_from_paths_stream(&base_file_path, log_file_paths, options)
+ .await
+ }
+
+ /// Reads a file slice from paths as a stream of record batches.
+ ///
+ /// This is the streaming version of [FileGroupReader::read_file_slice_from_paths].
+ ///
+ /// # Arguments
+ /// * `base_file_path` - Relative path to the base file.
+ /// * `log_file_paths` - Iterator of relative paths to log files.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches.
+ pub async fn read_file_slice_from_paths_stream<I, S>(
+ &self,
+ base_file_path: &str,
+ log_file_paths: I,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>>
+ where
+ I: IntoIterator<Item = S>,
+ S: AsRef<str>,
+ {
+ let log_file_paths: Vec<String> = log_file_paths
+ .into_iter()
+ .map(|s| s.as_ref().to_string())
+ .collect();
+
+ let use_read_optimized: bool = self
+ .hudi_configs
+ .get_or_default(HudiReadConfig::UseReadOptimizedMode)
+ .into();
+ let base_file_only = log_file_paths.is_empty() || use_read_optimized;
+
+ if base_file_only {
+ // True streaming: return a stream from the parquet file
+ self.read_base_file_stream(base_file_path, options).await
+ } else {
+ // Fallback: collect + merge, then yield as single-item stream
+ let batch = self
+ .read_file_slice_from_paths(base_file_path, log_file_paths)
+ .await?;
+ Ok(Box::pin(futures::stream::once(async { Ok(batch) })))
+ }
Review Comment:
For MOR tables with log files, the streaming implementation falls back to the non-streaming read_file_slice_from_paths method and returns the entire merged result as a single batch. This defeats the purpose of streaming for MOR tables and could cause high memory usage with large file slices. Consider documenting this limitation prominently in the function documentation, or implementing proper streaming merge support.
##########
crates/core/src/table/mod.rs:
##########
@@ -790,6 +793,148 @@ impl Table {
) -> Result<Vec<RecordBatch>> {
todo!("read_incremental_changes")
}
+
+ // =========================================================================
+ // Streaming Read APIs
+ // =========================================================================
+
+ /// Reads a file slice as a stream of record batches.
+ ///
+ /// This is the streaming version of reading a single file slice. It returns a stream
+ /// that yields record batches as they are read, without loading all data into memory.
+ ///
+ /// # Arguments
+ /// * `file_slice` - The file slice to read.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let file_slices = table.get_file_slices(empty_filters()).await?;
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ ///
+ /// for file_slice in &file_slices {
+ /// let mut stream = table.read_file_slice_stream(file_slice, &options).await?;
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// // Process batch...
+ /// }
+ /// }
+ /// ```
+ pub async fn read_file_slice_stream(
+ &self,
+ file_slice: &FileSlice,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>> {
+ let timestamp = options
+ .as_of_timestamp
+ .as_deref()
+ .or_else(|| self.timeline.get_latest_commit_timestamp_as_option());
+
+ let timestamp = match timestamp {
+ Some(ts) => ts.to_string(),
+ None => return Err(crate::error::CoreError::Timeline("No commit timestamp available".to_string())),
+ };
+
+ let fg_reader = self.create_file_group_reader_with_options([(
+ HudiReadConfig::FileGroupEndTimestamp,
+ timestamp.as_str(),
+ )])?;
+
+ fg_reader.read_file_slice_stream(file_slice, options).await
+ }
+
+ /// Reads the table snapshot as a stream of record batches.
+ ///
+ /// This is the streaming version of [Table::read_snapshot]. Instead of returning
+ /// all batches at once, it returns a stream that yields record batches as they
+ /// are read from the underlying file slices.
+ ///
+ /// # Arguments
+ /// * `filters` - Partition filters to apply.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches from all file slices.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ /// let mut stream = table.read_snapshot_stream(empty_filters(), &options).await?;
+ ///
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// println!("Read {} rows", batch.num_rows());
+ /// }
+ /// ```
+ pub async fn read_snapshot_stream<I, S>(
+ &self,
+ filters: I,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>>
+ where
+ I: IntoIterator<Item = (S, S, S)>,
+ S: AsRef<str>,
+ {
+ use futures::stream::{self, StreamExt};
+
+ let Some(timestamp) = self.timeline.get_latest_commit_timestamp_as_option() else {
+ // Return empty stream if no commits
+ return Ok(Box::pin(stream::empty()));
+ };
Review Comment:
Inconsistent error handling compared to read_file_slice_stream. The read_file_slice_stream function (line 841) returns an error when no commit timestamp is available, but read_snapshot_stream (line 889-891) returns an empty stream. This inconsistency could confuse API users about expected behavior. Consider aligning these behaviors for consistency.
```suggestion
let timestamp = self
.timeline
.get_latest_commit_timestamp_as_option()
.ok_or_else(|| "No commit timestamp available for snapshot read".into())?;
```
##########
crates/core/src/table/mod.rs:
##########
@@ -790,6 +793,148 @@ impl Table {
) -> Result<Vec<RecordBatch>> {
todo!("read_incremental_changes")
}
+
+ // =========================================================================
+ // Streaming Read APIs
+ // =========================================================================
+
+ /// Reads a file slice as a stream of record batches.
+ ///
+ /// This is the streaming version of reading a single file slice. It returns a stream
+ /// that yields record batches as they are read, without loading all data into memory.
+ ///
+ /// # Arguments
+ /// * `file_slice` - The file slice to read.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let file_slices = table.get_file_slices(empty_filters()).await?;
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ ///
+ /// for file_slice in &file_slices {
+ /// let mut stream = table.read_file_slice_stream(file_slice, &options).await?;
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// // Process batch...
+ /// }
+ /// }
+ /// ```
+ pub async fn read_file_slice_stream(
+ &self,
+ file_slice: &FileSlice,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>> {
+ let timestamp = options
+ .as_of_timestamp
+ .as_deref()
+ .or_else(|| self.timeline.get_latest_commit_timestamp_as_option());
+
+ let timestamp = match timestamp {
+ Some(ts) => ts.to_string(),
+ None => return Err(crate::error::CoreError::Timeline("No commit timestamp available".to_string())),
+ };
+
+ let fg_reader = self.create_file_group_reader_with_options([(
+ HudiReadConfig::FileGroupEndTimestamp,
+ timestamp.as_str(),
+ )])?;
+
+ fg_reader.read_file_slice_stream(file_slice, options).await
+ }
+
+ /// Reads the table snapshot as a stream of record batches.
+ ///
+ /// This is the streaming version of [Table::read_snapshot]. Instead of returning
+ /// all batches at once, it returns a stream that yields record batches as they
+ /// are read from the underlying file slices.
+ ///
+ /// # Arguments
+ /// * `filters` - Partition filters to apply.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches from all file slices.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ /// let mut stream = table.read_snapshot_stream(empty_filters(), &options).await?;
+ ///
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// println!("Read {} rows", batch.num_rows());
+ /// }
+ /// ```
+ pub async fn read_snapshot_stream<I, S>(
+ &self,
+ filters: I,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>>
+ where
+ I: IntoIterator<Item = (S, S, S)>,
+ S: AsRef<str>,
+ {
+ use futures::stream::{self, StreamExt};
+
+ let Some(timestamp) = self.timeline.get_latest_commit_timestamp_as_option() else {
+ // Return empty stream if no commits
+ return Ok(Box::pin(stream::empty()));
+ };
+
+ let filters = from_str_tuples(filters)?;
+ let file_slices = self.get_file_slices_internal(timestamp, &filters).await?;
+
+ if file_slices.is_empty() {
+ return Ok(Box::pin(stream::empty()));
+ }
+
+ let fg_reader = self.create_file_group_reader_with_options([(
+ HudiReadConfig::FileGroupEndTimestamp,
+ timestamp,
+ )])?;
+
+ // Create a stream that iterates through file slices and yields batches
+ let batch_size = options.batch_size;
+ let streams_iter = file_slices.into_iter().map(move |file_slice| {
+ let fg_reader = fg_reader.clone();
+ let options = ReadOptions {
+ projection: None,
+ row_predicate: None,
+ batch_size,
+ as_of_timestamp: None,
+ };
Review Comment:
The projection and row_predicate options from the input ReadOptions are being ignored. Only batch_size is extracted and used, while projection and row_predicate are explicitly set to None when creating a new ReadOptions for each file slice. This means users cannot apply column projections or row-level filters when using read_snapshot_stream, which breaks the API contract suggested by the ReadOptions parameter.
```suggestion
// Clone the caller-provided ReadOptions so that projection,
// row_predicate, as_of_timestamp, and batch_size are all preserved.
let mut options = options.clone();
options.batch_size = batch_size;
```
##########
crates/core/src/file_group/reader.rs:
##########
@@ -325,6 +327,183 @@ impl FileGroupReader {
.block_on(self.read_file_slice_from_paths(base_file_path, log_file_paths))
}
+ // =========================================================================
+ // Streaming Read APIs
+ // =========================================================================
+
+ /// Reads a file slice as a stream of record batches.
+ ///
+ /// This is the streaming version of [FileGroupReader::read_file_slice].
+ /// It returns a stream that yields record batches as they are read.
+ ///
+ /// For COW tables or read-optimized mode (base file only), this returns a true
+ /// streaming iterator from the underlying parquet file, yielding batches as they
+ /// are read without loading all data into memory.
+ ///
+ /// For MOR tables with log files, this falls back to the collect-and-merge approach
+ /// and yields the merged result as a single batch.
+ ///
+ /// # Arguments
+ /// * `file_slice` - The file slice to read.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches. The stream owns all necessary data and is `'static`.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ ///
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ /// let mut stream = reader.read_file_slice_stream(&file_slice, &options).await?;
+ ///
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// // Process batch...
+ /// }
+ /// ```
+ pub async fn read_file_slice_stream(
+ &self,
+ file_slice: &FileSlice,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>> {
+ let base_file_path = file_slice.base_file_relative_path()?;
+ let log_file_paths: Vec<String> = if file_slice.has_log_file() {
+ file_slice
+ .log_files
+ .iter()
+ .map(|log_file| file_slice.log_file_relative_path(log_file))
+ .collect::<Result<Vec<String>>>()?
+ } else {
+ vec![]
+ };
+
+ self.read_file_slice_from_paths_stream(&base_file_path, log_file_paths, options)
+ .await
+ }
+
+ /// Reads a file slice from paths as a stream of record batches.
+ ///
+ /// This is the streaming version of [FileGroupReader::read_file_slice_from_paths].
+ ///
+ /// # Arguments
+ /// * `base_file_path` - Relative path to the base file.
+ /// * `log_file_paths` - Iterator of relative paths to log files.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches.
+ pub async fn read_file_slice_from_paths_stream<I, S>(
+ &self,
+ base_file_path: &str,
+ log_file_paths: I,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>>
+ where
+ I: IntoIterator<Item = S>,
+ S: AsRef<str>,
+ {
+ let log_file_paths: Vec<String> = log_file_paths
+ .into_iter()
+ .map(|s| s.as_ref().to_string())
+ .collect();
+
+ let use_read_optimized: bool = self
+ .hudi_configs
+ .get_or_default(HudiReadConfig::UseReadOptimizedMode)
+ .into();
+ let base_file_only = log_file_paths.is_empty() || use_read_optimized;
+
+ if base_file_only {
+ // True streaming: return a stream from the parquet file
+ self.read_base_file_stream(base_file_path, options).await
+ } else {
+ // Fallback: collect + merge, then yield as single-item stream
+ let batch = self
+ .read_file_slice_from_paths(base_file_path, log_file_paths)
+ .await?;
+ Ok(Box::pin(futures::stream::once(async { Ok(batch) })))
+ }
+ }
+
+ /// Reads a base file as a stream of record batches.
+ ///
+ /// This method streams record batches directly from the parquet file without
+ /// loading all data into memory at once.
+ async fn read_base_file_stream(
+ &self,
+ relative_path: &str,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>> {
+ // Get default batch size from config
+ let default_batch_size: usize = self
+ .hudi_configs
+ .get_or_default(HudiReadConfig::StreamBatchSize)
+ .into();
+
+ let batch_size = options.batch_size.unwrap_or(default_batch_size);
+
+ let parquet_options = ParquetReadOptions::new().with_batch_size(batch_size);
+
+ let hudi_configs = self.hudi_configs.clone();
+ let path = relative_path.to_string();
+
+ // Get the parquet stream
+ let parquet_stream = self
+ .storage
+ .get_parquet_file_stream(&path, parquet_options)
+ .map_err(|e| ReadFileSliceError(format!("Failed to read path {path}: {e:?}")))
+ .await?;
+
+ let populates_meta_fields: bool = hudi_configs
+ .get_or_default(HudiTableConfig::PopulatesMetaFields)
+ .into();
+
+ // Create a stream that applies commit time filtering
+ let stream = parquet_stream
+ .into_stream()
+ .filter_map(move |result| {
+ let hudi_configs = hudi_configs.clone();
+ async move {
+ match result {
+ Err(e) => Some(Err(ReadFileSliceError(format!(
+ "Failed to read batch: {e:?}"
+ )))),
+ Ok(batch) => {
+ // Apply commit time filtering if meta fields are populated
+ let filtered = if populates_meta_fields {
+ match create_commit_time_filter(&hudi_configs, &batch) {
+ Err(e) => return Some(Err(e)),
+ Ok(Some(mask)) => {
+ match filter_record_batch(&batch, &mask) {
+ Ok(b) => b,
+ Err(e) => {
+ return Some(Err(ReadFileSliceError(format!(
+ "Failed to filter records: {e:?}"
+ ))))
+ }
+ }
+ }
+ Ok(None) => batch,
+ }
+ } else {
+ batch
+ };
+
+ // Only yield non-empty batches
+ if filtered.num_rows() > 0 {
+ Some(Ok(filtered))
+ } else {
+ None
+ }
+ }
+ }
+ }
+ });
+
+ Ok(Box::pin(stream))
+ }
Review Comment:
The projection and row_predicate fields in ReadOptions are defined but never actually used in the streaming implementation. The read_base_file_stream function only applies commit time filtering but doesn't handle column projection (which would need to be passed to ParquetReadOptions.projection as column indices) or row-level predicates (which would need to be applied after commit time filtering). This makes these ReadOptions fields non-functional in the streaming API.
##########
crates/core/src/table/mod.rs:
##########
@@ -790,6 +793,148 @@ impl Table {
) -> Result<Vec<RecordBatch>> {
todo!("read_incremental_changes")
}
+
+ // =========================================================================
+ // Streaming Read APIs
+ // =========================================================================
+
+ /// Reads a file slice as a stream of record batches.
+ ///
+ /// This is the streaming version of reading a single file slice. It returns a stream
+ /// that yields record batches as they are read, without loading all data into memory.
+ ///
+ /// # Arguments
+ /// * `file_slice` - The file slice to read.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let file_slices = table.get_file_slices(empty_filters()).await?;
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ ///
+ /// for file_slice in &file_slices {
+ /// let mut stream = table.read_file_slice_stream(file_slice, &options).await?;
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// // Process batch...
+ /// }
+ /// }
+ /// ```
+ pub async fn read_file_slice_stream(
+ &self,
+ file_slice: &FileSlice,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>> {
+ let timestamp = options
+ .as_of_timestamp
+ .as_deref()
+ .or_else(|| self.timeline.get_latest_commit_timestamp_as_option());
+
+ let timestamp = match timestamp {
+ Some(ts) => ts.to_string(),
+ None => return Err(crate::error::CoreError::Timeline("No commit timestamp available".to_string())),
+ };
+
+ let fg_reader = self.create_file_group_reader_with_options([(
+ HudiReadConfig::FileGroupEndTimestamp,
+ timestamp.as_str(),
+ )])?;
+
+ fg_reader.read_file_slice_stream(file_slice, options).await
+ }
+
+ /// Reads the table snapshot as a stream of record batches.
+ ///
+ /// This is the streaming version of [Table::read_snapshot]. Instead of returning
+ /// all batches at once, it returns a stream that yields record batches as they
+ /// are read from the underlying file slices.
+ ///
+ /// # Arguments
+ /// * `filters` - Partition filters to apply.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches from all file slices.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ /// let mut stream = table.read_snapshot_stream(empty_filters(), &options).await?;
+ ///
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// println!("Read {} rows", batch.num_rows());
+ /// }
+ /// ```
+ pub async fn read_snapshot_stream<I, S>(
+ &self,
+ filters: I,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>>
+ where
+ I: IntoIterator<Item = (S, S, S)>,
+ S: AsRef<str>,
+ {
+ use futures::stream::{self, StreamExt};
+
+ let Some(timestamp) = self.timeline.get_latest_commit_timestamp_as_option() else {
+ // Return empty stream if no commits
+ return Ok(Box::pin(stream::empty()));
+ };
+
+ let filters = from_str_tuples(filters)?;
+ let file_slices = self.get_file_slices_internal(timestamp, &filters).await?;
+
+ if file_slices.is_empty() {
+ return Ok(Box::pin(stream::empty()));
+ }
+
+ let fg_reader = self.create_file_group_reader_with_options([(
+ HudiReadConfig::FileGroupEndTimestamp,
+ timestamp,
+ )])?;
+
+ // Create a stream that iterates through file slices and yields batches
+ let batch_size = options.batch_size;
+ let streams_iter = file_slices.into_iter().map(move |file_slice| {
+ let fg_reader = fg_reader.clone();
+ let options = ReadOptions {
+ projection: None,
+ row_predicate: None,
+ batch_size,
+ as_of_timestamp: None,
+ };
+ async move {
+ fg_reader.read_file_slice_stream(&file_slice, &options).await
+ }
+ });
+
+ // Chain all the streams together
+ let combined_stream = stream::iter(streams_iter)
+ .then(|fut| fut)
+ .filter_map(|result| async move {
+ match result {
+ Ok(stream) => Some(stream),
+ Err(e) => {
+ // Log error and skip this file slice
+ log::warn!("Failed to read file slice: {:?}", e);
+ None
Review Comment:
Errors from individual file slices are silently dropped with only a warning logged. This could lead to incomplete or missing data without the caller being aware. Consider either propagating the error to the stream (allowing the consumer to decide how to handle it) or accumulating errors and returning them at the end. If silent skipping is intentional for fault tolerance, this behavior should be documented in the function's documentation.
```suggestion
.map(|result| {
match result {
Ok(stream) => stream,
Err(e) => {
// Log error and propagate it as an item in the output stream
log::warn!("Failed to read file slice: {:?}", e);
Box::pin(stream::once(async move { Err(e) })) as _
```
##########
crates/core/src/table/mod.rs:
##########
@@ -790,6 +793,148 @@ impl Table {
) -> Result<Vec<RecordBatch>> {
todo!("read_incremental_changes")
}
+
+ // =========================================================================
+ // Streaming Read APIs
+ // =========================================================================
+
+ /// Reads a file slice as a stream of record batches.
+ ///
+ /// This is the streaming version of reading a single file slice. It returns a stream
+ /// that yields record batches as they are read, without loading all data into memory.
+ ///
+ /// # Arguments
+ /// * `file_slice` - The file slice to read.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let file_slices = table.get_file_slices(empty_filters()).await?;
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ ///
+ /// for file_slice in &file_slices {
+ /// let mut stream = table.read_file_slice_stream(file_slice, &options).await?;
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// // Process batch...
+ /// }
+ /// }
+ /// ```
+ pub async fn read_file_slice_stream(
+ &self,
+ file_slice: &FileSlice,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>> {
+ let timestamp = options
+ .as_of_timestamp
+ .as_deref()
+ .or_else(|| self.timeline.get_latest_commit_timestamp_as_option());
+
+ let timestamp = match timestamp {
+ Some(ts) => ts.to_string(),
+ None => return Err(crate::error::CoreError::Timeline("No commit timestamp available".to_string())),
+ };
+
+ let fg_reader = self.create_file_group_reader_with_options([(
+ HudiReadConfig::FileGroupEndTimestamp,
+ timestamp.as_str(),
+ )])?;
+
+ fg_reader.read_file_slice_stream(file_slice, options).await
+ }
+
+ /// Reads the table snapshot as a stream of record batches.
+ ///
+ /// This is the streaming version of [Table::read_snapshot]. Instead of returning
+ /// all batches at once, it returns a stream that yields record batches as they
+ /// are read from the underlying file slices.
+ ///
+ /// # Arguments
+ /// * `filters` - Partition filters to apply.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches from all file slices.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ /// let mut stream = table.read_snapshot_stream(empty_filters(), &options).await?;
+ ///
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// println!("Read {} rows", batch.num_rows());
+ /// }
+ /// ```
+ pub async fn read_snapshot_stream<I, S>(
+ &self,
+ filters: I,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>>
+ where
+ I: IntoIterator<Item = (S, S, S)>,
+ S: AsRef<str>,
+ {
+ use futures::stream::{self, StreamExt};
+
+ let Some(timestamp) = self.timeline.get_latest_commit_timestamp_as_option() else {
+ // Return empty stream if no commits
+ return Ok(Box::pin(stream::empty()));
+ };
+
+ let filters = from_str_tuples(filters)?;
+ let file_slices = self.get_file_slices_internal(timestamp, &filters).await?;
+
+ if file_slices.is_empty() {
+ return Ok(Box::pin(stream::empty()));
+ }
+
+ let fg_reader = self.create_file_group_reader_with_options([(
+ HudiReadConfig::FileGroupEndTimestamp,
+ timestamp,
+ )])?;
+
+ // Create a stream that iterates through file slices and yields batches
+ let batch_size = options.batch_size;
+ let streams_iter = file_slices.into_iter().map(move |file_slice| {
+ let fg_reader = fg_reader.clone();
+ let options = ReadOptions {
+ projection: None,
+ row_predicate: None,
+ batch_size,
+ as_of_timestamp: None,
+ };
+ async move {
+ fg_reader.read_file_slice_stream(&file_slice, &options).await
+ }
+ });
+
+ // Chain all the streams together
+ let combined_stream = stream::iter(streams_iter)
+ .then(|fut| fut)
+ .filter_map(|result| async move {
+ match result {
+ Ok(stream) => Some(stream),
+ Err(e) => {
+ // Log error and skip this file slice
+ log::warn!("Failed to read file slice: {:?}", e);
+ None
+ }
+ }
+ })
+ .flatten();
+
+ Ok(Box::pin(combined_stream))
+ }
Review Comment:
The new streaming APIs (read_file_slice_stream and read_snapshot_stream) lack test coverage. The codebase has comprehensive test coverage for similar non-streaming read functions in crates/core/tests/table_read_tests.rs. Consider adding tests for the streaming APIs that verify basic functionality, error handling, and edge cases like empty results and missing timestamps.
--
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: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat: add streaming table and file group APIs [hudi-rs]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #508:
URL: https://github.com/apache/hudi-rs/pull/508#discussion_r2659332081
##########
crates/core/src/file_group/reader.rs:
##########
@@ -325,6 +323,166 @@ impl FileGroupReader {
.block_on(self.read_file_slice_from_paths(base_file_path, log_file_paths))
}
+ // =========================================================================
+ // Streaming Read APIs
+ // =========================================================================
+
+ /// Reads a file slice as a stream of record batches.
+ ///
+ /// This is the streaming version of [FileGroupReader::read_file_slice].
+ /// It returns a stream that yields record batches as they are read.
+ ///
+ /// For COW tables or read-optimized mode (base file only), this returns a true
+ /// streaming iterator from the underlying parquet file, yielding batches as they
+ /// are read without loading all data into memory.
+ ///
+ /// For MOR tables with log files, this falls back to the collect-and-merge approach
+ /// and yields the merged result as a single batch.
+ ///
+ /// # Arguments
+ /// * `file_slice` - The file slice to read.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches. The stream owns all necessary data and is `'static`.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ ///
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ /// let mut stream = reader.read_file_slice_stream(&file_slice, &options).await?;
+ ///
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// // Process batch...
+ /// }
+ /// ```
+ pub async fn read_file_slice_stream(
+ &self,
+ file_slice: &FileSlice,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>> {
+ let base_file_path = file_slice.base_file_relative_path()?;
+ let log_file_paths: Vec<String> = if file_slice.has_log_file() {
+ file_slice
+ .log_files
+ .iter()
+ .map(|log_file| file_slice.log_file_relative_path(log_file))
+ .collect::<Result<Vec<String>>>()?
+ } else {
+ vec![]
+ };
+
+ self.read_file_slice_from_paths_stream(&base_file_path, log_file_paths, options)
+ .await
+ }
+
+ /// Reads a file slice from paths as a stream of record batches.
+ ///
+ /// This is the streaming version of [FileGroupReader::read_file_slice_from_paths].
+ ///
+ /// # Arguments
+ /// * `base_file_path` - Relative path to the base file.
+ /// * `log_file_paths` - Iterator of relative paths to log files.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches.
+ pub async fn read_file_slice_from_paths_stream<I, S>(
+ &self,
+ base_file_path: &str,
+ log_file_paths: I,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>>
+ where
+ I: IntoIterator<Item = S>,
+ S: AsRef<str>,
+ {
+ let use_read_optimized: bool = self
+ .hudi_configs
+ .get_or_default(HudiReadConfig::UseReadOptimizedMode)
+ .into();
+
+ if use_read_optimized {
+ return self.read_base_file_stream(base_file_path, options).await;
+ }
+
+ let log_file_paths: Vec<String> = log_file_paths
+ .into_iter()
+ .map(|s| s.as_ref().to_string())
+ .collect();
+
+ if log_file_paths.is_empty() {
+ self.read_base_file_stream(base_file_path, options).await
+ } else {
+ // Fallback: collect + merge, then yield as single-item stream
+ let batch = self
+ .read_file_slice_from_paths(base_file_path, log_file_paths)
+ .await?;
+ Ok(Box::pin(futures::stream::once(async { Ok(batch) })))
+ }
+ }
+
+ /// Reads a base file as a stream of record batches.
+ async fn read_base_file_stream(
+ &self,
+ relative_path: &str,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>> {
+ use crate::config::table::BaseFileFormatValue;
+
+ // Validate base file format is parquet
+ let base_file_format: String = self
+ .hudi_configs
+ .get_or_default(HudiTableConfig::BaseFileFormat)
+ .into();
+ if !base_file_format.eq_ignore_ascii_case(BaseFileFormatValue::Parquet.as_ref()) {
+ return Err(ReadFileSliceError(format!(
+ "Streaming read only supports parquet format, got: {base_file_format}"
+ )));
+ }
+
+ let default_batch_size: usize = self
+ .hudi_configs
+ .get_or_default(HudiReadConfig::StreamBatchSize)
+ .into();
+ let batch_size = options.batch_size.unwrap_or(default_batch_size);
+ let parquet_options = ParquetReadOptions::new().with_batch_size(batch_size);
+
+ let hudi_configs = self.hudi_configs.clone();
+ let path = relative_path.to_string();
+
+ let parquet_stream = self
+ .storage
+ .get_parquet_file_stream(&path, parquet_options)
+ .map_err(|e| ReadFileSliceError(format!("Failed to read path {path}: {e:?}")))
+ .await?;
+
+ // Apply the same filtering logic as read_file_slice_by_base_file_path
+ let stream = parquet_stream
+ .into_stream()
+ .filter_map(move |result| {
+ let hudi_configs = hudi_configs.clone();
+ async move {
+ match result {
+ Err(e) => Some(Err(ReadFileSliceError(format!(
+ "Failed to read batch: {e:?}"
+ )))),
+ Ok(batch) => {
+ match apply_commit_time_filter(&hudi_configs, batch) {
+ Err(e) => Some(Err(e)),
+ Ok(filtered) if filtered.num_rows() > 0 => Some(Ok(filtered)),
+ Ok(_) => None,
+ }
+ }
+ }
+ }
+ });
+
+ Ok(Box::pin(stream))
+ }
Review Comment:
The new streaming APIs lack test coverage. While the existing `read_file_slice` method has tests in the file, there are no tests for `read_file_slice_stream`, `read_file_slice_from_paths_stream`, or `read_base_file_stream`. Given that other similar functions in this file have test coverage, these new streaming functions should also be tested to ensure they work correctly, especially for edge cases like empty batches, filtering, and error conditions.
##########
crates/core/src/table/mod.rs:
##########
@@ -790,6 +793,145 @@ impl Table {
) -> Result<Vec<RecordBatch>> {
todo!("read_incremental_changes")
}
+
+ // =========================================================================
+ // Streaming Read APIs
+ // =========================================================================
+
+ /// Reads a file slice as a stream of record batches.
+ ///
+ /// This is the streaming version of reading a single file slice. It returns a stream
+ /// that yields record batches as they are read, without loading all data into memory.
+ ///
+ /// # Arguments
+ /// * `file_slice` - The file slice to read.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let file_slices = table.get_file_slices(empty_filters()).await?;
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ ///
+ /// for file_slice in &file_slices {
+ /// let mut stream = table.read_file_slice_stream(file_slice, &options).await?;
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// // Process batch...
+ /// }
+ /// }
+ /// ```
+ pub async fn read_file_slice_stream(
+ &self,
+ file_slice: &FileSlice,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>> {
+ let timestamp = options
+ .as_of_timestamp
+ .as_deref()
+ .or_else(|| self.timeline.get_latest_commit_timestamp_as_option());
+
+ let timestamp = match timestamp {
+ Some(ts) => ts.to_string(),
+ None => return Err(crate::error::CoreError::Timeline("No commit timestamp available".to_string())),
+ };
+
+ let fg_reader = self.create_file_group_reader_with_options([(
+ HudiReadConfig::FileGroupEndTimestamp,
+ timestamp.as_str(),
+ )])?;
+
+ fg_reader.read_file_slice_stream(file_slice, options).await
+ }
+
+ /// Reads the table snapshot as a stream of record batches.
+ ///
+ /// This is the streaming version of [Table::read_snapshot]. Instead of returning
+ /// all batches at once, it returns a stream that yields record batches as they
+ /// are read from the underlying file slices.
+ ///
+ /// # Arguments
+ /// * `options` - Read options including partition filters, batch size, etc.
+ ///
+ /// # Returns
+ /// A stream of record batches from all file slices.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let options = ReadOptions::new()
+ /// .with_filters([("city", "=", "san_francisco")])
+ /// .with_batch_size(4096);
+ /// let mut stream = table.read_snapshot_stream(&options).await?;
+ ///
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// println!("Read {} rows", batch.num_rows());
+ /// }
+ /// ```
+ pub async fn read_snapshot_stream(
+ &self,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>> {
+ use futures::stream::{self, StreamExt};
+
+ let Some(timestamp) = self.timeline.get_latest_commit_timestamp_as_option() else {
+ return Ok(Box::pin(stream::empty()));
+ };
+
+ let filters: Vec<Filter> = options
+ .partition_filters
+ .iter()
+ .map(|(f, o, v)| Filter::try_from((f.as_str(), o.as_str(), v.as_str())))
+ .collect::<Result<Vec<_>>>()?;
+ let file_slices = self.get_file_slices_internal(timestamp, &filters).await?;
+
+ if file_slices.is_empty() {
+ return Ok(Box::pin(stream::empty()));
+ }
+
+ let fg_reader = self.create_file_group_reader_with_options([(
+ HudiReadConfig::FileGroupEndTimestamp,
+ timestamp,
+ )])?;
+
+ let batch_size = options.batch_size;
+ let streams_iter = file_slices.into_iter().map(move |file_slice| {
+ let fg_reader = fg_reader.clone();
+ let options = ReadOptions {
+ partition_filters: vec![],
+ projection: None,
+ row_predicate: None,
+ batch_size,
+ as_of_timestamp: None,
+ };
+ async move {
+ fg_reader.read_file_slice_stream(&file_slice, &options).await
+ }
+ });
+
+ let combined_stream = stream::iter(streams_iter)
+ .then(|fut| fut)
+ .filter_map(|result| async move {
+ match result {
+ Ok(stream) => Some(stream),
+ Err(e) => {
+ log::warn!("Failed to read file slice: {:?}", e);
+ None
+ }
+ }
+ })
+ .flatten();
+
+ Ok(Box::pin(combined_stream))
+ }
Review Comment:
The streaming table APIs `read_file_slice_stream` and `read_snapshot_stream` lack test coverage. The existing code has comprehensive tests for the non-streaming versions (e.g., `read_snapshot`, `get_file_slices`), but there are no tests for the new streaming variants. Consider adding tests that verify the streaming behavior, including proper handling of multiple batches, empty streams, and error conditions.
##########
crates/core/src/file_group/reader.rs:
##########
@@ -325,6 +323,166 @@ impl FileGroupReader {
.block_on(self.read_file_slice_from_paths(base_file_path, log_file_paths))
}
+ // =========================================================================
+ // Streaming Read APIs
+ // =========================================================================
+
+ /// Reads a file slice as a stream of record batches.
+ ///
+ /// This is the streaming version of [FileGroupReader::read_file_slice].
+ /// It returns a stream that yields record batches as they are read.
+ ///
+ /// For COW tables or read-optimized mode (base file only), this returns a true
+ /// streaming iterator from the underlying parquet file, yielding batches as they
+ /// are read without loading all data into memory.
+ ///
+ /// For MOR tables with log files, this falls back to the collect-and-merge approach
+ /// and yields the merged result as a single batch.
+ ///
+ /// # Arguments
+ /// * `file_slice` - The file slice to read.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches. The stream owns all necessary data and is `'static`.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ ///
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ /// let mut stream = reader.read_file_slice_stream(&file_slice, &options).await?;
+ ///
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// // Process batch...
+ /// }
+ /// ```
+ pub async fn read_file_slice_stream(
+ &self,
+ file_slice: &FileSlice,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>> {
+ let base_file_path = file_slice.base_file_relative_path()?;
+ let log_file_paths: Vec<String> = if file_slice.has_log_file() {
+ file_slice
+ .log_files
+ .iter()
+ .map(|log_file| file_slice.log_file_relative_path(log_file))
+ .collect::<Result<Vec<String>>>()?
+ } else {
+ vec![]
+ };
+
+ self.read_file_slice_from_paths_stream(&base_file_path, log_file_paths, options)
+ .await
+ }
+
+ /// Reads a file slice from paths as a stream of record batches.
+ ///
+ /// This is the streaming version of [FileGroupReader::read_file_slice_from_paths].
+ ///
+ /// # Arguments
+ /// * `base_file_path` - Relative path to the base file.
+ /// * `log_file_paths` - Iterator of relative paths to log files.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches.
+ pub async fn read_file_slice_from_paths_stream<I, S>(
+ &self,
+ base_file_path: &str,
+ log_file_paths: I,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>>
+ where
+ I: IntoIterator<Item = S>,
+ S: AsRef<str>,
+ {
+ let use_read_optimized: bool = self
+ .hudi_configs
+ .get_or_default(HudiReadConfig::UseReadOptimizedMode)
+ .into();
+
+ if use_read_optimized {
+ return self.read_base_file_stream(base_file_path, options).await;
+ }
+
+ let log_file_paths: Vec<String> = log_file_paths
+ .into_iter()
+ .map(|s| s.as_ref().to_string())
+ .collect();
+
+ if log_file_paths.is_empty() {
+ self.read_base_file_stream(base_file_path, options).await
+ } else {
+ // Fallback: collect + merge, then yield as single-item stream
+ let batch = self
+ .read_file_slice_from_paths(base_file_path, log_file_paths)
+ .await?;
+ Ok(Box::pin(futures::stream::once(async { Ok(batch) })))
+ }
+ }
+
+ /// Reads a base file as a stream of record batches.
+ async fn read_base_file_stream(
+ &self,
+ relative_path: &str,
+ options: &ReadOptions,
+ ) -> Result<BoxStream<'static, Result<RecordBatch>>> {
+ use crate::config::table::BaseFileFormatValue;
+
+ // Validate base file format is parquet
+ let base_file_format: String = self
+ .hudi_configs
+ .get_or_default(HudiTableConfig::BaseFileFormat)
+ .into();
+ if !base_file_format.eq_ignore_ascii_case(BaseFileFormatValue::Parquet.as_ref()) {
+ return Err(ReadFileSliceError(format!(
+ "Streaming read only supports parquet format, got: {base_file_format}"
+ )));
+ }
+
+ let default_batch_size: usize = self
+ .hudi_configs
+ .get_or_default(HudiReadConfig::StreamBatchSize)
+ .into();
+ let batch_size = options.batch_size.unwrap_or(default_batch_size);
+ let parquet_options = ParquetReadOptions::new().with_batch_size(batch_size);
Review Comment:
The `read_base_file_stream` method doesn't utilize the `projection` and `row_predicate` fields from `ReadOptions`. While batch_size is used, column projection could be passed to the ParquetReadOptions to optimize memory usage and I/O, and row predicates could be applied to filter batches in the stream. Consider implementing these features to provide the full functionality advertised by the ReadOptions API.
##########
crates/core/src/table/mod.rs:
##########
@@ -790,6 +793,145 @@ impl Table {
) -> Result<Vec<RecordBatch>> {
todo!("read_incremental_changes")
}
+
+ // =========================================================================
+ // Streaming Read APIs
+ // =========================================================================
+
+ /// Reads a file slice as a stream of record batches.
+ ///
+ /// This is the streaming version of reading a single file slice. It returns a stream
+ /// that yields record batches as they are read, without loading all data into memory.
+ ///
+ /// # Arguments
+ /// * `file_slice` - The file slice to read.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let file_slices = table.get_file_slices(empty_filters()).await?;
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ ///
+ /// for file_slice in &file_slices {
+ /// let mut stream = table.read_file_slice_stream(file_slice, &options).await?;
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// // Process batch...
+ /// }
+ /// }
+ /// ```
+ pub async fn read_file_slice_stream(
+ &self,
+ file_slice: &FileSlice,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>> {
+ let timestamp = options
+ .as_of_timestamp
+ .as_deref()
+ .or_else(|| self.timeline.get_latest_commit_timestamp_as_option());
+
+ let timestamp = match timestamp {
+ Some(ts) => ts.to_string(),
+ None => return Err(crate::error::CoreError::Timeline("No commit timestamp available".to_string())),
+ };
+
+ let fg_reader = self.create_file_group_reader_with_options([(
+ HudiReadConfig::FileGroupEndTimestamp,
+ timestamp.as_str(),
+ )])?;
+
+ fg_reader.read_file_slice_stream(file_slice, options).await
+ }
+
+ /// Reads the table snapshot as a stream of record batches.
+ ///
+ /// This is the streaming version of [Table::read_snapshot]. Instead of returning
+ /// all batches at once, it returns a stream that yields record batches as they
+ /// are read from the underlying file slices.
+ ///
+ /// # Arguments
+ /// * `options` - Read options including partition filters, batch size, etc.
+ ///
+ /// # Returns
+ /// A stream of record batches from all file slices.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let options = ReadOptions::new()
+ /// .with_filters([("city", "=", "san_francisco")])
+ /// .with_batch_size(4096);
+ /// let mut stream = table.read_snapshot_stream(&options).await?;
+ ///
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// println!("Read {} rows", batch.num_rows());
+ /// }
+ /// ```
+ pub async fn read_snapshot_stream(
+ &self,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>> {
+ use futures::stream::{self, StreamExt};
+
+ let Some(timestamp) = self.timeline.get_latest_commit_timestamp_as_option() else {
+ return Ok(Box::pin(stream::empty()));
+ };
+
+ let filters: Vec<Filter> = options
+ .partition_filters
+ .iter()
+ .map(|(f, o, v)| Filter::try_from((f.as_str(), o.as_str(), v.as_str())))
+ .collect::<Result<Vec<_>>>()?;
+ let file_slices = self.get_file_slices_internal(timestamp, &filters).await?;
+
+ if file_slices.is_empty() {
+ return Ok(Box::pin(stream::empty()));
+ }
+
+ let fg_reader = self.create_file_group_reader_with_options([(
+ HudiReadConfig::FileGroupEndTimestamp,
+ timestamp,
+ )])?;
+
+ let batch_size = options.batch_size;
+ let streams_iter = file_slices.into_iter().map(move |file_slice| {
+ let fg_reader = fg_reader.clone();
+ let options = ReadOptions {
+ partition_filters: vec![],
+ projection: None,
+ row_predicate: None,
+ batch_size,
+ as_of_timestamp: None,
+ };
+ async move {
+ fg_reader.read_file_slice_stream(&file_slice, &options).await
+ }
+ });
+
+ let combined_stream = stream::iter(streams_iter)
+ .then(|fut| fut)
+ .filter_map(|result| async move {
+ match result {
+ Ok(stream) => Some(stream),
+ Err(e) => {
+ log::warn!("Failed to read file slice: {:?}", e);
+ None
Review Comment:
Failed file slice reads are silently logged and skipped using `log::warn!` and `filter_map`. This means users won't know if some of their data failed to read. Consider either propagating the error to the caller or providing a configuration option to control this behavior. Silent data loss can lead to incorrect query results without user awareness.
```suggestion
.map(|result| {
match result {
Ok(stream) => stream,
Err(e) => {
log::warn!("Failed to read file slice: {:?}", e);
stream::once(async { Err(e) }).boxed()
```
##########
crates/core/src/file_group/reader.rs:
##########
@@ -425,6 +583,60 @@ impl FileGroupReader {
}
}
+/// Apply commit time filtering to a record batch.
+///
+/// This function mirrors the filtering logic in `FileGroupReader::create_filtering_mask_for_base_file_records`
+/// but takes `HudiConfigs` directly so it can be used in streaming contexts where `&self` is not available.
+fn apply_commit_time_filter(hudi_configs: &HudiConfigs, batch: RecordBatch) -> Result<RecordBatch> {
+ let populates_meta_fields: bool = hudi_configs
+ .get_or_default(HudiTableConfig::PopulatesMetaFields)
+ .into();
+ if !populates_meta_fields {
+ return Ok(batch);
+ }
+
+ let start_ts = hudi_configs
+ .try_get(HudiReadConfig::FileGroupStartTimestamp)
+ .map(|v| -> String { v.into() });
+ if start_ts.is_none() {
+ // If start timestamp is not provided, the query is snapshot or time-travel
+ return Ok(batch);
+ }
+
+ let mut and_filters: Vec<SchemableFilter> = Vec::new();
+ let schema = MetaField::schema();
+
+ if let Some(start) = start_ts {
+ let filter = Filter::try_from((MetaField::CommitTime.as_ref(), ">", start.as_str()))?;
+ and_filters.push(SchemableFilter::try_from((filter, schema.as_ref()))?);
+ }
+
+ if let Some(end) = hudi_configs
+ .try_get(HudiReadConfig::FileGroupEndTimestamp)
+ .map(|v| -> String { v.into() })
+ {
+ let filter = Filter::try_from((MetaField::CommitTime.as_ref(), "<=", end.as_str()))?;
+ and_filters.push(SchemableFilter::try_from((filter, schema.as_ref()))?);
+ }
+
+ if and_filters.is_empty() {
+ return Ok(batch);
+ }
+
+ let mut mask = BooleanArray::from(vec![true; batch.num_rows()]);
+ for filter in &and_filters {
+ let col_name = filter.field.name().as_str();
+ let col_values = batch
+ .column_by_name(col_name)
+ .ok_or_else(|| ReadFileSliceError(format!("Column {col_name} not found")))?;
+ let comparison = filter.apply_comparsion(col_values)?;
Review Comment:
This line contains a typo in the method name. The method is called `apply_comparsion` but it should be `apply_comparison`. This is an existing typo in the codebase (also present in the SchemableFilter implementation), but since you're now calling it from new code in the `apply_commit_time_filter` function, it's worth noting that this function should be renamed for clarity.
##########
crates/core/src/file_group/reader.rs:
##########
@@ -425,6 +583,60 @@ impl FileGroupReader {
}
}
+/// Apply commit time filtering to a record batch.
+///
+/// This function mirrors the filtering logic in `FileGroupReader::create_filtering_mask_for_base_file_records`
+/// but takes `HudiConfigs` directly so it can be used in streaming contexts where `&self` is not available.
+fn apply_commit_time_filter(hudi_configs: &HudiConfigs, batch: RecordBatch) -> Result<RecordBatch> {
+ let populates_meta_fields: bool = hudi_configs
+ .get_or_default(HudiTableConfig::PopulatesMetaFields)
+ .into();
+ if !populates_meta_fields {
+ return Ok(batch);
+ }
+
+ let start_ts = hudi_configs
+ .try_get(HudiReadConfig::FileGroupStartTimestamp)
+ .map(|v| -> String { v.into() });
+ if start_ts.is_none() {
+ // If start timestamp is not provided, the query is snapshot or time-travel
+ return Ok(batch);
+ }
+
+ let mut and_filters: Vec<SchemableFilter> = Vec::new();
+ let schema = MetaField::schema();
+
+ if let Some(start) = start_ts {
+ let filter = Filter::try_from((MetaField::CommitTime.as_ref(), ">", start.as_str()))?;
+ and_filters.push(SchemableFilter::try_from((filter, schema.as_ref()))?);
+ }
+
+ if let Some(end) = hudi_configs
+ .try_get(HudiReadConfig::FileGroupEndTimestamp)
+ .map(|v| -> String { v.into() })
+ {
+ let filter = Filter::try_from((MetaField::CommitTime.as_ref(), "<=", end.as_str()))?;
+ and_filters.push(SchemableFilter::try_from((filter, schema.as_ref()))?);
+ }
+
+ if and_filters.is_empty() {
+ return Ok(batch);
+ }
+
+ let mut mask = BooleanArray::from(vec![true; batch.num_rows()]);
+ for filter in &and_filters {
+ let col_name = filter.field.name().as_str();
+ let col_values = batch
+ .column_by_name(col_name)
+ .ok_or_else(|| ReadFileSliceError(format!("Column {col_name} not found")))?;
+ let comparison = filter.apply_comparsion(col_values)?;
+ mask = and(&mask, &comparison)?;
+ }
+
+ filter_record_batch(&batch, &mask)
+ .map_err(|e| ReadFileSliceError(format!("Failed to filter records: {e:?}")))
+}
Review Comment:
The `apply_commit_time_filter` function duplicates logic from `FileGroupReader::create_filtering_mask_for_base_file_records`. While the comment acknowledges this, code duplication can lead to maintenance issues if one is updated but not the other. Consider refactoring the common logic into a shared helper function that both can use, or have `create_filtering_mask_for_base_file_records` call `apply_commit_time_filter` internally.
--
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: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat: add streaming table and file group APIs [hudi-rs]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #508:
URL: https://github.com/apache/hudi-rs/pull/508#issuecomment-3707607761
## [Codecov](https://app.codecov.io/gh/apache/hudi-rs/pull/508?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `2.15054%` with `182 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 81.85%. Comparing base ([`065fd31`](https://app.codecov.io/gh/apache/hudi-rs/commit/065fd3131e855cb26d0882eb2e7b814539f711a2?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`6ed6db8`](https://app.codecov.io/gh/apache/hudi-rs/commit/6ed6db87ab045753a24db7bd47d4eeaf02a5db16?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
| [Files with missing lines](https://app.codecov.io/gh/apache/hudi-rs/pull/508?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [crates/core/src/file\_group/reader.rs](https://app.codecov.io/gh/apache/hudi-rs/pull/508?src=pr&el=tree&filepath=crates%2Fcore%2Fsrc%2Ffile_group%2Freader.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y3JhdGVzL2NvcmUvc3JjL2ZpbGVfZ3JvdXAvcmVhZGVyLnJz) | 0.00% | [88 Missing :warning: ](https://app.codecov.io/gh/apache/hudi-rs/pull/508?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [crates/core/src/table/mod.rs](https://app.codecov.io/gh/apache/hudi-rs/pull/508?src=pr&el=tree&filepath=crates%2Fcore%2Fsrc%2Ftable%2Fmod.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y3JhdGVzL2NvcmUvc3JjL3RhYmxlL21vZC5ycw==) | 0.00% | [40 Missing :warning: ](https://app.codecov.io/gh/apache/hudi-rs/pull/508?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [crates/core/src/storage/mod.rs](https://app.codecov.io/gh/apache/hudi-rs/pull/508?src=pr&el=tree&filepath=crates%2Fcore%2Fsrc%2Fstorage%2Fmod.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y3JhdGVzL2NvcmUvc3JjL3N0b3JhZ2UvbW9kLnJz) | 0.00% | [32 Missing :warning: ](https://app.codecov.io/gh/apache/hudi-rs/pull/508?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [crates/core/src/table/read\_options.rs](https://app.codecov.io/gh/apache/hudi-rs/pull/508?src=pr&el=tree&filepath=crates%2Fcore%2Fsrc%2Ftable%2Fread_options.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y3JhdGVzL2NvcmUvc3JjL3RhYmxlL3JlYWRfb3B0aW9ucy5ycw==) | 0.00% | [20 Missing :warning: ](https://app.codecov.io/gh/apache/hudi-rs/pull/508?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [crates/core/src/config/read.rs](https://app.codecov.io/gh/apache/hudi-rs/pull/508?src=pr&el=tree&filepath=crates%2Fcore%2Fsrc%2Fconfig%2Fread.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y3JhdGVzL2NvcmUvc3JjL2NvbmZpZy9yZWFkLnJz) | 66.66% | [2 Missing :warning: ](https://app.codecov.io/gh/apache/hudi-rs/pull/508?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## main #508 +/- ##
==========================================
- Coverage 85.65% 81.85% -3.81%
==========================================
Files 65 66 +1
Lines 3897 4083 +186
==========================================
+ Hits 3338 3342 +4
- Misses 559 741 +182
```
</details>
[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/hudi-rs/pull/508?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
</details>
--
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: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat: add streaming table and file group APIs [hudi-rs]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #508:
URL: https://github.com/apache/hudi-rs/pull/508#discussion_r2659445076
##########
crates/core/tests/table_read_tests.rs:
##########
@@ -555,6 +555,228 @@ mod v8_tables {
}
}
+/// Test module for streaming read APIs.
+/// These tests verify the streaming versions of snapshot and file slice reads.
+mod streaming_queries {
+ use super::*;
+ use futures::StreamExt;
+ use hudi_core::table::ReadOptions;
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_empty_table() -> Result<()> {
+ for base_url in SampleTable::V6Empty.urls() {
+ let hudi_table = Table::new(base_url.path()).await?;
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+ assert!(batches.is_empty(), "Empty table should produce no batches");
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_basic() -> Result<()> {
+ for base_url in SampleTable::V6Nonpartitioned.urls() {
+ let hudi_table = Table::new(base_url.path()).await?;
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(!batches.is_empty(), "Should produce at least one batch");
+
+ // Concatenate batches and verify data
+ let schema = &batches[0].schema();
+ let records = concat_batches(schema, &batches)?;
+
+ let sample_data = SampleTable::sample_data_order_by_id(&records);
+ assert_eq!(
+ sample_data,
+ vec![
+ (1, "Alice", false),
+ (2, "Bob", false),
+ (3, "Carol", true),
+ (4, "Diana", true),
+ ]
+ );
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_with_batch_size() -> Result<()> {
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ // Request small batch size
+ let options = ReadOptions::new().with_batch_size(1);
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ // With batch_size=1 and 4 rows, we should get multiple batches
+ // (exact number depends on parquet row groups)
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(total_rows, 4, "Total rows should match expected count");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_with_partition_filters() -> Result<()> {
+ let base_url = SampleTable::V6ComplexkeygenHivestyle.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let options = ReadOptions::new().with_filters([
+ ("byteField", ">=", "10"),
+ ("byteField", "<", "20"),
+ ("shortField", "!=", "100"),
+ ]);
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ let schema = &batches[0].schema();
Review Comment:
The test accesses `batches[0]` without checking if the vector is non-empty. While this follows the existing pattern in this test file (see lines 53, 86, 107, etc.), consider adding an assertion like `assert!(!batches.is_empty())` before this line for better test clarity and error messages, especially since this is part of new streaming API tests where behavior might differ from the existing non-streaming APIs.
##########
crates/core/src/storage/mod.rs:
##########
@@ -47,6 +49,62 @@ pub mod file_metadata;
pub mod reader;
pub mod util;
+/// Options for reading Parquet files with streaming.
+#[derive(Clone, Debug, Default)]
+pub struct ParquetReadOptions {
+ /// Target batch size (number of rows per batch).
+ pub batch_size: Option<usize>,
+ /// Column projection (indices of columns to read).
+ pub projection: Option<Vec<usize>>,
+}
+
+impl ParquetReadOptions {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn with_batch_size(mut self, batch_size: usize) -> Self {
+ self.batch_size = Some(batch_size);
+ self
+ }
+
+ pub fn with_projection(mut self, projection: Vec<usize>) -> Self {
+ self.projection = Some(projection);
+ self
+ }
+}
Review Comment:
The `ParquetReadOptions` struct duplicates some of the same configuration as `ReadOptions` (batch_size, projection). While `ParquetReadOptions` is for internal use at the storage layer and `ReadOptions` is the public API, this duplication means manual mapping between the two. Consider whether `ParquetReadOptions` could be derived directly from `ReadOptions` to avoid potential inconsistencies and reduce the need for manual field-by-field mapping.
##########
crates/core/tests/table_read_tests.rs:
##########
@@ -555,6 +555,228 @@ mod v8_tables {
}
}
+/// Test module for streaming read APIs.
+/// These tests verify the streaming versions of snapshot and file slice reads.
+mod streaming_queries {
+ use super::*;
+ use futures::StreamExt;
+ use hudi_core::table::ReadOptions;
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_empty_table() -> Result<()> {
+ for base_url in SampleTable::V6Empty.urls() {
+ let hudi_table = Table::new(base_url.path()).await?;
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+ assert!(batches.is_empty(), "Empty table should produce no batches");
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_basic() -> Result<()> {
+ for base_url in SampleTable::V6Nonpartitioned.urls() {
+ let hudi_table = Table::new(base_url.path()).await?;
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(!batches.is_empty(), "Should produce at least one batch");
+
+ // Concatenate batches and verify data
+ let schema = &batches[0].schema();
+ let records = concat_batches(schema, &batches)?;
+
+ let sample_data = SampleTable::sample_data_order_by_id(&records);
+ assert_eq!(
+ sample_data,
+ vec![
+ (1, "Alice", false),
+ (2, "Bob", false),
+ (3, "Carol", true),
+ (4, "Diana", true),
+ ]
+ );
+ }
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_with_batch_size() -> Result<()> {
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ // Request small batch size
+ let options = ReadOptions::new().with_batch_size(1);
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ // With batch_size=1 and 4 rows, we should get multiple batches
+ // (exact number depends on parquet row groups)
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(total_rows, 4, "Total rows should match expected count");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_with_partition_filters() -> Result<()> {
+ let base_url = SampleTable::V6ComplexkeygenHivestyle.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let options = ReadOptions::new().with_filters([
+ ("byteField", ">=", "10"),
+ ("byteField", "<", "20"),
+ ("shortField", "!=", "100"),
+ ]);
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ let schema = &batches[0].schema();
+ let records = concat_batches(schema, &batches)?;
+
+ let sample_data = SampleTable::sample_data_order_by_id(&records);
+ assert_eq!(sample_data, vec![(1, "Alice", false), (3, "Carol", true),]);
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_file_slice_stream_basic() -> Result<()> {
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ // Get file slices first
+ let file_slices = hudi_table.get_file_slices(empty_filters()).await?;
+ assert!(
+ !file_slices.is_empty(),
+ "Should have at least one file slice"
+ );
+
+ let options = ReadOptions::new();
+ let file_slice = &file_slices[0];
+ let mut stream = hudi_table
+ .read_file_slice_stream(file_slice, &options)
+ .await?;
+
+ // Collect all batches from stream
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(!batches.is_empty(), "Should produce at least one batch");
+
+ // Verify we got records
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert!(total_rows > 0, "Should read at least one row");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_file_slice_stream_with_batch_size() -> Result<()> {
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let file_slices = hudi_table.get_file_slices(empty_filters()).await?;
+ let file_slice = &file_slices[0];
+
+ // Test with small batch size
+ let options = ReadOptions::new().with_batch_size(1);
+ let mut stream = hudi_table
+ .read_file_slice_stream(file_slice, &options)
+ .await?;
+
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(total_rows, 4, "Should read all 4 rows");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_mor_with_log_files() -> Result<()> {
+ // Test MOR table with log files - should still work (falls back to collect+merge)
+ let base_url = QuickstartTripsTable::V6Trips8I1U.url_to_mor_avro();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ let mut batches = Vec::new();
+ while let Some(result) = stream.next().await {
+ batches.push(result?);
+ }
+
+ assert!(!batches.is_empty(), "Should produce batches from MOR table");
+
+ // Verify total row count
+ let total_rows: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(total_rows, 8, "Should have 8 rows (8 inserts)");
+ Ok(())
+ }
+
+ #[tokio::test]
+ async fn test_read_snapshot_stream_error_propagation() -> Result<()> {
+ // This test verifies that if we read from a valid table, no errors are propagated
+ // (We can't easily trigger file read errors in a unit test without mocking)
+ let base_url = SampleTable::V6Nonpartitioned.url_to_cow();
+ let hudi_table = Table::new(base_url.path()).await?;
+
+ let options = ReadOptions::new();
+ let mut stream = hudi_table.read_snapshot_stream(&options).await?;
+
+ // All reads should succeed without error
+ while let Some(result) = stream.next().await {
+ assert!(result.is_ok(), "Reading should not produce errors");
+ }
+ Ok(())
+ }
Review Comment:
The test `test_read_snapshot_stream_error_propagation` doesn't actually test error propagation - it only verifies that reading a valid table doesn't produce errors. As noted in the comment, it can't easily trigger file read errors without mocking. This test name is misleading. Consider renaming it to something like `test_read_snapshot_stream_successful_read` or implementing actual error propagation testing using integration test fixtures with invalid data.
##########
crates/core/src/table/mod.rs:
##########
@@ -790,6 +793,157 @@ impl Table {
) -> Result<Vec<RecordBatch>> {
todo!("read_incremental_changes")
}
+
+ // =========================================================================
+ // Streaming Read APIs
+ // =========================================================================
+
+ /// Reads a file slice as a stream of record batches.
+ ///
+ /// This is the streaming version of reading a single file slice. It returns a stream
+ /// that yields record batches as they are read, without loading all data into memory.
+ ///
+ /// # Arguments
+ /// * `file_slice` - The file slice to read.
+ /// * `options` - Read options for configuring the read operation.
+ ///
+ /// # Returns
+ /// A stream of record batches.
+ ///
+ /// # Example
+ /// ```ignore
+ /// use futures::StreamExt;
+ /// use hudi::table::ReadOptions;
+ ///
+ /// let file_slices = table.get_file_slices(empty_filters()).await?;
+ /// let options = ReadOptions::new().with_batch_size(4096);
+ ///
+ /// for file_slice in &file_slices {
+ /// let mut stream = table.read_file_slice_stream(file_slice, &options).await?;
+ /// while let Some(result) = stream.next().await {
+ /// let batch = result?;
+ /// // Process batch...
+ /// }
+ /// }
+ /// ```
+ pub async fn read_file_slice_stream(
+ &self,
+ file_slice: &FileSlice,
+ options: &ReadOptions,
+ ) -> Result<futures::stream::BoxStream<'static, Result<RecordBatch>>> {
+ let timestamp = options
+ .as_of_timestamp
+ .as_deref()
+ .or_else(|| self.timeline.get_latest_commit_timestamp_as_option());
+
+ let timestamp = match timestamp {
+ Some(ts) => ts.to_string(),
Review Comment:
Calling `.to_string()` on an `Option<&str>` that's already a reference is inefficient. The `timestamp` is immediately converted to string only to be passed as `&str` to the file group reader. Consider avoiding this allocation by keeping it as `&str` throughout, or restructure to avoid the unnecessary conversion.
--
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: commits-unsubscribe@hudi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org