You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by ka...@apache.org on 2026/07/05 15:14:06 UTC

(datafusion) branch final-aggr-with-lazily-materialize-poc-candidate1 updated: Hash selected final partition rows on replay

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

Rachelint pushed a commit to branch final-aggr-with-lazily-materialize-poc-candidate1
in repository https://gitbox.apache.org/repos/asf/datafusion.git


The following commit(s) were added to refs/heads/final-aggr-with-lazily-materialize-poc-candidate1 by this push:
     new eb7bee56e7 Hash selected final partition rows on replay
eb7bee56e7 is described below

commit eb7bee56e78fa42693d64c7e21bd2ab9df0a8f63
Author: kamille <ka...@apache.org>
AuthorDate: Sun Jul 5 23:14:00 2026 +0800

    Hash selected final partition rows on replay
---
 datafusion/common/src/hash_utils.rs                | 296 +++++++++++++++++++++
 .../aggregates/aggregate_hash_table/final_table.rs |  17 +-
 .../src/aggregates/group_values/mod.rs             |  21 +-
 .../physical-plan/src/aggregates/hash_aggregate.rs |  65 +++--
 4 files changed, 366 insertions(+), 33 deletions(-)

diff --git a/datafusion/common/src/hash_utils.rs b/datafusion/common/src/hash_utils.rs
index 1443b6152b..66eccc46e9 100644
--- a/datafusion/common/src/hash_utils.rs
+++ b/datafusion/common/src/hash_utils.rs
@@ -299,6 +299,57 @@ fn hash_array_primitive<T>(
     }
 }
 
+#[cfg(not(feature = "force_hash_collisions"))]
+fn hash_array_primitive_indices<T>(
+    array: &PrimitiveArray<T>,
+    random_state: &impl HashState,
+    indices: &[usize],
+    hashes_buffer: &mut [u64],
+    rehash: bool,
+) where
+    T: ArrowPrimitiveType<Native: HashValue>,
+{
+    assert_eq!(
+        hashes_buffer.len(),
+        array.len(),
+        "hashes_buffer and array should be of equal length"
+    );
+
+    if array.null_count() == 0 {
+        if rehash {
+            for &row in indices {
+                let value = unsafe { array.value_unchecked(row) };
+                let mut hasher =
+                    random_state.seeded_state(hashes_buffer[row]).build_hasher();
+                value.hash_write(&mut hasher);
+                hashes_buffer[row] = hasher.finish();
+            }
+        } else {
+            for &row in indices {
+                let value = unsafe { array.value_unchecked(row) };
+                hashes_buffer[row] = value.hash_one(random_state);
+            }
+        }
+    } else if rehash {
+        for &row in indices {
+            if array.is_valid(row) {
+                let value = unsafe { array.value_unchecked(row) };
+                let mut hasher =
+                    random_state.seeded_state(hashes_buffer[row]).build_hasher();
+                value.hash_write(&mut hasher);
+                hashes_buffer[row] = hasher.finish();
+            }
+        }
+    } else {
+        for &row in indices {
+            if array.is_valid(row) {
+                let value = unsafe { array.value_unchecked(row) };
+                hashes_buffer[row] = value.hash_one(random_state);
+            }
+        }
+    }
+}
+
 /// Hashes one array into the `hashes_buffer`
 /// If `rehash==true` this combines the previous hash value in the buffer
 /// with the new hash using `combine_hashes`
@@ -344,6 +395,54 @@ fn hash_array<T>(
     }
 }
 
+#[cfg(not(feature = "force_hash_collisions"))]
+fn hash_array_indices<T>(
+    array: &T,
+    random_state: &impl HashState,
+    indices: &[usize],
+    hashes_buffer: &mut [u64],
+    rehash: bool,
+) where
+    T: ArrayAccessor,
+    T::Item: HashValue,
+{
+    assert_eq!(
+        hashes_buffer.len(),
+        array.len(),
+        "hashes_buffer and array should be of equal length"
+    );
+
+    if array.null_count() == 0 {
+        if rehash {
+            for &row in indices {
+                let value = unsafe { array.value_unchecked(row) };
+                hashes_buffer[row] =
+                    combine_hashes(value.hash_one(random_state), hashes_buffer[row]);
+            }
+        } else {
+            for &row in indices {
+                let value = unsafe { array.value_unchecked(row) };
+                hashes_buffer[row] = value.hash_one(random_state);
+            }
+        }
+    } else if rehash {
+        for &row in indices {
+            if array.is_valid(row) {
+                let value = unsafe { array.value_unchecked(row) };
+                hashes_buffer[row] =
+                    combine_hashes(value.hash_one(random_state), hashes_buffer[row]);
+            }
+        }
+    } else {
+        for &row in indices {
+            if array.is_valid(row) {
+                let value = unsafe { array.value_unchecked(row) };
+                hashes_buffer[row] = value.hash_one(random_state);
+            }
+        }
+    }
+}
+
 /// Hash a StringView or BytesView array
 ///
 /// Templated to optimize inner loop based on presence of nulls and external buffers.
