Dandandan commented on code in PR #21090: URL: https://github.com/apache/datafusion/pull/21090#discussion_r2969538659
########## datafusion/functions-aggregate/src/first_last/state.rs: ########## @@ -0,0 +1,439 @@ +// 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 std::mem::size_of; +use std::sync::Arc; + +use arrow::array::{ + Array, ArrayRef, ArrowPrimitiveType, AsArray, BinaryBuilder, BinaryViewBuilder, + BooleanBufferBuilder, LargeBinaryBuilder, LargeStringBuilder, PrimitiveArray, + StringBuilder, StringViewBuilder, +}; +use arrow::buffer::{BooleanBuffer, NullBuffer}; +use arrow::datatypes::DataType; +use datafusion_common::{Result, internal_err}; +use datafusion_expr::EmitTo; + +pub(crate) trait ValueState: Send + Sync { + /// Resizes the state to accommodate `new_size` groups. + fn resize(&mut self, new_size: usize); + /// Updates the state for the specified `group_idx` using the value at `idx` from the provided `array`. + /// + /// Note: While this is not a batch interface, it is not a performance bottleneck. + /// In heavy aggregation benchmarks, the overhead of this method is typically less than 1%. + /// + /// Benchmarked queries with < 1% `update` overhead: + /// ```sql + /// -- TPC-H SF10 + /// select l_shipmode, last_value(l_partkey order by l_orderkey, l_linenumber, l_comment, l_suppkey, l_tax) + /// from 'benchmarks/data/tpch_sf10/lineitem' + /// group by l_shipmode; + /// + /// -- H2O G1_1e8 + /// select t.id1, first_value(t.id3 order by t.id2, t.id4) as r2 + /// from 'benchmarks/data/h2o/G1_1e8_1e8_100_0.parquet' as t + /// group by t.id1, t.v1; + /// ``` + fn update(&mut self, group_idx: usize, array: &ArrayRef, idx: usize) -> Result<()>; + /// Takes the accumulated state and returns it as an [`ArrayRef`], respecting the `emit_to` strategy. + fn take(&mut self, emit_to: EmitTo) -> Result<ArrayRef>; + /// Returns the estimated memory size of the state in bytes. + fn size(&self) -> usize; +} + +pub(crate) struct PrimitiveValueState<T: ArrowPrimitiveType + Send> { + /// Values data + vals: Vec<T::Native>, + nulls: BooleanBufferBuilder, + data_type: DataType, +} + +impl<T: ArrowPrimitiveType + Send> PrimitiveValueState<T> { + pub(crate) fn new(data_type: DataType) -> Self { + Self { + vals: vec![], + nulls: BooleanBufferBuilder::new(0), + data_type, + } + } +} + +impl<T: ArrowPrimitiveType + Send> ValueState for PrimitiveValueState<T> { + fn resize(&mut self, new_size: usize) { + self.vals.resize(new_size, T::default_value()); + self.nulls.resize(new_size); + } + + fn update(&mut self, group_idx: usize, array: &ArrayRef, idx: usize) -> Result<()> { + let array = array.as_primitive::<T>(); + self.vals[group_idx] = array.value(idx); + self.nulls.set_bit(group_idx, !array.is_null(idx)); + Ok(()) + } + + fn take(&mut self, emit_to: EmitTo) -> Result<ArrayRef> { + let values = emit_to.take_needed(&mut self.vals); + let null_buf = NullBuffer::new(take_need(&mut self.nulls, emit_to)); + let array: PrimitiveArray<T> = + PrimitiveArray::<T>::new(values.into(), Some(null_buf)) + .with_data_type(self.data_type.clone()); + Ok(Arc::new(array)) + } + + fn size(&self) -> usize { + self.vals.capacity() * size_of::<T::Native>() + self.nulls.capacity() / 8 + } +} + +/// Stores internal state for "bytes" types (Utf8, Binary, etc.). +/// +/// This implementation is similar to `MinMaxBytesState` in `min_max_bytes.rs`, but +/// it does not reuse it for two main reasons: +/// +/// 1. **Direct Overwrite**: `MinMaxBytesState::update_batch` is tightly coupled +/// with min/max comparison logic, whereas `FirstLast` performs its own comparisons +/// externally (using ordering columns) and only needs a simple interface to +/// unconditionally set/overwrite values for specific groups. +/// 2. **Different NULL Handling**: `MinMaxBytesState` always ignores `NULL` values +/// in the input, while `BytesValueState` needs to support setting `NULL` values +/// to correctly implement `RESPECT NULLS` behavior. +/// +pub(crate) struct BytesValueState { + vals: Vec<Option<Vec<u8>>>, Review Comment: I think this can be much more efficiently stored as values `Vec<u8>` and offsets `Vec<OffsetType>` -- 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]
