Rich-T-kid commented on code in PR #23128:
URL: https://github.com/apache/datafusion/pull/23128#discussion_r3523878572


##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/fixed_size_list.rs:
##########
@@ -0,0 +1,695 @@
+// 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.
+
+//! [`GroupColumn`] implementation for `FixedSizeList<primitive>`.
+//!
+//! Storage: outer null bitmap + a child [`PrimitiveGroupValueBuilder`] that
+//! holds every element flat (length = outer_len * list_len). The j-th element
+//! of the i-th outer row lives at child index `i * list_len + j`.
+
+use crate::aggregates::group_values::HashValue;
+use 
crate::aggregates::group_values::multi_group_by::primitive::PrimitiveGroupValueBuilder;
+use crate::aggregates::group_values::multi_group_by::{GroupColumn, 
nulls_equal_to};
+use crate::aggregates::group_values::null_builder::MaybeNullBufferBuilder;
+
+use arrow::array::{
+    Array, ArrayRef, ArrowPrimitiveType, BooleanBufferBuilder, 
FixedSizeListArray,
+};
+use arrow::datatypes::{DataType, FieldRef};
+use datafusion_common::Result;
+use std::sync::Arc;
+
+/// A [`GroupColumn`] for `FixedSizeList<T>` where `T` is a primitive type.
+pub struct FixedSizeListGroupValueBuilder<T: ArrowPrimitiveType> {
+    /// Child field, cached for `build` / `take_n`.
+    field: FieldRef,
+    /// List length per outer row.
+    list_len: i32,
+    /// Outer-level null bitmap.
+    outer_nulls: MaybeNullBufferBuilder,
+    /// Number of outer rows accumulated.
+    outer_len: usize,
+    /// Flat storage for child elements; always treated as nullable so it can
+    /// hold child nulls regardless of the outer row's nullability.
+    child: PrimitiveGroupValueBuilder<T, true>,
+}
+
+impl<T> FixedSizeListGroupValueBuilder<T>
+where
+    T: ArrowPrimitiveType,
+    T::Native: HashValue,
+{
+    pub fn new(data_type: &DataType) -> Self {
+        let (field, list_len) = match data_type {
+            DataType::FixedSizeList(f, n) => (Arc::clone(f), *n),
+            other => unreachable!(
+                "FixedSizeListGroupValueBuilder built with non-FixedSizeList 
type {other:?}"
+            ),
+        };
+        // `group_column_supported_type` and `make_group_column` both reject
+        // negative `list_len` upstream so this branch should be unreachable
+        // for any schema that survives the allow-list. Assert defensively
+        // to fail fast (and with a clear message) if a direct caller ever
+        // bypasses the factory with an invalid Arrow type.
+        assert!(
+            list_len >= 0,
+            "FixedSizeListGroupValueBuilder requires non-negative list size, 
got {list_len}"
+        );
+        let child = PrimitiveGroupValueBuilder::<T, 
true>::new(field.data_type().clone());
+        Self {
+            field,
+            list_len,
+            outer_nulls: MaybeNullBufferBuilder::new(),
+            outer_len: 0,
+            child,
+        }
+    }
+
+    /// Lossless widening to `usize`. The constructor asserts
+    /// `list_len >= 0`, so the conversion is well-defined. We still go
+    /// through `try_from` rather than `as usize` so any future
+    /// invariant break surfaces as a panic with a clear message rather
+    /// than a silent wrap.
+    fn list_len_usize(&self) -> usize {
+        usize::try_from(self.list_len)
+            .expect("list_len validated >= 0 in `new`; conversion to usize 
cannot fail")
+    }
+}
+
+impl<T> GroupColumn for FixedSizeListGroupValueBuilder<T>
+where
+    T: ArrowPrimitiveType,
+    T::Native: HashValue,
+{
+    fn equal_to(&self, lhs_row: usize, array: &ArrayRef, rhs_row: usize) -> 
bool {
+        let lhs_null = self.outer_nulls.is_null(lhs_row);
+        let rhs_null = array.is_null(rhs_row);
+        if let Some(result) = nulls_equal_to(lhs_null, rhs_null) {
+            return result;
+        }
+
+        let list_array = array
+            .as_any()
+            .downcast_ref::<FixedSizeListArray>()
+            .expect("FixedSizeListGroupValueBuilder called with 
non-FixedSizeList array");
+        // Use the borrowed child array + `value_offset` (same approach as
+        // `append_val` below) instead of `list_array.value(rhs_row)`,
+        // which would allocate a fresh sliced `ArrayRef` on every
+        // equality check inside grouping's hot path.
+        let child_array = list_array.values();
+        let list_len = self.list_len_usize();
+        let lhs_base = lhs_row * list_len;
+        let rhs_base = list_array.value_offset(rhs_row) as usize;
+        for j in 0..list_len {
+            if !self.child.equal_to(lhs_base + j, child_array, rhs_base + j) {
+                return false;
+            }
+        }
+        true
+    }
+
+    fn append_val(&mut self, array: &ArrayRef, row: usize) -> Result<()> {
+        let list_array = array
+            .as_any()
+            .downcast_ref::<FixedSizeListArray>()
+            .expect("FixedSizeListGroupValueBuilder called with 
non-FixedSizeList array");
+        self.outer_nulls.append(list_array.is_null(row));
+        self.outer_len += 1;
+        let child_array = list_array.values();
+        let list_len = self.list_len_usize();
+        // Use the array's own `value_offset` rather than computing `(offset
+        // + row) * list_len` ourselves. For sliced FixedSizeListArrays the
+        // `values()` slice is already advanced, so doing the arithmetic
+        // manually risks double-applying any future offset behavior.
+        let start = list_array.value_offset(row) as usize;
+        for j in 0..list_len {
+            self.child.append_val(child_array, start + j)?;
+        }
+        Ok(())
+    }
+
+    fn vectorized_equal_to(
+        &self,
+        lhs_rows: &[usize],
+        array: &ArrayRef,
+        rhs_rows: &[usize],
+        equal_to_results: &mut BooleanBufferBuilder,
+    ) {
+        for (idx, (&lhs_row, &rhs_row)) in
+            lhs_rows.iter().zip(rhs_rows.iter()).enumerate()
+        {
+            if !equal_to_results.get_bit(idx) {
+                continue;
+            }
+            if !self.equal_to(lhs_row, array, rhs_row) {
+                equal_to_results.set_bit(idx, false);
+            }
+        }
+    }
+
+    fn vectorized_append(&mut self, array: &ArrayRef, rows: &[usize]) -> 
Result<()> {
+        for &row in rows {
+            self.append_val(array, row)?;
+        }
+        Ok(())
+    }
+
+    fn len(&self) -> usize {
+        self.outer_len
+    }
+
+    fn size(&self) -> usize {
+        self.outer_nulls.allocated_size() + self.child.size()
+    }
+
+    fn build(self: Box<Self>) -> ArrayRef {
+        let Self {
+            field,
+            list_len,
+            mut outer_nulls,
+            outer_len: _,
+            child,
+        } = *self;
+        let outer_nulls = outer_nulls_take_build(&mut outer_nulls);
+        let child_array = Box::new(child).build();
+        Arc::new(FixedSizeListArray::new(
+            field,
+            list_len,
+            child_array,
+            outer_nulls,
+        ))
+    }
+
+    fn take_n(&mut self, n: usize) -> ArrayRef {

Review Comment:
   nvm on this. Since `build` takes a boxed reference to the trait this 
wouldn't work since take_n takes a mutable reference. This would need to be 
done in `GroupValuesColumn::Emit()`



-- 
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