@@ -472,6 +571,62 @@ fn hash_generic_byte_view_array<T: ByteViewType>(
     }
 }
 
+#[cfg(not(feature = "force_hash_collisions"))]
+fn hash_generic_byte_view_array_indices<T: ByteViewType>(
+    array: &GenericByteViewArray<T>,
+    random_state: &impl HashState,
+    indices: &[usize],
+    hashes_buffer: &mut [u64],
+    rehash: bool,
+) {
+    assert_eq!(
+        hashes_buffer.len(),
+        array.len(),
+        "hashes_buffer and array should be of equal length"
+    );
+
+    let buffers = array.data_buffers();
+    let view_bytes = |view_len: u32, view: u128| {
+        let view = ByteView::from(view);
+        let offset = view.offset as usize;
+        unsafe {
+            let data = buffers.get_unchecked(view.buffer_index as usize);
+            data.get_unchecked(offset..offset + view_len as usize)
+        }
+    };
+
+    let has_nulls = array.null_count() != 0;
+    let has_buffers = !array.data_buffers().is_empty();
+    for &row in indices {
+        if has_nulls && array.is_null(row) {
+            continue;
+        }
+
+        let view = array.views()[row];
+        let view_len = view as u32;
+        if !has_buffers || view_len <= 12 {
+            if rehash {
+                let mut hasher =
+                    random_state.seeded_state(hashes_buffer[row]).build_hasher();
+                view.hash_write(&mut hasher);
+                hashes_buffer[row] = hasher.finish();
+            } else {
+                hashes_buffer[row] = view.hash_one(random_state);
+            }
+            continue;
+        }
+
+        let value = view_bytes(view_len, view);
+        if rehash {
+            let mut hasher = random_state.seeded_state(hashes_buffer[row]).build_hasher();
+            value.hash_write(&mut hasher);
+            hashes_buffer[row] = hasher.finish();
+        } else {
+            hashes_buffer[row] = value.hash_one(random_state);
+        }
+    }
+}
+
 /// Hash dictionary array with compile-time specialization for null handling.
 ///
 /// Uses const generics to eliminate runtim branching in the hot loop:
@@ -1086,6 +1241,76 @@ fn hash_single_array(
     Ok(())
 }
 
