andygrove commented on code in PR #4801: URL: https://github.com/apache/datafusion-comet/pull/4801#discussion_r3552846792
########## native/spark-expr/src/agg_funcs/approx_percentile.rs: ########## @@ -0,0 +1,318 @@ +// 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 super::quantile_summaries::QuantileSummaries; +use arrow::array::{Array, ArrayRef, BinaryArray, Float64Array, ListArray}; +use arrow::datatypes::{DataType, Field, FieldRef}; +use datafusion::common::utils::SingleRowListArrayBuilder; +use datafusion::common::{downcast_value, Result, ScalarValue}; +use datafusion::logical_expr::function::{AccumulatorArgs, StateFieldsArgs}; +use datafusion::logical_expr::Volatility::Immutable; +use datafusion::logical_expr::{Accumulator, AggregateUDFImpl, Signature}; +use datafusion::physical_expr::expressions::format_state_name; +use std::sync::Arc; + +/// Native implementation of Spark's `approx_percentile` / `percentile_approx`, +/// backed by a bit-for-bit `QuantileSummaries` (Greenwald-Khanna) port. The +/// child value is cast to Float64 by the serde; the original `input_type` is +/// carried so results can be cast back to Spark's output type. +#[derive(Debug)] +pub struct ApproxPercentile { + name: String, + signature: Signature, + percentiles: Vec<f64>, + accuracy: i64, + input_type: DataType, + return_array: bool, +} + +impl PartialEq for ApproxPercentile { + fn eq(&self, other: &Self) -> bool { + self.name == other.name + && self.percentiles == other.percentiles + && self.accuracy == other.accuracy + && self.input_type == other.input_type + && self.return_array == other.return_array + } +} +impl Eq for ApproxPercentile {} + +impl std::hash::Hash for ApproxPercentile { + fn hash<H: std::hash::Hasher>(&self, state: &mut H) { + self.name.hash(state); + self.percentiles + .iter() + .for_each(|p| p.to_bits().hash(state)); + self.accuracy.hash(state); + self.input_type.hash(state); + self.return_array.hash(state); + } +} + +impl ApproxPercentile { + pub fn new( + percentiles: Vec<f64>, + accuracy: i64, + input_type: DataType, + return_array: bool, + ) -> Self { + Self { + name: "approx_percentile".to_string(), + signature: Signature::numeric(1, Immutable), + percentiles, + accuracy, + input_type, + return_array, + } + } +} + +impl AggregateUDFImpl for ApproxPercentile { + fn name(&self) -> &str { + &self.name + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { + if self.return_array { + Ok(DataType::List(Arc::new(Field::new( + "item", + self.input_type.clone(), + false, + )))) + } else { + Ok(self.input_type.clone()) + } + } + + fn accumulator(&self, _acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> { + Ok(Box::new(ApproxPercentileAccumulator::new( + self.percentiles.clone(), + self.accuracy, + self.input_type.clone(), + self.return_array, + ))) + } + + fn state_fields(&self, _args: StateFieldsArgs) -> Result<Vec<FieldRef>> { + Ok(vec![Arc::new(Field::new( + format_state_name(&self.name, "digest"), + DataType::Binary, + true, + ))]) + } + + fn groups_accumulator_supported(&self, _args: AccumulatorArgs) -> bool { + false + } +} + +#[derive(Debug)] +struct ApproxPercentileAccumulator { + summary: QuantileSummaries, + percentiles: Vec<f64>, + input_type: DataType, + return_array: bool, +} + +impl ApproxPercentileAccumulator { + fn new(percentiles: Vec<f64>, accuracy: i64, input_type: DataType, return_array: bool) -> Self { + let relative_error = 1.0 / accuracy as f64; + Self { + summary: QuantileSummaries::new( + QuantileSummaries::DEFAULT_COMPRESS_THRESHOLD, + relative_error, + ), + percentiles, + input_type, + return_array, + } + } + + /// Cast a double quantile back to Spark's output type. GK always returns an + /// actual inserted value (never an interpolation), so for the supported + /// numeric types this round-trips exactly and is always in range. + fn cast_back(&self, d: f64) -> ScalarValue { + match &self.input_type { + DataType::Int8 => ScalarValue::Int8(Some(d as i8)), + DataType::Int16 => ScalarValue::Int16(Some(d as i16)), + DataType::Int32 => ScalarValue::Int32(Some(d as i32)), + DataType::Int64 => ScalarValue::Int64(Some(d as i64)), + DataType::Float32 => ScalarValue::Float32(Some(d as f32)), + _ => ScalarValue::Float64(Some(d)), + } + } +} + +impl Accumulator for ApproxPercentileAccumulator { + fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> { + let arr = downcast_value!(&values[0], Float64Array); + if arr.null_count() == 0 { + // Fast path: no validity checks needed, iterate the raw values. + for &v in arr.values() { + self.summary.insert(v); + } + } else { + for v in arr.iter().flatten() { + self.summary.insert(v); + } + } + Ok(()) + } + + fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> { + let digests = downcast_value!(&states[0], BinaryArray); + self.summary.compress(); + for i in 0..digests.len() { + if digests.is_null(i) { + continue; + } + let peer = QuantileSummaries::from_bytes( + QuantileSummaries::DEFAULT_COMPRESS_THRESHOLD, + digests.value(i), + ); + if self.summary.count() == 0 { + // Empty self: merge would just clone the peer, so move it in. + self.summary = peer; + } else { + self.summary = self.summary.merge(&peer); + } + } + Ok(()) + } + + fn state(&mut self) -> Result<Vec<ScalarValue>> { + self.summary.compress(); + Ok(vec![ScalarValue::Binary(Some(self.summary.to_bytes()))]) + } + + fn evaluate(&mut self) -> Result<ScalarValue> { + self.summary.compress(); + match self.summary.query(&self.percentiles) { Review Comment: Good catch, this was a real bug. Spark's `ApproximatePercentile.eval` returns null whenever `result.length == 0`, so an empty percentage array yields null even for the array signature. `evaluate` now routes both the no-rows case and the empty-percentiles case through a shared `null_result`. Added `empty_percentiles_is_null` and `array_output_empty_input_is_null` Rust tests plus a SQL case. ########## spark/src/test/resources/sql-tests/expressions/aggregate/approx_percentile.sql: ########## @@ -0,0 +1,68 @@ +-- 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. + +-- Native approx_percentile via a GK (Greenwald-Khanna) quantile summary port, +-- matching Spark's algorithm and default relative error, so results are +-- bit-identical. Only byte, short, int, long, float, and double inputs are +-- supported. Every query below uses the default `query` mode, which asserts +-- native execution, so an all-fallback run of this file cannot vacuously pass. + +-- scalar percentile over a bigint (long) column +query +SELECT approx_percentile(id, 0.5) FROM range(1000) Review Comment: Added all five: `int` input, extreme `0.0` / `1.0` percentiles, negative values (`cast(id AS int) - 500`), a duplicate-heavy `id % 5` column, and array output over empty input. The Rust suite also gained `extreme_percentiles_hit_short_circuits`, `negative_values_are_ordered`, `duplicate_heavy_column_accumulates_g`, and `array_output_empty_input_is_null`. -- 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]
