alamb commented on code in PR #23646:
URL: https://github.com/apache/datafusion/pull/23646#discussion_r3752605833


##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/fixed_size_binary.rs:
##########
@@ -0,0 +1,515 @@
+// 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.
+
+use crate::aggregates::group_values::multi_group_by::{
+    GroupColumn, Nulls, nulls_equal_to,
+};
+use crate::aggregates::group_values::null_builder::MaybeNullBufferBuilder;
+use arrow::array::{
+    Array, ArrayRef, AsArray, BooleanBufferBuilder, FixedSizeBinaryArray,
+};
+use arrow::buffer::{Buffer, NullBuffer};
+use datafusion_common::utils::proxy::VecAllocExt;
+use datafusion_common::utils::split_vec_min_alloc;
+use datafusion_common::{Result, exec_datafusion_err};
+use std::sync::Arc;
+
+/// An implementation of [`GroupColumn`] for `FixedSizeBinary` values
+///
+/// Stores the group values in a single flat buffer, `byte_width` bytes per
+/// value, in a way that allows:
+///
+/// 1. Efficient comparison of incoming rows to existing rows
+/// 2. Efficient construction of the final output array (the buffer is handed
+///    to [`FixedSizeBinaryArray`] as-is, no offsets needed)
+///
+/// Null values occupy `byte_width` zeroed bytes in the buffer so that the
+/// value of row `i` is always stored at `i * byte_width..(i + 1) * 
byte_width`.
+pub struct FixedSizeBinaryGroupValueBuilder {
+    /// The width in bytes of each value, from `DataType::FixedSizeBinary`
+    byte_width: usize,
+    /// The flattened group values, `byte_width` bytes per value
+    buffer: Vec<u8>,
+    /// The number of group values stored
+    ///
+    /// Tracked explicitly rather than derived from `buffer.len()` because
+    /// `byte_width` may be `0`
+    len: usize,
+    /// Null state (null rows still occupy `byte_width` bytes in `buffer`)
+    nulls: MaybeNullBufferBuilder,
+}
+
+impl FixedSizeBinaryGroupValueBuilder {
+    /// Create a new builder for values of `byte_width` bytes each
+    ///
+    /// `byte_width` is the width carried by `DataType::FixedSizeBinary` and
+    /// must be non-negative (negative widths are rejected by the dispatch in
+    /// `make_group_column`)
+    pub fn new(byte_width: i32) -> Self {
+        debug_assert!(byte_width >= 0);
+        Self {
+            byte_width: byte_width as usize,
+            buffer: Vec::new(),
+            len: 0,
+            nulls: MaybeNullBufferBuilder::new(),
+        }
+    }
+
+    fn do_append_val_inner(&mut self, array: &FixedSizeBinaryArray, row: 
usize) {
+        if array.is_null(row) {
+            self.nulls.append(true);
+            // Null rows still occupy `byte_width` (zeroed) bytes in the
+            // buffer so the value offset stays a function of the row index
+            self.buffer.resize(self.buffer.len() + self.byte_width, 0);
+        } else {
+            self.nulls.append(false);
+            self.buffer.extend_from_slice(array.value(row));
+        }
+        self.len += 1;
+    }
+
+    fn do_equal_to_inner(
+        &self,
+        lhs_row: usize,
+        array: &FixedSizeBinaryArray,
+        rhs_row: usize,
+    ) -> bool {
+        let exist_null = self.nulls.is_null(lhs_row);
+        let input_null = array.is_null(rhs_row);
+        if let Some(result) = nulls_equal_to(exist_null, input_null) {
+            return result;
+        }
+        // Otherwise, we need to check their values
+        self.value(lhs_row) == array.value(rhs_row)
+    }
+
+    /// return the current value of the specified row irrespective of null
+    /// (null rows store `byte_width` zeroed bytes)
+    pub fn value(&self, row: usize) -> &[u8] {
+        let start = row * self.byte_width;
+        &self.buffer[start..start + self.byte_width]
+    }
+
+    /// Assemble an output array from `values` + `nulls` parts
+    ///
+    /// Uses `try_new_with_len` rather than `try_new` because the length
+    /// cannot be derived from the values buffer when `byte_width == 0`
+    fn build_array(
+        byte_width: usize,
+        values: Vec<u8>,
+        nulls: Option<NullBuffer>,
+        len: usize,
+    ) -> ArrayRef {
+        let array = FixedSizeBinaryArray::try_new_with_len(
+            byte_width as i32,
+            Buffer::from(values),
+            nulls,
+            len,
+        )
+        .expect("buffer, nulls and len kept consistent on append");
+        Arc::new(array)
+    }
+}
+
+impl GroupColumn for FixedSizeBinaryGroupValueBuilder {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool {
+        self.do_equal_to_inner(lhs_row, array.as_fixed_size_binary(), rhs_row)
+    }
+
+    fn append_val(&mut self, array: &ArrayRef, row: usize) -> Result<()> {
+        let arr = array.as_fixed_size_binary();
+        debug_assert_eq!(arr.value_size(), self.byte_width);
+        self.do_append_val_inner(arr, row);
+        Ok(())
+    }
+
+    fn vectorized_equal_to(
+        &self,
+        lhs_rows: &[usize],
+        array: &ArrayRef,
+        rhs_rows: &[usize],
+        equal_to_results: &mut BooleanBufferBuilder,
+    ) {
+        let array = array.as_fixed_size_binary();
+
+        for (idx, (&lhs_row, &rhs_row)) in

Review Comment:
   As a follow on, this can likely be optimized more -- for example, we could 
have a special case loop for when the inputs are known to have no nulls (likely 
a common case for things like UUIDs)
   
   We could also move to using get_unchecked to skip the bounds check and try 
to make this lookup loop even more performant
   
   



##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/fixed_size_binary.rs:
##########
@@ -0,0 +1,515 @@
+// 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.
+
+use crate::aggregates::group_values::multi_group_by::{
+    GroupColumn, Nulls, nulls_equal_to,
+};
+use crate::aggregates::group_values::null_builder::MaybeNullBufferBuilder;
+use arrow::array::{
+    Array, ArrayRef, AsArray, BooleanBufferBuilder, FixedSizeBinaryArray,
+};
+use arrow::buffer::{Buffer, NullBuffer};
+use datafusion_common::utils::proxy::VecAllocExt;
+use datafusion_common::utils::split_vec_min_alloc;
+use datafusion_common::{Result, exec_datafusion_err};
+use std::sync::Arc;
+
+/// An implementation of [`GroupColumn`] for `FixedSizeBinary` values
+///
+/// Stores the group values in a single flat buffer, `byte_width` bytes per
+/// value, in a way that allows:
+///
+/// 1. Efficient comparison of incoming rows to existing rows
+/// 2. Efficient construction of the final output array (the buffer is handed
+///    to [`FixedSizeBinaryArray`] as-is, no offsets needed)
+///
+/// Null values occupy `byte_width` zeroed bytes in the buffer so that the
+/// value of row `i` is always stored at `i * byte_width..(i + 1) * 
byte_width`.
+pub struct FixedSizeBinaryGroupValueBuilder {
+    /// The width in bytes of each value, from `DataType::FixedSizeBinary`
+    byte_width: usize,
+    /// The flattened group values, `byte_width` bytes per value
+    buffer: Vec<u8>,
+    /// The number of group values stored
+    ///
+    /// Tracked explicitly rather than derived from `buffer.len()` because
+    /// `byte_width` may be `0`
+    len: usize,
+    /// Null state (null rows still occupy `byte_width` bytes in `buffer`)
+    nulls: MaybeNullBufferBuilder,
+}
+
+impl FixedSizeBinaryGroupValueBuilder {
+    /// Create a new builder for values of `byte_width` bytes each
+    ///
+    /// `byte_width` is the width carried by `DataType::FixedSizeBinary` and
+    /// must be non-negative (negative widths are rejected by the dispatch in
+    /// `make_group_column`)
+    pub fn new(byte_width: i32) -> Self {
+        debug_assert!(byte_width >= 0);
+        Self {
+            byte_width: byte_width as usize,
+            buffer: Vec::new(),
+            len: 0,
+            nulls: MaybeNullBufferBuilder::new(),
+        }
+    }
+
+    fn do_append_val_inner(&mut self, array: &FixedSizeBinaryArray, row: 
usize) {
+        if array.is_null(row) {
+            self.nulls.append(true);
+            // Null rows still occupy `byte_width` (zeroed) bytes in the
+            // buffer so the value offset stays a function of the row index
+            self.buffer.resize(self.buffer.len() + self.byte_width, 0);
+        } else {
+            self.nulls.append(false);
+            self.buffer.extend_from_slice(array.value(row));
+        }
+        self.len += 1;
+    }
+
+    fn do_equal_to_inner(
+        &self,
+        lhs_row: usize,
+        array: &FixedSizeBinaryArray,
+        rhs_row: usize,
+    ) -> bool {
+        let exist_null = self.nulls.is_null(lhs_row);
+        let input_null = array.is_null(rhs_row);
+        if let Some(result) = nulls_equal_to(exist_null, input_null) {
+            return result;
+        }
+        // Otherwise, we need to check their values
+        self.value(lhs_row) == array.value(rhs_row)
+    }
+
+    /// return the current value of the specified row irrespective of null
+    /// (null rows store `byte_width` zeroed bytes)
+    pub fn value(&self, row: usize) -> &[u8] {
+        let start = row * self.byte_width;
+        &self.buffer[start..start + self.byte_width]
+    }
+
+    /// Assemble an output array from `values` + `nulls` parts
+    ///
+    /// Uses `try_new_with_len` rather than `try_new` because the length
+    /// cannot be derived from the values buffer when `byte_width == 0`
+    fn build_array(
+        byte_width: usize,
+        values: Vec<u8>,
+        nulls: Option<NullBuffer>,
+        len: usize,
+    ) -> ArrayRef {
+        let array = FixedSizeBinaryArray::try_new_with_len(
+            byte_width as i32,
+            Buffer::from(values),
+            nulls,
+            len,
+        )
+        .expect("buffer, nulls and len kept consistent on append");
+        Arc::new(array)
+    }
+}
+
+impl GroupColumn for FixedSizeBinaryGroupValueBuilder {
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool {
+        self.do_equal_to_inner(lhs_row, array.as_fixed_size_binary(), rhs_row)
+    }
+
+    fn append_val(&mut self, array: &ArrayRef, row: usize) -> Result<()> {
+        let arr = array.as_fixed_size_binary();
+        debug_assert_eq!(arr.value_size(), self.byte_width);
+        self.do_append_val_inner(arr, row);
+        Ok(())
+    }
+
+    fn vectorized_equal_to(
+        &self,
+        lhs_rows: &[usize],
+        array: &ArrayRef,
+        rhs_rows: &[usize],
+        equal_to_results: &mut BooleanBufferBuilder,
+    ) {
+        let array = array.as_fixed_size_binary();
+
+        for (idx, (&lhs_row, &rhs_row)) in
+            lhs_rows.iter().zip(rhs_rows.iter()).enumerate()
+        {
+            // Has found not equal to in previous column, don't need to check
+            if !equal_to_results.get_bit(idx) {
+                continue;
+            }
+
+            if !self.do_equal_to_inner(lhs_row, array, rhs_row) {
+                equal_to_results.set_bit(idx, false);
+            }
+        }
+    }
+
+    fn vectorized_append(&mut self, array: &ArrayRef, rows: &[usize]) -> 
Result<()> {
+        let arr = array.as_fixed_size_binary();
+        debug_assert_eq!(arr.value_size(), self.byte_width);
+
+        let reserve_bytes = rows.len() * self.byte_width;
+        self.buffer.try_reserve(reserve_bytes).map_err(|e| {
+            exec_datafusion_err!("failed to reserve {reserve_bytes} bytes: 
{e}")
+        })?;
+
+        let null_count = array.null_count();
+        let num_rows = array.len();
+        let all_null_or_non_null = if null_count == 0 {
+            Nulls::None
+        } else if null_count == num_rows {
+            Nulls::All
+        } else {
+            Nulls::Some
+        };
+
+        match all_null_or_non_null {

Review Comment:
   this is nice



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

To unsubscribe, e-mail: [email protected]

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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to