+#[cfg(not(feature = "force_hash_collisions"))]
+fn hash_null_indices<S: HashState>(
+    random_state: &S,
+    indices: &[usize],
+    hashes_buffer: &mut [u64],
+    rehash: bool,
+) {
+    if rehash {
+        for &row in indices {
+            hashes_buffer[row] =
+                combine_hashes(random_state.hash_one(1), hashes_buffer[row]);
+        }
+    } else {
+        for &row in indices {
+            hashes_buffer[row] = random_state.hash_one(1);
+        }
+    }
+}
+
+#[cfg(not(feature = "force_hash_collisions"))]
+fn hash_single_array_indices_fallback(
+    array: &dyn Array,
+    random_state: &impl HashState,
+    indices: &[usize],
+    hashes_buffer: &mut [u64],
+    rehash: bool,
+) -> Result<()> {
+    let take_indices =
+        UInt64Array::from_iter_values(indices.iter().map(|&idx| idx as u64));
+    let array = take(array, &take_indices, None)?;
+    let mut selected_hashes = if rehash {
+        indices.iter().map(|&idx| hashes_buffer[idx]).collect()
+    } else {
+        vec![0; indices.len()]
+    };
+
+    hash_single_array(array.as_ref(), random_state, &mut selected_hashes, rehash)?;
+    for (&row, hash) in indices.iter().zip(selected_hashes) {
+        hashes_buffer[row] = hash;
+    }
+    Ok(())
+}
+
+#[cfg(not(feature = "force_hash_collisions"))]
+fn hash_single_array_indices(
+    array: &dyn Array,
+    random_state: &impl HashState,
+    indices: &[usize],
+    hashes_buffer: &mut [u64],
+    rehash: bool,
+) -> Result<()> {
+    downcast_primitive_array! {
+        array => hash_array_primitive_indices(array, random_state, indices, hashes_buffer, rehash),
+        DataType::Null => hash_null_indices(random_state, indices, hashes_buffer, rehash),
+        DataType::Boolean => hash_array_indices(&as_boolean_array(array)?, random_state, indices, hashes_buffer, rehash),
+        DataType::Utf8 => hash_array_indices(&as_string_array(array)?, random_state, indices, hashes_buffer, rehash),
+        DataType::Utf8View => hash_generic_byte_view_array_indices(as_string_view_array(array)?, random_state, indices, hashes_buffer, rehash),
+        DataType::LargeUtf8 => hash_array_indices(&as_largestring_array(array), random_state, indices, hashes_buffer, rehash),
+        DataType::Binary => hash_array_indices(&as_generic_binary_array::<i32>(array)?, random_state, indices, hashes_buffer, rehash),
+        DataType::BinaryView => hash_generic_byte_view_array_indices(as_binary_view_array(array)?, random_state, indices, hashes_buffer, rehash),
+        DataType::LargeBinary => hash_array_indices(&as_generic_binary_array::<i64>(array)?, random_state, indices, hashes_buffer, rehash),
+        DataType::FixedSizeBinary(_) => {
+            let array: &FixedSizeBinaryArray = array.as_any().downcast_ref().unwrap();
+            hash_array_indices(&array, random_state, indices, hashes_buffer, rehash)
+        }
+        _ => hash_single_array_indices_fallback(array, random_state, indices, hashes_buffer, rehash)?,
+    }
+    Ok(())
+}
+
 /// Test version of `hash_single_array` that forces all hashes to collide to zero.
 #[cfg(feature = "force_hash_collisions")]
 fn hash_single_array(
@@ -1100,6 +1325,20 @@ fn hash_single_array(
     Ok(())
 }
 
+#[cfg(feature = "force_hash_collisions")]
+fn hash_single_array_indices(
+    _array: &dyn Array,
+    _random_state: &impl HashState,
+    indices: &[usize],
+    hashes_buffer: &mut [u64],
+    _rehash: bool,
+) -> Result<()> {
+    for &row in indices {
+        hashes_buffer[row] = 0;
+    }
+    Ok(())
+}
+
 /// Something that can be returned as a `&dyn Array`.
 ///
 /// We want `create_hashes` to accept either `&dyn Array` or `ArrayRef`,
@@ -1158,6 +1397,38 @@ where
     Ok(hashes_buffer)
 }
 
