You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "zhuqi-lucas (via GitHub)" <gi...@apache.org> on 2026/06/02 05:49:59 UTC
[PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
zhuqi-lucas opened a new pull request, #22706:
URL: https://github.com/apache/datafusion/pull/22706
## Which issue does this PR close?
Closes #22682.
## Rationale for this change
Today `multi_group_by::supported_schema` is all-or-nothing: if any single GROUP BY column is not in the `supported_type` allow-list, the whole grouping falls back to the byte-encoded `GroupValuesRows` path, even when every other column would have qualified for the fast column-wise + cross-column short-circuit path. The most common offender in real workloads is a single nested column (e.g. `LargeList<Struct<Utf8, LargeUtf8>>`) that drags an otherwise primitive-heavy 30+ column GROUP BY onto the slow path.
This PR adds column-native `GroupColumn` implementations for `FixedSizeList<primitive>`, `Struct<...>`, `List<T>`, and `LargeList<T>`, so a GROUP BY containing any of these no longer falls back from `GroupValuesColumn` to `GroupValuesRows`.
## What changes are included in this PR?
- `FixedSizeListGroupValueBuilder<T>` for `FixedSizeList<primitive>`. Uses an inner `PrimitiveGroupValueBuilder` for the flat child storage.
- `StructGroupValueBuilder` for `Struct<...>` with recursive child support.
- `ListGroupValueBuilder<O: OffsetSizeTrait>` for `List<T>` (O=i32) and `LargeList<T>` (O=i64) with recursive child support. Null outer rows occupy a zero-length range so the offset buffer stays monotonic without consuming child slots.
- A recursive `make_group_column(field: &Field) -> Result<Box<dyn GroupColumn>>` factory in `multi_group_by/mod.rs` that replaces the inline match in `GroupValuesColumn::intern`. Walks nested fields and recursively builds children for `Struct` / `List` / `LargeList`.
- `supported_type` recursively checks children for `List` / `LargeList` / `Struct`. `FixedSizeList` is restricted to primitive children in this PR; composing FSL with nested children can follow in a separate PR.
## Are these changes tested?
Yes. 38 new tests, 68/68 group_values tests pass, 142/142 aggregates regression pass.
Per-builder:
- append / build round trip
- `equal_to` for outer nulls, inner nulls, identical, different (and for List: different lengths, empty)
- **sliced input array** (offset != 0) for each builder
- `take_n` boundary cases: `n=0`, `n=len`, prefix containing null rows
- `vectorized_equal_to` / `vectorized_append` match per-row reference
- `size()` grows with appends
- `build` on empty builder returns empty array
Composition:
- `Struct<Struct<Utf8, Int32>>` (two-level nested struct)
- `List<List<Int32>>` (two-level nested list)
- `LargeList<Struct<Utf8, Int32>>` end-to-end through `new_group_values`
Invariants:
- `supported_type` accepts every primitive + nested combo and rejects `Float16`, `Decimal256`, `Time64(Second)`, `List<Float16>`, `Struct{Float16}`, `FixedSizeList<Utf8>`, etc.
- A `supported_type` <-> `make_group_column` consistency fuzz over 21 supported + 9 unsupported types asserts the biconditional. Pins the invariant against future drift between the allow-list and the dispatcher.
## Are there any user-facing changes?
No public API changes. The new builders are internal to `physical-plan`. `supported_type` becomes more permissive (returns `true` for the new types), so existing GROUP BYs that were previously falling back to `GroupValuesRows` will now use `GroupValuesColumn` automatically; this is a performance improvement, not a behavior change.
## Known limitations
1. `FixedSizeList` is restricted to primitive child types. Composing FSL with `Struct` / `List` children is straightforward via the factory but not in this PR.
2. `vectorized_equal_to` / `vectorized_append` for the new builders fall back to per-row loops. They are correctness-equivalent to the specialized vectorized paths used by the primitive builders, but a follow-up can add type-specialized batched comparators where beneficial.
3. `Map<K, V>` not included; ordering semantics need a separate discussion.
Happy to split this into 4-5 smaller PRs (factory refactor, then one PR per type) if maintainers prefer reviewing the staging incrementally. The single commit is structured so the factory and the per-type builders are mutually dependent and easier to read together.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "nathanb9 (via GitHub)" <gi...@apache.org>.
nathanb9 commented on code in PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#discussion_r3346128588
##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/list.rs:
##########
@@ -0,0 +1,844 @@
+// 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 `List<T>` and `LargeList<T>` group keys.
+//!
+//! Storage:
+//! - `offsets: Vec<O>` of length `outer_len + 1`, with `offsets[0] = 0`. The
+//! children of outer row `i` live at child positions
+//! `[offsets[i] .. offsets[i+1])`.
+//! - `child: Box<dyn GroupColumn>` for the element type.
+//! - `outer_nulls`: outer-row null bitmap.
+//!
+//! Null outer rows are stored with a zero-length range (i.e.
+//! `offsets[i+1] == offsets[i]`). No child slots are pushed for null rows.
+
+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, BooleanBufferBuilder, GenericListArray, OffsetSizeTrait,
+};
+use arrow::buffer::{OffsetBuffer, ScalarBuffer};
+use arrow::datatypes::FieldRef;
+use datafusion_common::{Result, internal_datafusion_err};
+use std::mem::size_of_val;
+use std::sync::Arc;
+
+/// A [`GroupColumn`] for `List<T>` (`O = i32`) and `LargeList<T>` (`O = i64`).
+pub struct ListGroupValueBuilder<O: OffsetSizeTrait> {
+ field: FieldRef,
+ offsets: Vec<O>,
+ child: Box<dyn GroupColumn>,
+ outer_nulls: MaybeNullBufferBuilder,
+ outer_len: usize,
+}
+
+impl<O: OffsetSizeTrait> ListGroupValueBuilder<O> {
+ pub fn new(field: FieldRef, child: Box<dyn GroupColumn>) -> Self {
+ Self {
+ field,
+ offsets: vec![O::usize_as(0)],
+ child,
+ outer_nulls: MaybeNullBufferBuilder::new(),
+ outer_len: 0,
+ }
+ }
+
+ fn list_array(array: &ArrayRef) -> &GenericListArray<O> {
+ array
+ .as_any()
+ .downcast_ref::<GenericListArray<O>>()
+ .expect("ListGroupValueBuilder called with non-List/LargeList array")
+ }
+
+ fn current_end(&self) -> O {
+ *self.offsets.last().expect("offsets is never empty")
+ }
+
+ fn push_offset(&mut self, additional: usize) -> Result<()> {
+ // Guard against usize overflow first (cheap, defense in depth: a
+ // List<i32> with cumulative length close to i32::MAX could wrap
+ // before the `O::from_usize` range check below would fire).
+ let next = self
+ .current_end()
+ .as_usize()
+ .checked_add(additional)
+ .ok_or_else(|| {
+ internal_datafusion_err!(
+ "List offset usize overflow: current={} additional={}",
+ self.current_end().as_usize(),
+ additional
+ )
+ })?;
+ let next_o = O::from_usize(next)
+ .ok_or_else(|| internal_datafusion_err!("List offset overflows {}", next))?;
+ self.offsets.push(next_o);
+ Ok(())
+ }
+}
+
+impl<O: OffsetSizeTrait> GroupColumn for ListGroupValueBuilder<O> {
+ 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 l = Self::list_array(array);
+ // sliced child covering exactly the rhs row's elements
+ let rhs_sublist: ArrayRef = l.value(rhs_row);
+ let lhs_start = self.offsets[lhs_row].as_usize();
+ let lhs_end = self.offsets[lhs_row + 1].as_usize();
+ let lhs_len = lhs_end - lhs_start;
+ if lhs_len != rhs_sublist.len() {
+ return false;
+ }
+ for j in 0..lhs_len {
+ if !self.child.equal_to(lhs_start + j, &rhs_sublist, j) {
+ return false;
+ }
+ }
+ true
+ }
+
+ fn append_val(&mut self, array: &ArrayRef, row: usize) -> Result<()> {
+ let l = Self::list_array(array);
+ if l.is_null(row) {
+ self.outer_nulls.append(true);
+ // Zero-length range for null outer rows: do not push any child
+ // elements, and the offset for the next row stays the same.
+ let end = self.current_end();
+ self.offsets.push(end);
+ } else {
+ self.outer_nulls.append(false);
+ let sublist: ArrayRef = l.value(row);
+ let n = sublist.len();
+ for j in 0..n {
+ self.child.append_val(&sublist, j)?;
+ }
+ self.push_offset(n)?;
+ }
+ self.outer_len += 1;
+ 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 {
Review Comment:
`size_of_val` from `std::mem` does `len * size_of::<O>()` not giving current vec allocation (`capacity * size_of::<O>()`)
instead could use:
```suggestion
fn size(&self) -> usize {
self.offsets.allocated_size()
+ self.outer_nulls.allocated_size()
+ self.child.size()
}
```
helper from datafusion: `use datafusion_execution::memory_pool::proxy::{HashTableAllocExt, VecAllocExt};`
=
##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/list.rs:
##########
@@ -0,0 +1,844 @@
+// 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 `List<T>` and `LargeList<T>` group keys.
+//!
+//! Storage:
+//! - `offsets: Vec<O>` of length `outer_len + 1`, with `offsets[0] = 0`. The
+//! children of outer row `i` live at child positions
+//! `[offsets[i] .. offsets[i+1])`.
+//! - `child: Box<dyn GroupColumn>` for the element type.
+//! - `outer_nulls`: outer-row null bitmap.
+//!
+//! Null outer rows are stored with a zero-length range (i.e.
+//! `offsets[i+1] == offsets[i]`). No child slots are pushed for null rows.
+
+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, BooleanBufferBuilder, GenericListArray, OffsetSizeTrait,
+};
+use arrow::buffer::{OffsetBuffer, ScalarBuffer};
+use arrow::datatypes::FieldRef;
+use datafusion_common::{Result, internal_datafusion_err};
+use std::mem::size_of_val;
+use std::sync::Arc;
+
+/// A [`GroupColumn`] for `List<T>` (`O = i32`) and `LargeList<T>` (`O = i64`).
+pub struct ListGroupValueBuilder<O: OffsetSizeTrait> {
+ field: FieldRef,
+ offsets: Vec<O>,
+ child: Box<dyn GroupColumn>,
+ outer_nulls: MaybeNullBufferBuilder,
+ outer_len: usize,
+}
+
+impl<O: OffsetSizeTrait> ListGroupValueBuilder<O> {
+ pub fn new(field: FieldRef, child: Box<dyn GroupColumn>) -> Self {
+ Self {
+ field,
+ offsets: vec![O::usize_as(0)],
+ child,
+ outer_nulls: MaybeNullBufferBuilder::new(),
+ outer_len: 0,
+ }
+ }
+
+ fn list_array(array: &ArrayRef) -> &GenericListArray<O> {
+ array
+ .as_any()
+ .downcast_ref::<GenericListArray<O>>()
+ .expect("ListGroupValueBuilder called with non-List/LargeList array")
+ }
+
+ fn current_end(&self) -> O {
+ *self.offsets.last().expect("offsets is never empty")
+ }
+
+ fn push_offset(&mut self, additional: usize) -> Result<()> {
+ // Guard against usize overflow first (cheap, defense in depth: a
+ // List<i32> with cumulative length close to i32::MAX could wrap
+ // before the `O::from_usize` range check below would fire).
+ let next = self
+ .current_end()
+ .as_usize()
+ .checked_add(additional)
+ .ok_or_else(|| {
+ internal_datafusion_err!(
+ "List offset usize overflow: current={} additional={}",
+ self.current_end().as_usize(),
+ additional
+ )
+ })?;
+ let next_o = O::from_usize(next)
+ .ok_or_else(|| internal_datafusion_err!("List offset overflows {}", next))?;
+ self.offsets.push(next_o);
+ Ok(())
+ }
+}
+
+impl<O: OffsetSizeTrait> GroupColumn for ListGroupValueBuilder<O> {
+ 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 l = Self::list_array(array);
+ // sliced child covering exactly the rhs row's elements
+ let rhs_sublist: ArrayRef = l.value(rhs_row);
+ let lhs_start = self.offsets[lhs_row].as_usize();
+ let lhs_end = self.offsets[lhs_row + 1].as_usize();
+ let lhs_len = lhs_end - lhs_start;
+ if lhs_len != rhs_sublist.len() {
+ return false;
+ }
+ for j in 0..lhs_len {
+ if !self.child.equal_to(lhs_start + j, &rhs_sublist, j) {
+ return false;
+ }
+ }
+ true
+ }
+
+ fn append_val(&mut self, array: &ArrayRef, row: usize) -> Result<()> {
+ let l = Self::list_array(array);
+ if l.is_null(row) {
+ self.outer_nulls.append(true);
+ // Zero-length range for null outer rows: do not push any child
+ // elements, and the offset for the next row stays the same.
+ let end = self.current_end();
+ self.offsets.push(end);
+ } else {
+ self.outer_nulls.append(false);
+ let sublist: ArrayRef = l.value(row);
+ let n = sublist.len();
+ for j in 0..n {
+ self.child.append_val(&sublist, j)?;
+ }
+ self.push_offset(n)?;
+ }
+ self.outer_len += 1;
+ 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 {
Review Comment:
`size_of_val` from `std::mem` does `len * size_of::<O>()` not giving current vec allocation (`capacity * size_of::<O>()`)
instead could use:
```suggestion
fn size(&self) -> usize {
self.offsets.allocated_size()
+ self.outer_nulls.allocated_size()
+ self.child.size()
}
```
helper from datafusion: `use datafusion_execution::memory_pool::proxy::{HashTableAllocExt, VecAllocExt};`
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#discussion_r3338974884
##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/fixed_size_list.rs:
##########
@@ -0,0 +1,632 @@
+// 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::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: ArrowPrimitiveType> FixedSizeListGroupValueBuilder<T> {
+ 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:?}"
+ ),
+ };
+ let child = PrimitiveGroupValueBuilder::<T, true>::new(field.data_type().clone());
+ Self {
+ field,
+ list_len,
+ outer_nulls: MaybeNullBufferBuilder::new(),
+ outer_len: 0,
+ child,
+ }
+ }
+
+ fn list_len_usize(&self) -> usize {
+ self.list_len as usize
+ }
+}
+
+impl<T: ArrowPrimitiveType> GroupColumn for FixedSizeListGroupValueBuilder<T> {
+ 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");
+ let rhs_sublist: ArrayRef = list_array.value(rhs_row);
+ let list_len = self.list_len_usize();
+ let lhs_base = lhs_row * list_len;
+ for j in 0..list_len {
+ if !self.child.equal_to(lhs_base + j, &rhs_sublist, 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();
+ // FixedSizeList layout: outer row `row` owns child indices
+ // [row * list_len .. (row + 1) * list_len). The Arrow logical offset
+ // is already folded into `array.value(row)`; we use it indirectly via
+ // `values()` which is the unsliced child array, so include the outer
+ // array's offset here.
+ let start = (list_array.offset() + row) * list_len;
+ for j in 0..list_len {
+ self.child.append_val(child_array, start + j)?;
+ }
+ Ok(())
Review Comment:
`FixedSizeListArray::values()` may already be sliced to the logical region when the outer array is sliced. Computing `start` as `(list_array.offset() + row) * list_len` risks double-applying the offset and reading the wrong child values (or going out of bounds) for sliced inputs. Use `FixedSizeListArray::value_offset(row)` to compute the correct starting index.
##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/list.rs:
##########
@@ -0,0 +1,827 @@
+// 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 `List<T>` and `LargeList<T>` group keys.
+//!
+//! Storage:
+//! - `offsets: Vec<O>` of length `outer_len + 1`, with `offsets[0] = 0`. The
+//! children of outer row `i` live at child positions
+//! `[offsets[i] .. offsets[i+1])`.
+//! - `child: Box<dyn GroupColumn>` for the element type.
+//! - `outer_nulls`: outer-row null bitmap.
+//!
+//! Null outer rows are stored with a zero-length range (i.e.
+//! `offsets[i+1] == offsets[i]`). No child slots are pushed for null rows.
+
+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, BooleanBufferBuilder, GenericListArray, OffsetSizeTrait,
+};
+use arrow::buffer::{OffsetBuffer, ScalarBuffer};
+use arrow::datatypes::FieldRef;
+use datafusion_common::{Result, internal_datafusion_err};
+use std::mem::size_of_val;
+use std::sync::Arc;
+
+/// A [`GroupColumn`] for `List<T>` (`O = i32`) and `LargeList<T>` (`O = i64`).
+pub struct ListGroupValueBuilder<O: OffsetSizeTrait> {
+ field: FieldRef,
+ offsets: Vec<O>,
+ child: Box<dyn GroupColumn>,
+ outer_nulls: MaybeNullBufferBuilder,
+ outer_len: usize,
+}
+
+impl<O: OffsetSizeTrait> ListGroupValueBuilder<O> {
+ pub fn new(field: FieldRef, child: Box<dyn GroupColumn>) -> Self {
+ Self {
+ field,
+ offsets: vec![O::usize_as(0)],
+ child,
+ outer_nulls: MaybeNullBufferBuilder::new(),
+ outer_len: 0,
+ }
+ }
+
+ fn list_array<'a>(array: &'a ArrayRef) -> &'a GenericListArray<O> {
+ array
+ .as_any()
+ .downcast_ref::<GenericListArray<O>>()
+ .expect("ListGroupValueBuilder called with non-List/LargeList array")
+ }
+
+ fn current_end(&self) -> O {
+ *self.offsets.last().expect("offsets is never empty")
+ }
+
+ fn push_offset(&mut self, additional: usize) -> Result<()> {
+ let next = self.current_end().as_usize() + additional;
+ let next_o = O::from_usize(next)
+ .ok_or_else(|| internal_datafusion_err!("List offset overflows {}", next))?;
+ self.offsets.push(next_o);
+ Ok(())
+ }
+}
Review Comment:
`push_offset` does `as_usize() + additional` without overflow checking. On very large inputs this can wrap `usize` before the `O::from_usize` check runs, leading to incorrect offsets and potential memory safety issues later when building arrays. Use `checked_add` to detect overflow before converting to `O`.
##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs:
##########
@@ -1272,7 +1301,259 @@ mod tests {
GroupValues, multi_group_by::GroupValuesColumn,
};
- use super::GroupIndexView;
+ use super::{GroupIndexView, supported_schema, supported_type};
+
+ #[test]
+ fn supported_type_accepts_supported_primitives_and_strings() {
+ assert!(supported_type(&DataType::Int32));
+ assert!(supported_type(&DataType::Int64));
+ assert!(supported_type(&DataType::Float64));
+ assert!(supported_type(&DataType::Boolean));
+ assert!(supported_type(&DataType::Decimal128(38, 10)));
+ assert!(supported_type(&DataType::Utf8));
+ assert!(supported_type(&DataType::LargeUtf8));
+ assert!(supported_type(&DataType::Utf8View));
+ }
+
+ #[test]
+ fn supported_type_rejects_unsupported_primitives() {
+ // Float16 and Decimal256 are not in the supported set.
+ assert!(!supported_type(&DataType::Float16));
+ assert!(!supported_type(&DataType::Decimal256(76, 10)));
+ // Time64(Second) and Time64(Millisecond) variants are not supported
+ // (only the more precise Microsecond/Nanosecond are).
Review Comment:
The comment says only `Time64(Microsecond/Nanosecond)` are supported, but `supported_type` currently rejects *all* `Time64` variants (it doesn’t match `DataType::Time64(_)` at all). This is misleading in tests and may hide a real dispatcher/allow-list mismatch.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#discussion_r3346349834
##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/list.rs:
##########
@@ -0,0 +1,844 @@
+// 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 `List<T>` and `LargeList<T>` group keys.
+//!
+//! Storage:
+//! - `offsets: Vec<O>` of length `outer_len + 1`, with `offsets[0] = 0`. The
+//! children of outer row `i` live at child positions
+//! `[offsets[i] .. offsets[i+1])`.
+//! - `child: Box<dyn GroupColumn>` for the element type.
+//! - `outer_nulls`: outer-row null bitmap.
+//!
+//! Null outer rows are stored with a zero-length range (i.e.
+//! `offsets[i+1] == offsets[i]`). No child slots are pushed for null rows.
+
+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, BooleanBufferBuilder, GenericListArray, OffsetSizeTrait,
+};
+use arrow::buffer::{OffsetBuffer, ScalarBuffer};
+use arrow::datatypes::FieldRef;
+use datafusion_common::{Result, internal_datafusion_err};
+use std::mem::size_of_val;
+use std::sync::Arc;
+
+/// A [`GroupColumn`] for `List<T>` (`O = i32`) and `LargeList<T>` (`O = i64`).
+pub struct ListGroupValueBuilder<O: OffsetSizeTrait> {
+ field: FieldRef,
+ offsets: Vec<O>,
+ child: Box<dyn GroupColumn>,
+ outer_nulls: MaybeNullBufferBuilder,
+ outer_len: usize,
+}
+
+impl<O: OffsetSizeTrait> ListGroupValueBuilder<O> {
+ pub fn new(field: FieldRef, child: Box<dyn GroupColumn>) -> Self {
+ Self {
+ field,
+ offsets: vec![O::usize_as(0)],
+ child,
+ outer_nulls: MaybeNullBufferBuilder::new(),
+ outer_len: 0,
+ }
+ }
+
+ fn list_array(array: &ArrayRef) -> &GenericListArray<O> {
+ array
+ .as_any()
+ .downcast_ref::<GenericListArray<O>>()
+ .expect("ListGroupValueBuilder called with non-List/LargeList array")
+ }
+
+ fn current_end(&self) -> O {
+ *self.offsets.last().expect("offsets is never empty")
+ }
+
+ fn push_offset(&mut self, additional: usize) -> Result<()> {
+ // Guard against usize overflow first (cheap, defense in depth: a
+ // List<i32> with cumulative length close to i32::MAX could wrap
+ // before the `O::from_usize` range check below would fire).
+ let next = self
+ .current_end()
+ .as_usize()
+ .checked_add(additional)
+ .ok_or_else(|| {
+ internal_datafusion_err!(
+ "List offset usize overflow: current={} additional={}",
+ self.current_end().as_usize(),
+ additional
+ )
+ })?;
+ let next_o = O::from_usize(next)
+ .ok_or_else(|| internal_datafusion_err!("List offset overflows {}", next))?;
+ self.offsets.push(next_o);
+ Ok(())
+ }
+}
+
+impl<O: OffsetSizeTrait> GroupColumn for ListGroupValueBuilder<O> {
+ 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 l = Self::list_array(array);
+ // sliced child covering exactly the rhs row's elements
+ let rhs_sublist: ArrayRef = l.value(rhs_row);
+ let lhs_start = self.offsets[lhs_row].as_usize();
+ let lhs_end = self.offsets[lhs_row + 1].as_usize();
+ let lhs_len = lhs_end - lhs_start;
+ if lhs_len != rhs_sublist.len() {
+ return false;
+ }
+ for j in 0..lhs_len {
+ if !self.child.equal_to(lhs_start + j, &rhs_sublist, j) {
+ return false;
+ }
+ }
+ true
+ }
+
+ fn append_val(&mut self, array: &ArrayRef, row: usize) -> Result<()> {
+ let l = Self::list_array(array);
+ if l.is_null(row) {
+ self.outer_nulls.append(true);
+ // Zero-length range for null outer rows: do not push any child
+ // elements, and the offset for the next row stays the same.
+ let end = self.current_end();
+ self.offsets.push(end);
+ } else {
+ self.outer_nulls.append(false);
+ let sublist: ArrayRef = l.value(row);
+ let n = sublist.len();
+ for j in 0..n {
+ self.child.append_val(&sublist, j)?;
+ }
+ self.push_offset(n)?;
+ }
+ self.outer_len += 1;
+ 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 {
Review Comment:
Thanks @nathanb9 for review, addressed in this PR, but we want to split to more PRs, i will address there too.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#issuecomment-4618828366
Split PR 1 of 5 opened as #22751 — the dispatcher refactor + Time variant alignment + dhat heap regression harness, no new builders.
Follow-up PRs in order, each stacking on the previous merging:
- PR 2: `FixedSizeList<primitive>` support
- PR 3: `Struct<...>` support (uses the factory recursively)
- PR 4: `List<T>` / `LargeList<T>` support (uses the factory recursively, includes the `size()` accounting fix from #22706 commit 33eeddcdd)
- PR 5: Composition tests + memory regression assertions (`LargeList<Struct>`, `List<List>`, `Struct<Struct>`, dhat budget vs Rows comparison)
Each PR after 1 will lower the `dhat-heap` budget in `dhat_tests` to lock in that PR's memory win.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#issuecomment-4702217601
> @zhuqi-lucas thanks so much for driving this. Just checking: we are waiting on PR2 for review now right?
Yes @adriangb , thanks, i will submit the following PRs soon, the PR1 already merged.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#issuecomment-5288629628
Thank you for your contribution. Unfortunately, this pull request is stale because it has been open 60 days with no activity. Please remove the stale label or comment or this will be closed in 7 days.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#issuecomment-4602560085
Thanks for taking a look. Answers below.
## Q1: source of "most common offender" + supported-types table
Yes, from production observation. The shape is a wide multi-column GROUP BY (~40 columns) on a SEC filings materialized view, where a single `LargeList<Struct<Utf8, LargeUtf8>>` column for filing notes was causing the entire grouping to fall back to `GroupValuesRows`. Without that column the grouping completes at ~15 GiB peak; with it the path switches to row encoding and peak grows past 25 GiB. The PR's memory regression tests synthesize that shape and show 2.2x to 3.9x savings on smaller versions of the same pattern.
Below is the multi-column GROUP BY supported set after this PR. (Single-column GROUP BY has separate specializations in `single_group_by/` that this PR does not touch.)
**Supported**
- Int8..Int64, UInt8..UInt64, Float32, Float64
- Decimal128
- Utf8, LargeUtf8, Utf8View
- Binary, LargeBinary, BinaryView
- Boolean
- Date32, Date64
- Time32(Second / Millisecond)
- Time64(Microsecond / Nanosecond). This PR closes a pre-existing inconsistency on main where the dispatcher accepted these but `supported_type` did not. Copilot review caught it.
- Timestamp(any unit)
- **NEW: FixedSizeList\<primitive\>** (primitive child only)
- **NEW: List\<T\> / LargeList\<T\>** (recursive: child must be a supported type)
- **NEW: Struct\<...\>** (recursive: all fields must be supported types)
**Still falls back to `GroupValuesRows`**
- Float16, Decimal256
- FixedSizeList with non-primitive child
- Map\<K, V\> (entry-ordering semantics deserve their own discussion)
- Union, Dictionary, FixedSizeBinary
- Interval, Duration
The PR pins the `supported_type` ↔ `make_group_column` biconditional as a unit-test fuzz (`supported_type_and_make_group_column_stay_in_sync`) over 21 supported + 12 unsupported cases, so future drift between the allow-list and the dispatcher trips immediately.
## Q2: split into smaller PRs
Happy to. Proposed stacked sequence:
1. **Refactor only.** Extract the inline match in `GroupValuesColumn::intern` into a recursive `make_group_column(field: &Field) -> Result<Box<dyn GroupColumn>>` factory and make `supported_type` recursive (the recursion is needed up front so subsequent PRs can plug in nested children cleanly). No new builders. Also includes the Time32 / Time64 alignment fix and the consistency fuzz so the invariant is locked from the start.
2. **FixedSizeList\<primitive\>** support. Smallest new builder, no recursive child handling needed.
3. **Struct\<...\>** support. Recursive child via PR 1's factory.
4. **List\<T\> and LargeList\<T\>** support. Recursive child via PR 1's factory.
5. **Memory regression tests + composition coverage.** `LargeList<Struct>`, `List<List>`, `Struct<Struct>` end-to-end, plus the GroupValuesColumn-vs-GroupValuesRows size assertions that pin the 2.2x to 3.9x savings.
I'll prototype the split as stacked commits on this branch first so you can sanity-check the boundaries before I open the actual sequence of PRs.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#issuecomment-4602513773
Before I review the 2k LOC a couple of questions:
> The most common offender in real workloads is a single nested column (e.g. LargeList<Struct<Utf8, LargeUtf8>>) that drags an otherwise primitive-heavy 30+ column GROUP BY onto the slow path.
Is "most common offender" from your production data? Are there any other unsupported cases (e.g. are all dates, etc. supported)? A table / confirmation of what is and what is not supported would be great.
> This PR adds column-native GroupColumn implementations for FixedSizeList<primitive>, Struct<...>, List<T>, and LargeList<T>, so a GROUP BY containing any of these no longer falls back from GroupValuesColumn to GroupValuesRows.
Since you're adding support for multiple things my immediate ask would be: can we split this into 1 PR prepping whatever refactoring is needed + 1 PR per type we are adding support for? You can prototype this by refactoring this PR into stacked commits then we can split it once that looks good.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on code in PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#discussion_r3339027858
##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/fixed_size_list.rs:
##########
@@ -0,0 +1,632 @@
+// 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::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: ArrowPrimitiveType> FixedSizeListGroupValueBuilder<T> {
+ 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:?}"
+ ),
+ };
+ let child = PrimitiveGroupValueBuilder::<T, true>::new(field.data_type().clone());
+ Self {
+ field,
+ list_len,
+ outer_nulls: MaybeNullBufferBuilder::new(),
+ outer_len: 0,
+ child,
+ }
+ }
+
+ fn list_len_usize(&self) -> usize {
+ self.list_len as usize
+ }
+}
+
+impl<T: ArrowPrimitiveType> GroupColumn for FixedSizeListGroupValueBuilder<T> {
+ 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");
+ let rhs_sublist: ArrayRef = list_array.value(rhs_row);
+ let list_len = self.list_len_usize();
+ let lhs_base = lhs_row * list_len;
+ for j in 0..list_len {
+ if !self.child.equal_to(lhs_base + j, &rhs_sublist, 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();
+ // FixedSizeList layout: outer row `row` owns child indices
+ // [row * list_len .. (row + 1) * list_len). The Arrow logical offset
+ // is already folded into `array.value(row)`; we use it indirectly via
+ // `values()` which is the unsliced child array, so include the outer
+ // array's offset here.
+ let start = (list_array.offset() + row) * list_len;
+ for j in 0..list_len {
+ self.child.append_val(child_array, start + j)?;
+ }
+ Ok(())
Review Comment:
Good catch. Switched to `list_array.value_offset(row) as usize` in 2e59e6b1c. Correctness-equivalent today (FSL's `offset()` returns 0 and `values()` is already sliced), but the new form avoids double-applying any future offset behavior and matches the arrow-array convention.
##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/list.rs:
##########
@@ -0,0 +1,827 @@
+// 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 `List<T>` and `LargeList<T>` group keys.
+//!
+//! Storage:
+//! - `offsets: Vec<O>` of length `outer_len + 1`, with `offsets[0] = 0`. The
+//! children of outer row `i` live at child positions
+//! `[offsets[i] .. offsets[i+1])`.
+//! - `child: Box<dyn GroupColumn>` for the element type.
+//! - `outer_nulls`: outer-row null bitmap.
+//!
+//! Null outer rows are stored with a zero-length range (i.e.
+//! `offsets[i+1] == offsets[i]`). No child slots are pushed for null rows.
+
+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, BooleanBufferBuilder, GenericListArray, OffsetSizeTrait,
+};
+use arrow::buffer::{OffsetBuffer, ScalarBuffer};
+use arrow::datatypes::FieldRef;
+use datafusion_common::{Result, internal_datafusion_err};
+use std::mem::size_of_val;
+use std::sync::Arc;
+
+/// A [`GroupColumn`] for `List<T>` (`O = i32`) and `LargeList<T>` (`O = i64`).
+pub struct ListGroupValueBuilder<O: OffsetSizeTrait> {
+ field: FieldRef,
+ offsets: Vec<O>,
+ child: Box<dyn GroupColumn>,
+ outer_nulls: MaybeNullBufferBuilder,
+ outer_len: usize,
+}
+
+impl<O: OffsetSizeTrait> ListGroupValueBuilder<O> {
+ pub fn new(field: FieldRef, child: Box<dyn GroupColumn>) -> Self {
+ Self {
+ field,
+ offsets: vec![O::usize_as(0)],
+ child,
+ outer_nulls: MaybeNullBufferBuilder::new(),
+ outer_len: 0,
+ }
+ }
+
+ fn list_array<'a>(array: &'a ArrayRef) -> &'a GenericListArray<O> {
+ array
+ .as_any()
+ .downcast_ref::<GenericListArray<O>>()
+ .expect("ListGroupValueBuilder called with non-List/LargeList array")
+ }
+
+ fn current_end(&self) -> O {
+ *self.offsets.last().expect("offsets is never empty")
+ }
+
+ fn push_offset(&mut self, additional: usize) -> Result<()> {
+ let next = self.current_end().as_usize() + additional;
+ let next_o = O::from_usize(next)
+ .ok_or_else(|| internal_datafusion_err!("List offset overflows {}", next))?;
+ self.offsets.push(next_o);
+ Ok(())
+ }
+}
Review Comment:
Added in 2e59e6b1c. Guarded with `checked_add` so usize overflow is caught with a clear message before `O::from_usize` runs the range check.
##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/mod.rs:
##########
@@ -1272,7 +1301,259 @@ mod tests {
GroupValues, multi_group_by::GroupValuesColumn,
};
- use super::GroupIndexView;
+ use super::{GroupIndexView, supported_schema, supported_type};
+
+ #[test]
+ fn supported_type_accepts_supported_primitives_and_strings() {
+ assert!(supported_type(&DataType::Int32));
+ assert!(supported_type(&DataType::Int64));
+ assert!(supported_type(&DataType::Float64));
+ assert!(supported_type(&DataType::Boolean));
+ assert!(supported_type(&DataType::Decimal128(38, 10)));
+ assert!(supported_type(&DataType::Utf8));
+ assert!(supported_type(&DataType::LargeUtf8));
+ assert!(supported_type(&DataType::Utf8View));
+ }
+
+ #[test]
+ fn supported_type_rejects_unsupported_primitives() {
+ // Float16 and Decimal256 are not in the supported set.
+ assert!(!supported_type(&DataType::Float16));
+ assert!(!supported_type(&DataType::Decimal256(76, 10)));
+ // Time64(Second) and Time64(Millisecond) variants are not supported
+ // (only the more precise Microsecond/Nanosecond are).
Review Comment:
Good catch, this exposed a pre-existing inconsistency on main. Fixed in 2e59e6b1c by tightening `supported_type` to match the dispatcher exactly: `Time32(Second / Millisecond)` and `Time64(Microsecond / Nanosecond)` (the only semantically valid Time variants in Arrow). Also extended the supported_type ↔ make_group_column consistency fuzz to cover all four valid + four invalid Time combinations so the alignment is locked going forward.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "nathanb9 (via GitHub)" <gi...@apache.org>.
nathanb9 commented on code in PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#discussion_r3346128588
##########
datafusion/physical-plan/src/aggregates/group_values/multi_group_by/list.rs:
##########
@@ -0,0 +1,844 @@
+// 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 `List<T>` and `LargeList<T>` group keys.
+//!
+//! Storage:
+//! - `offsets: Vec<O>` of length `outer_len + 1`, with `offsets[0] = 0`. The
+//! children of outer row `i` live at child positions
+//! `[offsets[i] .. offsets[i+1])`.
+//! - `child: Box<dyn GroupColumn>` for the element type.
+//! - `outer_nulls`: outer-row null bitmap.
+//!
+//! Null outer rows are stored with a zero-length range (i.e.
+//! `offsets[i+1] == offsets[i]`). No child slots are pushed for null rows.
+
+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, BooleanBufferBuilder, GenericListArray, OffsetSizeTrait,
+};
+use arrow::buffer::{OffsetBuffer, ScalarBuffer};
+use arrow::datatypes::FieldRef;
+use datafusion_common::{Result, internal_datafusion_err};
+use std::mem::size_of_val;
+use std::sync::Arc;
+
+/// A [`GroupColumn`] for `List<T>` (`O = i32`) and `LargeList<T>` (`O = i64`).
+pub struct ListGroupValueBuilder<O: OffsetSizeTrait> {
+ field: FieldRef,
+ offsets: Vec<O>,
+ child: Box<dyn GroupColumn>,
+ outer_nulls: MaybeNullBufferBuilder,
+ outer_len: usize,
+}
+
+impl<O: OffsetSizeTrait> ListGroupValueBuilder<O> {
+ pub fn new(field: FieldRef, child: Box<dyn GroupColumn>) -> Self {
+ Self {
+ field,
+ offsets: vec![O::usize_as(0)],
+ child,
+ outer_nulls: MaybeNullBufferBuilder::new(),
+ outer_len: 0,
+ }
+ }
+
+ fn list_array(array: &ArrayRef) -> &GenericListArray<O> {
+ array
+ .as_any()
+ .downcast_ref::<GenericListArray<O>>()
+ .expect("ListGroupValueBuilder called with non-List/LargeList array")
+ }
+
+ fn current_end(&self) -> O {
+ *self.offsets.last().expect("offsets is never empty")
+ }
+
+ fn push_offset(&mut self, additional: usize) -> Result<()> {
+ // Guard against usize overflow first (cheap, defense in depth: a
+ // List<i32> with cumulative length close to i32::MAX could wrap
+ // before the `O::from_usize` range check below would fire).
+ let next = self
+ .current_end()
+ .as_usize()
+ .checked_add(additional)
+ .ok_or_else(|| {
+ internal_datafusion_err!(
+ "List offset usize overflow: current={} additional={}",
+ self.current_end().as_usize(),
+ additional
+ )
+ })?;
+ let next_o = O::from_usize(next)
+ .ok_or_else(|| internal_datafusion_err!("List offset overflows {}", next))?;
+ self.offsets.push(next_o);
+ Ok(())
+ }
+}
+
+impl<O: OffsetSizeTrait> GroupColumn for ListGroupValueBuilder<O> {
+ 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 l = Self::list_array(array);
+ // sliced child covering exactly the rhs row's elements
+ let rhs_sublist: ArrayRef = l.value(rhs_row);
+ let lhs_start = self.offsets[lhs_row].as_usize();
+ let lhs_end = self.offsets[lhs_row + 1].as_usize();
+ let lhs_len = lhs_end - lhs_start;
+ if lhs_len != rhs_sublist.len() {
+ return false;
+ }
+ for j in 0..lhs_len {
+ if !self.child.equal_to(lhs_start + j, &rhs_sublist, j) {
+ return false;
+ }
+ }
+ true
+ }
+
+ fn append_val(&mut self, array: &ArrayRef, row: usize) -> Result<()> {
+ let l = Self::list_array(array);
+ if l.is_null(row) {
+ self.outer_nulls.append(true);
+ // Zero-length range for null outer rows: do not push any child
+ // elements, and the offset for the next row stays the same.
+ let end = self.current_end();
+ self.offsets.push(end);
+ } else {
+ self.outer_nulls.append(false);
+ let sublist: ArrayRef = l.value(row);
+ let n = sublist.len();
+ for j in 0..n {
+ self.child.append_val(&sublist, j)?;
+ }
+ self.push_offset(n)?;
+ }
+ self.outer_len += 1;
+ 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 {
Review Comment:
`size_of_val` from `std::mem` does `len * size_of::<O>()` not giving current vec allocation (`capacity * size_of::<O>()`)
instead could use:
```rust
fn size(&self) -> usize {
self.offsets.allocated_size()
+ self.outer_nulls.allocated_size()
+ self.child.size()
}
```
helper from datafusion: `use datafusion_execution::memory_pool::proxy::{HashTableAllocExt, VecAllocExt};`
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "zhuqi-lucas (via GitHub)" <gi...@apache.org>.
zhuqi-lucas commented on PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#issuecomment-4602892722
Both make sense, agree on both.
**EPIC for remaining type coverage**
Opened #22715 as the broader tracking EPIC. It includes the existing #22682 (nested types, in flight via this PR sequence) plus the 6 additional primitives you called out (`FixedSizeBinary`, `Float16`, `Duration`, `Interval`, `Decimal256`, `Dictionary`), ordered easiest-first. `Dictionary` is flagged "needs discussion before implementation" because of the encoded-vs-decoded key trade-off. Each remaining-primitive item blocks on PR 1 of this PR sequence (the factory + recursive `supported_type`); after that they're independently mergeable.
**dhat memory regression tests**
Good call. The `size()`-based assertions I have today report what each builder self-claims, which is honest for column-native (each `Vec` / null buffer is accounted) but a weak signal for "did this PR actually move real heap."
Plan: in the refactor / setup PR (PR 1 of the split), add a small dhat-based harness gated behind a `dhat-heap` feature so the default test run does not pay the profiler cost. The harness wraps `GroupValuesColumn::intern` on a representative dataset in `dhat::Profiler::builder().testing().build()` and asserts `dhat::HeapStats::get().max_bytes < N`. Threshold is set generously at first; each subsequent type-support PR lowers it to reflect the actual win from that PR landing. Same harness can be reused by the EPIC items in #22715 as they land.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#issuecomment-4602618225
Would you be open to creating an EPIC for the other types as well? Interval, Duration, Float16, Decimal256, Dictionary and FixedSizeBinary in particular seem like pretty common primitives that we should be able to handle.
You bring up a good point with memory regression tests: would it make sense to also merge some [dhat](https://docs.rs/dhat/latest/dhat/) tests in one of the setup PRs so we can measure before / after memory usage? E.g. you write a test and set the limit to 8GB, then when you add support for a type lower that to 2GB.
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on PR #22706:
URL: https://github.com/apache/datafusion/pull/22706#issuecomment-4702193033
@zhuqi-lucas thanks so much for driving this. Just checking: we are waiting on PR2 for review now right?
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY [datafusion]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #22706: feat(physical-plan): add GroupColumn support for FixedSizeList / List / LargeList / Struct in multi-column GROUP BY
URL: https://github.com/apache/datafusion/pull/22706
--
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: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org