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: [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]
