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

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


The following commit(s) were added to refs/heads/main by this push:
     new 856a96a0 perf(datafusion): reuse cached file slices across scan plans 
(#1109)
856a96a0 is described below

commit 856a96a06b30b8d7ec431abc30f24cce73dae658
Author: slfan1989 <[email protected]>
AuthorDate: Sun Dec 6 03:01:35 2026 +0800

    perf(datafusion): reuse cached file slices across scan plans (#1109)
---
 crates/datafusion/src/hudi_exec.rs | 106 +++++++++++++++++++++++++++----------
 crates/datafusion/src/lib.rs       |  32 ++++++-----
 2 files changed, 97 insertions(+), 41 deletions(-)

diff --git a/crates/datafusion/src/hudi_exec.rs 
b/crates/datafusion/src/hudi_exec.rs
index f5ba3071..97e3d64a 100644
--- a/crates/datafusion/src/hudi_exec.rs
+++ b/crates/datafusion/src/hudi_exec.rs
@@ -20,6 +20,7 @@
 //! [`FileGroupReader`], supporting all base file formats and MOR log merging.
 
 use std::fmt;
+use std::ops::Range;
 use std::pin::Pin;
 use std::sync::Arc;
 use std::task::{Context, Poll};
@@ -42,7 +43,7 @@ use datafusion_physical_expr::PhysicalExpr;
 use futures::stream::{self, BoxStream, TryStreamExt};
 use futures::{Stream, StreamExt};
 
-use crate::{external_error, inexact_usize_from_u64, view_type};
+use crate::{external_error, inexact_usize_from_u64, slices_per_partition, 
view_type};
 use hudi_core::file_group::file_slice::FileSlice;
 use hudi_core::file_group::reader::FileGroupReader;
 use hudi_core::table::ReadOptions;
@@ -56,7 +57,10 @@ use hudi_core::table::ReadOptions;
 /// native `ParquetSource` path for row-group/page-level pruning.
 #[derive(Debug)]
 pub struct HudiScanExec {
-    file_slice_partitions: Vec<Arc<Vec<FileSlice>>>,
+    // The provider's cache owns the same listing. Partition ranges let several
+    // plans reuse it without copying file names and log metadata per slice.
+    file_slices: Arc<Vec<FileSlice>>,
+    file_slice_partitions: Vec<Range<usize>>,
     file_group_reader: Arc<FileGroupReader>,
     read_options: ReadOptions,
     input_partitions: usize,
@@ -109,7 +113,7 @@ impl HudiScanExec {
 
     #[allow(clippy::too_many_arguments)]
     pub fn new(
-        file_slice_partitions: Vec<Vec<FileSlice>>,
+        file_slices: Arc<Vec<FileSlice>>,
         file_group_reader: Arc<FileGroupReader>,
         read_options: ReadOptions,
         input_partitions: usize,
@@ -130,11 +134,11 @@ impl HudiScanExec {
         // (DataFusion's planners typically expect at least one partition; some
         // operators panic on zero). `execute(0)` then returns an empty stream
         // via the `if file_slices.is_empty()` short-circuit below.
-        let partitions: Vec<Arc<Vec<FileSlice>>> = if 
file_slice_partitions.is_empty() {
-            vec![Arc::new(vec![])]
-        } else {
-            file_slice_partitions.into_iter().map(Arc::new).collect()
-        };
+        let chunk_size = slices_per_partition(file_slices.len(), 
input_partitions);
+        let partitions: Vec<_> = (0..file_slices.len().max(1))
+            .step_by(chunk_size)
+            .map(|start| start..(start + chunk_size).min(file_slices.len()))
+            .collect();
         let n_partitions = partitions.len();
 
         let properties = PlanProperties::new(
@@ -145,6 +149,7 @@ impl HudiScanExec {
         );
 
         Self {
+            file_slices,
             file_slice_partitions: partitions,
             file_group_reader,
             read_options,
@@ -162,6 +167,11 @@ impl HudiScanExec {
     pub(crate) fn read_options(&self) -> &ReadOptions {
         &self.read_options
     }
+
+    #[cfg(test)]
+    pub(crate) fn file_slices(&self) -> &Arc<Vec<FileSlice>> {
+        &self.file_slices
+    }
 }
 
 /// Cast the string and binary columns of `batch` to the view types `schema`
@@ -319,7 +329,6 @@ impl Stream for BaselineMetricStream {
 
 impl DisplayAs for HudiScanExec {
     fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> 
fmt::Result {
-        let total_slices: usize = self.file_slice_partitions.iter().map(|p| 
p.len()).sum();
         match t {
             DisplayFormatType::Default | DisplayFormatType::Verbose => {
                 write!(
@@ -327,7 +336,7 @@ impl DisplayAs for HudiScanExec {
                     "HudiScanExec: input_partitions={}, partitions={}, 
file_slices={}, file_slice_read_concurrency={}, projection={:?}, limit={:?}",
                     self.input_partitions,
                     self.file_slice_partitions.len(),
-                    total_slices,
+                    self.file_slices.len(),
                     self.file_slice_read_concurrency,
                     self.projection,
                     self.limit,
@@ -394,7 +403,7 @@ impl ExecutionPlan for HudiScanExec {
         partition: usize,
         context: Arc<datafusion::execution::TaskContext>,
     ) -> Result<SendableRecordBatchStream> {
-        let file_slices = self
+        let indices = self
             .file_slice_partitions
             .get(partition)
             .ok_or_else(|| {
@@ -404,6 +413,7 @@ impl ExecutionPlan for HudiScanExec {
                 ))
             })?
             .clone();
+        let file_slices = &self.file_slices[indices.clone()];
 
         let projected_schema = self.projected_schema.clone();
         let baseline_metrics = BaselineMetrics::new(&self.metrics, partition);
@@ -428,7 +438,7 @@ impl ExecutionPlan for HudiScanExec {
         // the bytes.
         let mut reservation = 
MemoryConsumer::new(format!("HudiScanExec[{partition}]"))
             .register(context.memory_pool());
-        let planned = Self::planned_slices(self.file_slice_read_concurrency, 
&file_slices);
+        let planned = Self::planned_slices(self.file_slice_read_concurrency, 
file_slices);
         let per_slice = file_slices
             .iter()
             .map(|s| {
@@ -440,18 +450,18 @@ impl ExecutionPlan for HudiScanExec {
             .unwrap_or(0) as usize;
         let concurrency = Self::reserve_for_slices(&mut reservation, 
per_slice, planned);
 
-        let stream = stream::iter(0..file_slices.len())
+        let file_slices = Arc::clone(&self.file_slices);
+        let stream = stream::iter(indices)
             .map(move |idx| {
-                let file_slice = file_slices[idx].clone();
+                let file_slices = Arc::clone(&file_slices);
                 let reader = reader.clone();
                 let options = options.clone();
                 let declared = declared.clone();
                 async move {
-                    let inner_stream =
-                        reader
-                            .read_file_slice_stream(&file_slice, &options)
-                            .await
-                            .map_err(|e| external_error("Failed to read file 
slice", e))?;
+                    let inner_stream = reader
+                        .read_file_slice_stream(&file_slices[idx], &options)
+                        .await
+                        .map_err(|e| external_error("Failed to read file 
slice", e))?;
                     Ok::<_, DataFusionError>(
                         inner_stream
                             .map_err(|e| external_error("Failed to read 
batch", e))
@@ -492,26 +502,23 @@ impl ExecutionPlan for HudiScanExec {
         let column_statistics =
             vec![ColumnStatistics::new_unknown(); 
self.projected_schema.fields().len()];
 
-        let partitions: Box<dyn Iterator<Item = &[FileSlice]> + '_> = match 
partition {
-            None => Box::new(
-                self.file_slice_partitions
-                    .iter()
-                    .map(|slices| slices.as_slice()),
-            ),
+        let slices = match partition {
+            None => self.file_slices.as_slice(),
             Some(idx) => match self.file_slice_partitions.get(idx) {
-                Some(slices) => Box::new(std::iter::once(slices.as_slice())),
+                Some(indices) => &self.file_slices[indices.clone()],
                 None => return 
Ok(Arc::new(Statistics::new_unknown(&self.projected_schema))),
             },
         };
 
         Ok(Arc::new(Self::aggregate_partitions(
-            partitions,
+            std::iter::once(slices),
             column_statistics,
         )))
     }
 
     fn with_fetch(&self, limit: Option<usize>) -> Option<Arc<dyn 
ExecutionPlan>> {
         Some(Arc::new(Self {
+            file_slices: Arc::clone(&self.file_slices),
             file_slice_partitions: self.file_slice_partitions.clone(),
             file_group_reader: self.file_group_reader.clone(),
             read_options: self.read_options.clone(),
@@ -930,7 +937,7 @@ mod tests {
                 .unwrap(),
         );
         let exec = HudiScanExec::new(
-            vec![],
+            Arc::new(vec![]),
             reader,
             ReadOptions::new(),
             1,
@@ -941,5 +948,48 @@ mod tests {
         );
 
         assert!(exec.metrics().is_some());
+        assert_eq!(exec.properties.output_partitioning().partition_count(), 1);
+        assert_eq!(exec.file_slice_partitions[0], 0..0);
+    }
+
+    #[tokio::test]
+    async fn test_partition_statistics_uses_only_its_range_of_shared_slices() {
+        use datafusion::physical_plan::statistics::{StatisticsArgs, 
StatisticsContext};
+
+        let base_path = 
canonicalize(Path::new("tests/data/table_props_valid")).unwrap();
+        let base_url = Url::from_file_path(base_path).unwrap();
+        let reader = Arc::new(
+            FileGroupReader::new_with_options(base_url.as_str(), 
empty_options())
+                .await
+                .unwrap(),
+        );
+        let file_slices = (1..=5)
+            .map(|rows| {
+                file_slice_with_meta(
+                    &format!("file-{rows}_0-1-1_20250101000000000.parquet"),
+                    100,
+                    rows,
+                    200,
+                )
+            })
+            .collect();
+        let exec = HudiScanExec::new(
+            Arc::new(file_slices),
+            reader,
+            ReadOptions::new(),
+            2,
+            1,
+            Arc::new(Schema::empty()),
+            None,
+            None,
+        );
+        assert_eq!(exec.properties.output_partitioning().partition_count(), 2);
+        let stats = StatisticsContext::new();
+        for (partition, expected) in [(Some(0), 6), (Some(1), 9), (None, 15)] {
+            let actual = stats
+                .compute(&exec, 
&StatisticsArgs::new().with_partition(partition))
+                .unwrap();
+            assert_eq!(actual.num_rows, Precision::Inexact(expected));
+        }
     }
 }
diff --git a/crates/datafusion/src/lib.rs b/crates/datafusion/src/lib.rs
index d16b4d05..f3e9b335 100644
--- a/crates/datafusion/src/lib.rs
+++ b/crates/datafusion/src/lib.rs
@@ -117,6 +117,10 @@ fn default_file_slice_read_concurrency() -> usize {
     }
 }
 
+fn slices_per_partition(num_slices: usize, input_partitions: usize) -> usize {
+    num_slices.div_ceil(input_partitions.max(1)).max(1)
+}
+
 pub(crate) fn inexact_usize_from_u64(value: u64) -> Precision<usize> {
     match usize::try_from(value) {
         Ok(value) => Precision::Inexact(value),
@@ -452,7 +456,7 @@ impl HudiDataSource {
     async fn get_file_slices_cached(
         &self,
         pushdown_filters: &[(String, String, String)],
-    ) -> Result<Vec<FileSlice>> {
+    ) -> Result<Arc<Vec<FileSlice>>> {
         if let Some(slices) = self
             .file_slice_cache
             .lock()
@@ -460,7 +464,7 @@ impl HudiDataSource {
             .entries
             .get(pushdown_filters)
         {
-            return Ok(slices.as_ref().clone());
+            return Ok(Arc::clone(slices));
         }
         let read_options =
             self.scan_read_options(pushdown_filters.to_vec(), 
self.effective_read_optimized())?;
@@ -474,7 +478,7 @@ impl HudiDataSource {
             .lock()
             .await
             .insert(pushdown_filters.to_vec(), Arc::clone(&shared));
-        Ok(shared.as_ref().clone())
+        Ok(shared)
     }
 
     #[cfg(test)]
@@ -839,11 +843,11 @@ impl HudiDataSource {
         state: &dyn Session,
         projection: Option<&Vec<usize>>,
         limit: Option<usize>,
-        flat_slices: Vec<FileSlice>,
+        flat_slices: &[FileSlice],
     ) -> Result<Arc<dyn ExecutionPlan>> {
         let input_partitions = self.get_input_partitions_for_scan(state);
         let file_slices =
-            hudi_core::util::collection::split_into_chunks(flat_slices, 
input_partitions);
+            flat_slices.chunks(slices_per_partition(flat_slices.len(), 
input_partitions));
         let base_url = self.table.base_url();
         let mut parquet_file_groups: Vec<Vec<PartitionedFile>> = Vec::new();
         for file_slice_vec in file_slices {
@@ -920,7 +924,7 @@ impl HudiDataSource {
         projection: Option<&Vec<usize>>,
         limit: Option<usize>,
         input_partitions: usize,
-        flat_slices: Vec<FileSlice>,
+        flat_slices: Arc<Vec<FileSlice>>,
         read_options: ReadOptions,
     ) -> Result<Arc<dyn ExecutionPlan>> {
         // Derive the fan-out from the scan's memory budget when one is set. 
The
@@ -935,9 +939,6 @@ impl HudiDataSource {
             &slice_log_bytes,
             self.file_slice_read_concurrency,
         );
-        let file_slices =
-            hudi_core::util::collection::split_into_chunks(flat_slices, 
input_partitions);
-
         // The reader is built with the caller's full options so table-level
         // setup sees the same query context. Dropped partition filters are 
only
         // stripped from the per-slice options passed into HudiScanExec below,
@@ -960,7 +961,7 @@ impl HudiDataSource {
         }
 
         Ok(Arc::new(HudiScanExec::new(
-            file_slices,
+            flat_slices,
             file_group_reader,
             hudi_read_options,
             input_partitions,
@@ -1086,7 +1087,7 @@ impl TableProvider for HudiDataSource {
                     &partition_read_options,
                     &partition_flat_slices,
                 )? {
-                    self.scan_parquet(state, projection, limit, 
partition_flat_slices)
+                    self.scan_parquet(state, projection, limit, 
&partition_flat_slices)
                         .await
                 } else {
                     let flat_slices = if all_filters_are_partition_filters {
@@ -1370,7 +1371,7 @@ mod tests {
         let ctx = SessionContext::new();
         let state = ctx.state();
         let err = hudi
-            .scan_parquet(&state, None, None, slices)
+            .scan_parquet(&state, None, None, &slices)
             .await
             .expect_err("a sizeless base file must not reach DataFusion as 
zero bytes");
         assert!(err.to_string().contains("has no known size"), "{err}");
@@ -1720,6 +1721,11 @@ mod tests {
         assert_eq!(hudi.file_slice_cache_len().await, 1);
 
         let second = hudi.scan(&state, None, &[], None).await.unwrap();
+        let cached = hudi.get_file_slices_cached(&[]).await.unwrap();
+        for plan in [&first, &second] {
+            let exec = plan.downcast_ref::<HudiScanExec>().unwrap();
+            assert!(Arc::ptr_eq(exec.file_slices(), &cached));
+        }
         assert_eq!(
             hudi.file_slice_cache_len().await,
             1,
@@ -1796,7 +1802,7 @@ mod tests {
         let flat_slices = 
hudi.table.get_file_slices(&read_options).await.unwrap();
 
         let plan = hudi
-            .scan_hudi(None, None, 1, flat_slices, read_options)
+            .scan_hudi(None, None, 1, Arc::new(flat_slices), read_options)
             .await
             .unwrap();
         let exec = plan

Reply via email to