+/// Creates hash values for selected rows, based on the values in the columns.
+///
+/// `hashes_buffer` must have the same length as the input arrays. Only rows in
+/// `indices` are updated. Values outside `indices` are left unchanged.
+pub fn create_hashes_indices<'a, I, T>(
+    arrays: I,
+    random_state: &impl HashState,
+    indices: &[usize],
+    hashes_buffer: &'a mut [u64],
+) -> Result<&'a mut [u64]>
+where
+    I: IntoIterator<Item = T>,
+    T: AsDynArray,
+{
+    for (col_idx, array) in arrays.into_iter().enumerate() {
+        let array = array.as_dyn_array();
+        assert_eq!(
+            hashes_buffer.len(),
+            array.len(),
+            "hashes_buffer and array should be of equal length"
+        );
+        let rehash = col_idx >= 1;
+        if !rehash {
+            for &row in indices {
+                hashes_buffer[row] = 0;
+            }
+        }
+        hash_single_array_indices(array, random_state, indices, hashes_buffer, rehash)?;
+    }
+    Ok(hashes_buffer)
+}
+
 #[cfg(test)]
 mod tests {
     use std::sync::Arc;
@@ -1216,6 +1487,31 @@ mod tests {
         Ok(())
     }
 
+    #[test]
+    fn create_hashes_indices_updates_only_selected_rows() -> Result<()> {
+        let int_array: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4]));
+        let string_array: ArrayRef = Arc::new(StringViewArray::from(vec![
+            Some("a"),
+            None,
+            Some("c"),
+            Some("d"),
+        ]));
+        let arrays = [int_array, string_array];
+        let random_state = RandomState::with_seed(0);
+
+        let mut full_hashes = vec![0; arrays[0].len()];
+        create_hashes(&arrays, &random_state, &mut full_hashes)?;
+
+        let mut selected_hashes = vec![u64::MAX; arrays[0].len()];
+        create_hashes_indices(&arrays, &random_state, &[1, 3], &mut selected_hashes)?;
+
+        assert_eq!(selected_hashes[0], u64::MAX);
+        assert_eq!(selected_hashes[1], full_hashes[1]);
+        assert_eq!(selected_hashes[2], u64::MAX);
+        assert_eq!(selected_hashes[3], full_hashes[3]);
+        Ok(())
+    }
+
     macro_rules! create_hash_binary {
         ($NAME:ident, $ARRAY:ty) => {
             #[cfg(not(feature = "force_hash_collisions"))]
diff --git a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/final_table.rs b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/final_table.rs
index 7dceb37aa3..a3a3f7530f 100644
--- a/datafusion/physical-plan/src/aggregates/aggregate_hash_table/final_table.rs
+++ b/datafusion/physical-plan/src/aggregates/aggregate_hash_table/final_table.rs
@@ -152,10 +152,12 @@ impl AggregateHashTable<FinalMarker> {
         Ok(())
     }
 
-    pub(in crate::aggregates) fn create_group_hashes(
+    pub(in crate::aggregates) fn create_group_hashes_indices(
         &self,
         evaluated_batch: &EvaluatedAggregateBatch,
-    ) -> Result<Vec<u64>> {
+        partition_indices: &[usize],
+        hashes: &mut Vec<u64>,
+    ) -> Result<()> {
         assert_eq_or_internal_err!(
             evaluated_batch.grouping_set_args.len(),
             1,
@@ -164,13 +166,14 @@ impl AggregateHashTable<FinalMarker> {
 
         let state = self.state.building();
         let group_values = &evaluated_batch.grouping_set_args[0];
-        let mut hashes = Vec::new();
         let timer = self.group_by_metrics.time_calculating_group_ids.timer();
-        state
-            .group_values
-            .create_hashes(group_values, &mut hashes)?;
+        state.group_values.create_hashes_indices(
+            group_values,
+            partition_indices,
+            hashes,
+        )?;
         drop(timer);
-        Ok(hashes)
+        Ok(())
     }
 
     pub(in crate::aggregates) fn aggregate_partitioned_evaluated_batch(
diff --git a/datafusion/physical-plan/src/aggregates/group_values/mod.rs b/datafusion/physical-plan/src/aggregates/group_values/mod.rs
index edf7d2eef2..6c9bd663c7 100644
--- a/datafusion/physical-plan/src/aggregates/group_values/mod.rs
+++ b/datafusion/physical-plan/src/aggregates/group_values/mod.rs
@@ -24,7 +24,7 @@ use arrow::array::types::{
 };
 use arrow::array::{ArrayRef, downcast_primitive};
 use arrow::datatypes::{DataType, SchemaRef, TimeUnit};
-use datafusion_common::hash_utils::create_hashes;
+use datafusion_common::hash_utils::{create_hashes, create_hashes_indices};
 use datafusion_common::{Result, internal_err};
 
 use datafusion_expr::EmitTo;
@@ -121,6 +121,25 @@ pub trait GroupValues: Send {
         Ok(())
     }
 
+    /// Computes hash values for selected group value rows before partitioned intern.
+    fn create_hashes_indices(
+        &self,
+        cols: &[ArrayRef],
+        indices: &[usize],
+        hashes: &mut Vec<u64>,
+    ) -> Result<()> {
+        if hashes.len() != cols[0].len() {
+            hashes.resize(cols[0].len(), 0);
+        }
+        create_hashes_indices(
+            cols,
+            &crate::aggregates::AGGREGATION_HASH_SEED,
+            indices,
+            hashes,
+        )?;
+        Ok(())
+    }
+
     /// Returns true if [`Self::intern_partitioned`] is supported.
     fn supports_intern_partitioned(&self) -> bool {
         false
diff --git a/datafusion/physical-plan/src/aggregates/hash_aggregate.rs b/datafusion/physical-plan/src/aggregates/hash_aggregate.rs
index e331eb82f7..e286d4828e 100644
--- a/datafusion/physical-plan/src/aggregates/hash_aggregate.rs
+++ b/datafusion/physical-plan/src/aggregates/hash_aggregate.rs
@@ -26,7 +26,6 @@
 //! See issue for details: <https://github.com/apache/datafusion/issues/22710>
 
 use std::collections::{BTreeMap, BTreeSet};
-use std::mem::size_of;
 use std::ops::ControlFlow;
 use std::sync::Arc;
 use std::task::{Context, Poll};
@@ -56,27 +55,18 @@ use crate::{InputOrderMode, RecordBatchStream, SendableRecordBatchStream, metric
 struct BufferedFinalPartitionBatch {
     batch: RecordBatch,
     evaluated_batch: EvaluatedAggregateBatch,
-    group_hashes: Vec<u64>,
 }
 
 impl BufferedFinalPartitionBatch {
-    fn new(
-        batch: RecordBatch,
-        evaluated_batch: EvaluatedAggregateBatch,
-        group_hashes: Vec<u64>,
-    ) -> Self {
+    fn new(batch: RecordBatch, evaluated_batch: EvaluatedAggregateBatch) -> Self {
         Self {
             batch,
             evaluated_batch,
-            group_hashes,
         }
     }
 
     fn memory_size(&self) -> usize {
-        let group_hashes_size = self.group_hashes.capacity() * size_of::<u64>();
-        get_record_batch_memory_size(&self.batch)
-            + self.evaluated_batch.memory_size()
-            + group_hashes_size
+        get_record_batch_memory_size(&self.batch) + self.evaluated_batch.memory_size()
     }
 }
 
@@ -86,6 +76,7 @@ struct FinalPartitionRunState {
     subpartition_column_idx: Option<usize>,
     total_runs_size: usize,
     partition_indices_buffer: Vec<usize>,
+    group_hashes_buffer: Vec<u64>,
 }
 
 impl FinalPartitionRunState {
@@ -96,6 +87,7 @@ impl FinalPartitionRunState {
             subpartition_column_idx: None,
             total_runs_size: 0,
             partition_indices_buffer: Vec::new(),
+            group_hashes_buffer: Vec::new(),
         }
     }
 
@@ -111,7 +103,6 @@ impl FinalPartitionRunState {
         &mut self,
         batch: RecordBatch,
         evaluated_batch: EvaluatedAggregateBatch,
-        group_hashes: Vec<u64>,
     ) -> Result<usize> {
         let subpartition_column_idx = match self.subpartition_column_idx {
             Some(idx) => idx,
@@ -146,8 +137,7 @@ impl FinalPartitionRunState {
             }
         }
 
-        let buffered_batch =
-            BufferedFinalPartitionBatch::new(batch, evaluated_batch, group_hashes);
+        let buffered_batch = BufferedFinalPartitionBatch::new(batch, evaluated_batch);
         let batch_size = buffered_batch.memory_size();
         self.total_runs_size += batch_size;
         self.batches.push(buffered_batch);
@@ -203,6 +193,14 @@ impl FinalPartitionRunState {
         partition_indices.clear();
         self.partition_indices_buffer = partition_indices;
     }
+
+    fn take_group_hashes_buffer(&mut self) -> Vec<u64> {
+        std::mem::take(&mut self.group_hashes_buffer)
+    }
+
+    fn return_group_hashes_buffer(&mut self, group_hashes: Vec<u64>) {
+        self.group_hashes_buffer = group_hashes;
+    }
 }
 
 /// Hash aggregation is implemented in two stages: partial and final. This
@@ -982,11 +980,10 @@ impl FinalHashAggregateStream {
         }
 
         let evaluated_batch = hash_table.evaluate_batch(batch)?;
-        let group_hashes = hash_table.create_group_hashes(&evaluated_batch)?;
 
         self.partition_run_state
             .as_mut()
-            .map(|state| state.stage_batch(batch.clone(), evaluated_batch, group_hashes))
+            .map(|state| state.stage_batch(batch.clone(), evaluated_batch))
             .transpose()
     }
 
@@ -1052,21 +1049,39 @@ impl FinalHashAggregateStream {
             };
 
             debug_assert!(!partition_indices.is_empty());
-            let buffered_batch = {
+            let mut group_hashes = self
+                .partition_run_state
+                .as_mut()
+                .ok_or_else(|| {
+                    DataFusionError::Internal(
+                        "missing partition run state while building final aggregate hashes"
+                            .to_string(),
+                    )
+                })?
+                .take_group_hashes_buffer();
+
+            {
                 let state = self.partition_run_state.as_ref().ok_or_else(|| {
                     DataFusionError::Internal(
                         "missing partition run state while replaying final aggregate runs"
                             .to_string(),
                     )
                 })?;
-                &state.batches[batch_idx]
-            };
-            hash_table.aggregate_partitioned_evaluated_batch(
-                &buffered_batch.evaluated_batch,
-                &buffered_batch.group_hashes,
-                &partition_indices,
-            )?;
+                let buffered_batch = &state.batches[batch_idx];
+                hash_table.create_group_hashes_indices(
+                    &buffered_batch.evaluated_batch,
+                    &partition_indices,
+                    &mut group_hashes,
+                )?;
+                hash_table.aggregate_partitioned_evaluated_batch(
+                    &buffered_batch.evaluated_batch,
+                    &group_hashes,
+                    &partition_indices,
+                )?;
+            }
+
             if let Some(state) = self.partition_run_state.as_mut() {
+                state.return_group_hashes_buffer(group_hashes);
                 state.return_partition_indices(partition_indices);
             }
         }


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org