Skip to main content

datafusion_functions_aggregate_common/aggregate/avg_distinct/
decimal.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use arrow::{
6    array::{ArrayRef, ArrowNativeTypeOp, ArrowNumericType},
7    compute::DecimalCast,
8    datatypes::{ArrowNativeType, DecimalType},
9};
10use datafusion_common::{Result, ScalarValue, exec_datafusion_err, exec_err};
11use datafusion_expr_common::accumulator::Accumulator;
12use std::fmt::Debug;
13use std::marker::PhantomData;
14use std::mem::size_of_val;
15
16use crate::aggregate::sum_distinct::DistinctSumAccumulator;
17use crate::utils::DecimalAverager;
18
19/// Generic implementation of `AVG DISTINCT` for Decimal types.
20/// Handles both all Arrow decimal types (32, 64, 128 and 256 bits).
21///
22/// The distinct values are stored in the input type `I`, the result is returned
23/// as the same or wider type `O`, and the intermediate sum is computed in the
24/// (never narrower) sum type `S` so it cannot overflow `I`'s native type.
25#[derive(Debug)]
26pub struct DecimalDistinctAvgAccumulator<
27    I: DecimalType + Debug,
28    S: DecimalType + Debug = I,
29    O: DecimalType + Debug = I,
30> {
31    sum_accumulator: DistinctSumAccumulator<I>,
32    sum_scale: i8,
33    target_precision: u8,
34    target_scale: i8,
35    _types: PhantomData<(S, O)>,
36}
37
38impl<I, S, O> DecimalDistinctAvgAccumulator<I, S, O>
39where
40    I: DecimalType + Debug,
41    S: DecimalType + Debug,
42    O: DecimalType + Debug,
43{
44    pub fn with_decimal_params(
45        sum_scale: i8,
46        target_precision: u8,
47        target_scale: i8,
48    ) -> Self {
49        let data_type = I::TYPE_CONSTRUCTOR(I::MAX_PRECISION, sum_scale);
50
51        Self {
52            sum_accumulator: DistinctSumAccumulator::new(data_type),
53            sum_scale,
54            target_precision,
55            target_scale,
56            _types: PhantomData,
57        }
58    }
59}
60
61/// Adds a distinct input value to AVG's widened intermediate sum.
62/// Wrapping is intentional because the caller selects `S` with the same
63/// `avg_sum_data_type` headroom contract as the non-distinct AVG path.
64#[inline]
65fn add_avg_distinct_sum<I, S>(sum: S::Native, value: I::Native) -> S::Native
66where
67    I: ArrowNumericType,
68    S: ArrowNumericType,
69    I::Native: Into<S::Native>,
70{
71    sum.add_wrapping(value.into())
72}
73
74impl<I, S, O> Accumulator for DecimalDistinctAvgAccumulator<I, S, O>
75where
76    I: DecimalType + ArrowNumericType + Debug,
77    S: DecimalType + ArrowNumericType + Debug,
78    O: DecimalType + ArrowNumericType + Debug,
79    I::Native: Into<S::Native> + DecimalCast,
80    S::Native: DecimalCast,
81    O::Native: DecimalCast,
82{
83    fn state(&mut self) -> Result<Vec<ScalarValue>> {
84        self.sum_accumulator.state()
85    }
86
87    fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> {
88        self.sum_accumulator.update_batch(values)
89    }
90
91    fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> {
92        self.sum_accumulator.merge_batch(states)
93    }
94
95    fn evaluate(&mut self) -> Result<ScalarValue> {
96        let out_type = O::TYPE_CONSTRUCTOR(self.target_precision, self.target_scale);
97        let count = self.sum_accumulator.distinct_count();
98        if count == 0 {
99            return ScalarValue::new_primitive::<O>(None, &out_type);
100        }
101
102        // Sum the distinct input values in the wider `S` so the total cannot
103        // overflow the input's native width (mirrors the non-distinct path).
104        let mut sum = S::Native::usize_as(0);
105        for value in self.sum_accumulator.distinct_values() {
106            sum = add_avg_distinct_sum::<I, S>(sum, value);
107        }
108
109        let Some(count) = S::Native::from_usize(count) else {
110            return exec_err!(
111                "Arithmetic overflow in avg: the distinct count {count} cannot \
112                 be represented in the sum type"
113            );
114        };
115
116        let averager = DecimalAverager::<S>::try_new(
117            self.sum_scale,
118            self.target_precision,
119            self.target_scale,
120        )?;
121        // Converting the average to the output type cannot fail in practice:
122        // `DecimalAverager::avg` validates it against the output precision,
123        // whose bound fits the output's native type by construction.
124        let avg =
125            O::Native::from_decimal(averager.avg(sum, count)?).ok_or_else(|| {
126                exec_datafusion_err!(
127                    "Arithmetic overflow in avg: the computed average does not fit \
128                     the output type"
129                )
130            })?;
131        ScalarValue::new_primitive::<O>(Some(avg), &out_type)
132    }
133
134    fn size(&self) -> usize {
135        let fixed_size = size_of_val(self);
136
137        // Account for the size of the sum_accumulator with its contained values
138        fixed_size + self.sum_accumulator.size()
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    #![expect(
145        clippy::large_digit_groups,
146        reason = "the single `_` marks the decimal point of the fixed-point literal"
147    )]
148
149    use super::*;
150    use arrow::array::{
151        Decimal32Array, Decimal64Array, Decimal128Array, Decimal256Array,
152    };
153    use arrow::datatypes::{
154        Decimal32Type, Decimal64Type, Decimal128Type, Decimal256Type, i256,
155    };
156    use std::sync::Arc;
157
158    #[test]
159    fn test_decimal32_distinct_avg_accumulator() -> Result<()> {
160        let precision = 5_u8;
161        let scale = 2_i8;
162        let array = Decimal32Array::from(vec![
163            Some(10_00),
164            Some(12_50),
165            Some(17_50),
166            Some(20_00),
167            Some(20_00),
168            Some(30_00),
169            None,
170            None,
171        ])
172        .with_precision_and_scale(precision, scale)?;
173
174        let mut accumulator =
175            DecimalDistinctAvgAccumulator::<Decimal32Type>::with_decimal_params(
176                scale, 9, 6,
177            );
178        accumulator.update_batch(&[Arc::new(array)])?;
179
180        let result = accumulator.evaluate()?;
181        let expected_result = ScalarValue::Decimal32(Some(18000000), 9, 6);
182        assert_eq!(result, expected_result);
183
184        Ok(())
185    }
186
187    #[test]
188    fn test_decimal64_distinct_avg_accumulator() -> Result<()> {
189        let precision = 10_u8;
190        let scale = 4_i8;
191        let array = Decimal64Array::from(vec![
192            Some(100_0000),
193            Some(125_0000),
194            Some(175_0000),
195            Some(200_0000),
196            Some(200_0000),
197            Some(300_0000),
198            None,
199            None,
200        ])
201        .with_precision_and_scale(precision, scale)?;
202
203        let mut accumulator =
204            DecimalDistinctAvgAccumulator::<Decimal64Type>::with_decimal_params(
205                scale, 14, 8,
206            );
207        accumulator.update_batch(&[Arc::new(array)])?;
208
209        let result = accumulator.evaluate()?;
210        let expected_result = ScalarValue::Decimal64(Some(180_00000000), 14, 8);
211        assert_eq!(result, expected_result);
212
213        Ok(())
214    }
215
216    #[test]
217    fn test_decimal128_distinct_avg_accumulator() -> Result<()> {
218        let precision = 10_u8;
219        let scale = 4_i8;
220        let array = Decimal128Array::from(vec![
221            Some(100_0000),
222            Some(125_0000),
223            Some(175_0000),
224            Some(200_0000),
225            Some(200_0000),
226            Some(300_0000),
227            None,
228            None,
229        ])
230        .with_precision_and_scale(precision, scale)?;
231
232        let mut accumulator =
233            DecimalDistinctAvgAccumulator::<Decimal128Type>::with_decimal_params(
234                scale, 14, 8,
235            );
236        accumulator.update_batch(&[Arc::new(array)])?;
237
238        let result = accumulator.evaluate()?;
239        let expected_result = ScalarValue::Decimal128(Some(180_00000000), 14, 8);
240        assert_eq!(result, expected_result);
241
242        Ok(())
243    }
244
245    #[test]
246    fn test_decimal256_distinct_avg_accumulator() -> Result<()> {
247        let precision = 50_u8;
248        let scale = 2_i8;
249
250        let array = Decimal256Array::from(vec![
251            Some(i256::from_i128(10_000)),
252            Some(i256::from_i128(12_500)),
253            Some(i256::from_i128(17_500)),
254            Some(i256::from_i128(20_000)),
255            Some(i256::from_i128(20_000)),
256            Some(i256::from_i128(30_000)),
257            None,
258            None,
259        ])
260        .with_precision_and_scale(precision, scale)?;
261
262        let mut accumulator =
263            DecimalDistinctAvgAccumulator::<Decimal256Type>::with_decimal_params(
264                scale, 54, 6,
265            );
266        accumulator.update_batch(&[Arc::new(array)])?;
267
268        let result = accumulator.evaluate()?;
269        let expected_result =
270            ScalarValue::Decimal256(Some(i256::from_i128(180_000000)), 54, 6);
271        assert_eq!(result, expected_result);
272
273        Ok(())
274    }
275
276    // The overflow regression tests below use odd-count ranges symmetric
277    // around a center value, so the exact sum is `count * center` and the
278    // average is exactly `center`.
279
280    #[test]
281    fn test_decimal32_distinct_avg_widens_to_decimal64() -> Result<()> {
282        // 42951 distinct values centered on 50000:
283        // sum = 42951 * 50000 = 2,147,550,000 > i32::MAX
284        let array = Decimal32Array::from_iter_values(28525..=71475)
285            .with_precision_and_scale(5, 0)?;
286
287        let mut accumulator = DecimalDistinctAvgAccumulator::<
288            Decimal32Type,
289            Decimal64Type,
290        >::with_decimal_params(0, 9, 4);
291        accumulator.update_batch(&[Arc::new(array)])?;
292
293        assert_eq!(
294            accumulator.evaluate()?,
295            ScalarValue::Decimal32(Some(500_000_000), 9, 4)
296        );
297
298        Ok(())
299    }
300
301    #[test]
302    fn test_decimal32_distinct_avg_widens_to_decimal128() -> Result<()> {
303        // 21477 distinct values centered on 99999:
304        // sum = 21477 * 99999 = 2,147,678,523 > i32::MAX
305        let array = Decimal32Array::from_iter_values(89261..=110737)
306            .with_precision_and_scale(9, 0)?;
307
308        let mut accumulator = DecimalDistinctAvgAccumulator::<
309            Decimal32Type,
310            Decimal128Type,
311        >::with_decimal_params(0, 9, 4);
312        accumulator.update_batch(&[Arc::new(array)])?;
313
314        assert_eq!(
315            accumulator.evaluate()?,
316            ScalarValue::Decimal32(Some(999_990_000), 9, 4)
317        );
318
319        Ok(())
320    }
321
322    #[test]
323    fn test_decimal64_distinct_avg_widens_to_decimal128() -> Result<()> {
324        // 92235 distinct values centered on 10^14 - 1:
325        // sum = 92235 * (10^14 - 1) ~= 9.22e18 > i64::MAX
326        let center: i64 = 100_000_000_000_000 - 1;
327        let array = Decimal64Array::from_iter_values(center - 46117..=center + 46117)
328            .with_precision_and_scale(18, 0)?;
329
330        let mut accumulator = DecimalDistinctAvgAccumulator::<
331            Decimal64Type,
332            Decimal128Type,
333        >::with_decimal_params(0, 18, 4);
334        accumulator.update_batch(&[Arc::new(array)])?;
335
336        assert_eq!(
337            accumulator.evaluate()?,
338            ScalarValue::Decimal64(Some(999_999_999_999_990_000), 18, 4)
339        );
340
341        Ok(())
342    }
343
344    #[test]
345    fn test_decimal128_distinct_avg_widens_to_decimal256() -> Result<()> {
346        // 21477 distinct values ending at 10^34 - 1, centered on 10^34 - 10739:
347        // sum = 21477 * (10^34 - 10739) ~= 2.15e38 > i128::MAX
348        let center: i128 = 10_i128.pow(34) - 10739;
349        let array = Decimal128Array::from_iter_values(center - 10738..=center + 10738)
350            .with_precision_and_scale(34, 0)?;
351
352        let mut accumulator = DecimalDistinctAvgAccumulator::<
353            Decimal128Type,
354            Decimal256Type,
355        >::with_decimal_params(0, 38, 4);
356        accumulator.update_batch(&[Arc::new(array)])?;
357
358        assert_eq!(
359            accumulator.evaluate()?,
360            ScalarValue::Decimal128(Some(center * 10_000), 38, 4)
361        );
362
363        Ok(())
364    }
365}