use std::cmp::Ordering;
use super::*;
use crate::execution::common::decimal::DecimalAverager;
use crate::execution::matching::{
ExecutableReduction, SelectedReductionOp as Op, WinningValue,
};
use crate::execution::storage::bound_columns::decode_decimal128_to_f64_bits;
use datafusion::arrow::array::{AsArray, Float64Array, PrimitiveArray};
use datafusion::arrow::buffer::{BooleanBuffer, Buffer, NullBuffer};
use datafusion::arrow::datatypes::{
ArrowNativeTypeOp, ArrowPrimitiveType, DataType, Decimal128Type, FieldRef,
Float32Type, Float64Type, Int32Type, Int64Type, Schema,
};
#[cfg(test)]
use datafusion::common::ScalarValue;
use datafusion::logical_expr::{EmitTo, function::AccumulatorArgs};
struct PrimitiveValues<T: ArrowPrimitiveType> {
carry: Option<T::Native>,
values: Vec<T::Native>,
validity: Vec<u8>,
memory: MemoryReservation,
}
impl<T: ArrowPrimitiveType> PrimitiveValues<T> {
fn new(memory: &MemoryReservation) -> Self {
Self {
carry: None,
values: Vec::new(),
validity: Vec::new(),
memory: memory.new_empty(),
}
}
fn release(&mut self) {
self.values = Vec::new();
self.validity = Vec::new();
self.memory.free();
}
fn take_array(&mut self, dtype: &DataType) -> ArrayRef {
let values = std::mem::take(&mut self.values);
let nulls = (!self.validity.is_empty()).then(|| {
NullBuffer::new(BooleanBuffer::new(
Buffer::from_vec(std::mem::take(&mut self.validity)),
0,
values.len(),
))
});
Arc::new(
PrimitiveArray::<T>::new(values.into(), nulls).with_data_type(dtype.clone()),
)
}
fn len(&self) -> usize {
self.values.len()
}
fn reserve_result(&mut self) -> Result<()> {
if self.values.len() == self.values.capacity() {
try_reserve_accounted(
&mut self.values,
&self.memory,
1,
"primitive summary values",
)?;
}
if self.carry.is_none() || !self.validity.is_empty() {
self.reserve_validity(self.values.len() + 1)?;
}
Ok(())
}
fn push_reserved(&mut self) {
let i = self.values.len();
debug_assert!(i < self.values.capacity());
if self.carry.is_none() {
self.validity[i / 8] &= !(1 << (i % 8));
}
self.values.push(self.carry.unwrap_or(T::Native::ZERO));
}
fn reserve_validity(&mut self, upto: usize) -> Result<()> {
let needed = upto.div_ceil(8);
if self.validity.len() < needed {
let additional = needed - self.validity.len();
try_reserve_accounted(
&mut self.validity,
&self.memory,
additional,
"primitive summary validity",
)?;
self.validity.resize(needed, u8::MAX);
}
Ok(())
}
}
pub(super) struct ReductionColumns {
pub(super) slots: Vec<Option<ReductionColumn>>,
}
impl ReductionColumns {
pub(super) fn new(
summaries: &[ExecutableDirectCountSummary],
memory: &mut MemoryReservation,
) -> Result<Option<Self>> {
if !summaries.iter().any(|s| s.reduction().is_some()) {
return Ok(None);
}
let mut slots = Vec::new();
try_reserve_accounted(
&mut slots,
memory,
summaries.len(),
"selected reduction columns",
)?;
Ok(Some(Self { slots }))
}
}
enum PrimitiveResult {
Int32(PrimitiveValues<Int32Type>),
Int64(PrimitiveValues<Int64Type>),
Float64(PrimitiveValues<Float64Type>),
Decimal128(PrimitiveValues<Decimal128Type>),
}
macro_rules! primitive {
($value:expr, $col:ident, $body:expr) => {
match $value {
PrimitiveResult::Int32($col) => $body,
PrimitiveResult::Int64($col) => $body,
PrimitiveResult::Float64($col) => $body,
PrimitiveResult::Decimal128($col) => $body,
}
};
}
pub(super) struct ReductionColumn {
result: PrimitiveResult,
non_null: u64,
finalized: bool,
}
impl ReductionColumn {
pub(super) fn new(
spec: &ExecutableReduction,
memory: &MemoryReservation,
) -> Result<Self> {
let result = match spec.output_type {
DataType::Int32 => PrimitiveResult::Int32(PrimitiveValues::new(memory)),
DataType::Int64 => PrimitiveResult::Int64(PrimitiveValues::new(memory)),
DataType::Float64 => PrimitiveResult::Float64(PrimitiveValues::new(memory)),
DataType::Decimal128(..) => {
PrimitiveResult::Decimal128(PrimitiveValues::new(memory))
}
ref other => {
return internal_err!("unsupported selected reduction output {other}");
}
};
let mut col = Self {
result,
non_null: 0,
finalized: false,
};
col.reset(spec.op);
Ok(col)
}
fn reset(&mut self, op: Op) {
primitive!(&mut self.result, col, col.carry = None);
if let (Op::Count, PrimitiveResult::Int64(col)) = (op, &mut self.result) {
col.carry = Some(0);
}
self.non_null = 0;
self.finalized = false;
}
fn update(
&mut self,
field: &ExecutableDirectCountSummary,
source: &ArrayRef,
first: usize,
rows: usize,
memory: &MemoryReservation,
) -> Result<()> {
let spec = field.reduction().expect("bound reduction");
if self.finalized
|| source.data_type() != &spec.input_type
|| first.checked_add(rows).is_none_or(|end| end > source.len())
{
return internal_err!("invalid selected reduction span");
}
let range = first..first + rows;
let op = spec.op;
match (op, &mut self.result, source.data_type()) {
(Op::Count, PrimitiveResult::Int64(col), _) => {
let valid = source.nulls().map_or(rows, |n| {
n.inner()
.inner()
.count_set_bits_offset(n.offset() + first, rows)
});
col.carry = Some(
col.carry
.unwrap_or(0)
.checked_add(valid as i64)
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"selected COUNT exceeds Int64".into(),
)
})?,
);
}
(_, PrimitiveResult::Int64(col), DataType::Int32) => fold(
col,
op,
source.as_primitive::<Int32Type>(),
range,
i64::from,
),
(_, PrimitiveResult::Int64(col), DataType::Int64) => {
fold(col, op, source.as_primitive::<Int64Type>(), range, |v| v)
}
(_, PrimitiveResult::Int32(col), DataType::Int32) => {
fold(col, op, source.as_primitive::<Int32Type>(), range, |v| v)
}
(Op::Min | Op::Max, PrimitiveResult::Float64(col), source_ty) => {
match source_ty {
DataType::Float64 => {
fold(col, op, source.as_primitive::<Float64Type>(), range, |v| v)
}
DataType::Float32 => fold(
col,
op,
source.as_primitive::<Float32Type>(),
range,
f64::from,
),
DataType::Int32 => fold(
col,
op,
source.as_primitive::<Int32Type>(),
range,
f64::from,
),
DataType::Int64 => {
fold(col, op, source.as_primitive::<Int64Type>(), range, |v| {
v as f64
})
}
DataType::Decimal128(_, scale) => fold(
col,
op,
source.as_primitive::<Decimal128Type>(),
range,
|v| f64::from_bits(decode_decimal128_to_f64_bits(v, *scale)),
),
_ => {
return internal_err!(
"invalid selected Float64 reduction source"
);
}
}
}
(Op::Avg | Op::Sum, PrimitiveResult::Float64(col), _) => {
match source.data_type() {
DataType::Int32 => {
let accepted = sum_finite_float64(
col,
source.as_primitive::<Int32Type>(),
range,
f64::from,
);
self.non_null += accepted;
}
DataType::Int64 => {
let accepted = sum_finite_float64(
col,
source.as_primitive::<Int64Type>(),
range,
|v| v as f64,
);
self.non_null += accepted;
}
DataType::Decimal128(_, scale) => {
let accepted = sum_finite_float64(
col,
source.as_primitive::<Decimal128Type>(),
range,
|v| f64::from_bits(decode_decimal128_to_f64_bits(v, *scale)),
);
self.non_null += accepted;
}
_ => {
let mut carry = col.carry;
let mut accepted = 0;
let mut add = |value: f64| -> Result<()> {
let previous = carry.unwrap_or(0.0);
let sum = previous + value;
let ambiguous = sum.is_nan()
&& ((previous.is_nan()
&& value.is_nan()
&& (previous.to_bits() | (1 << 51))
!= (value.to_bits() | (1 << 51)))
|| (previous.is_infinite() && value.is_infinite()));
carry = Some(if ambiguous {
exceptional_float_add(
op,
previous,
value,
field.field().arrow_field(),
memory,
)?
} else {
sum
});
accepted += 1;
Ok(())
};
match source.data_type() {
DataType::Float64 => visit_valid(
source.as_primitive::<Float64Type>(),
range,
&mut add,
)?,
DataType::Float32 => visit_valid(
source.as_primitive::<Float32Type>(),
range,
|v| add(f64::from(v)),
)?,
_ => {
return internal_err!(
"invalid selected Float64 reduction source"
);
}
}
col.carry = carry;
self.non_null += accepted;
}
}
}
(_, PrimitiveResult::Decimal128(col), DataType::Decimal128(..)) => {
let input = source.as_primitive::<Decimal128Type>();
if op == Op::Avg {
visit_valid(input, range, |value| {
col.carry = Some(col.carry.unwrap_or(0).wrapping_add(value));
self.non_null += 1;
Ok(())
})?;
} else {
fold(col, op, input, range, |v| v);
}
}
_ => return internal_err!("incompatible selected reduction types"),
}
Ok(())
}
fn set(&mut self, spec: &ExecutableReduction, value: WinningValue) -> Result<()> {
match (&mut self.result, value) {
(PrimitiveResult::Int32(col), WinningValue::Int32(v)) => col.carry = v,
(PrimitiveResult::Int64(col), WinningValue::Int64(v))
if v.is_some() || spec.op != Op::Count =>
{
col.carry = v
}
(PrimitiveResult::Float64(col), WinningValue::Float64(v)) => col.carry = v,
(PrimitiveResult::Decimal128(col), WinningValue::Decimal128(v)) => {
col.carry = v
}
_ => return internal_err!("invalid forwarded selected aggregate"),
}
self.finalized = true;
Ok(())
}
pub(super) fn reserve(&mut self, spec: &ExecutableReduction) -> Result<()> {
if !self.finalized && spec.op == Op::Avg && self.non_null != 0 {
match (&mut self.result, &spec.input_type, &spec.output_type) {
(PrimitiveResult::Float64(col), _, _) => {
col.carry = col.carry.map(|sum| sum / self.non_null as f64)
}
(
PrimitiveResult::Decimal128(col),
DataType::Decimal128(_, scale),
DataType::Decimal128(p, s),
) => {
let avg = DecimalAverager::<Decimal128Type>::try_new(*scale, *p, *s)?;
col.carry = col
.carry
.map(|sum| avg.avg(sum, i128::from(self.non_null)))
.transpose()?;
}
_ => return internal_err!("invalid selected AVG result"),
}
}
self.finalized = true;
primitive!(&mut self.result, col, col.reserve_result())
}
pub(super) fn append_reserved(&mut self, op: Op) {
debug_assert!(self.finalized);
primitive!(&mut self.result, col, col.push_reserved());
self.reset(op);
}
pub(super) fn len(&self) -> usize {
primitive!(&self.result, col, col.len())
}
pub(super) fn prepare_array(
&mut self,
dtype: &DataType,
memory: &MemoryReservation,
) -> Result<ArrayRef> {
memory.try_grow(size_of::<Float64Array>() + 2 * size_of::<usize>())?;
Ok(primitive!(&mut self.result, col, col.take_array(dtype)))
}
pub(super) fn release(&mut self) {
primitive!(&mut self.result, col, col.release());
}
}
fn visit_valid<T: ArrowPrimitiveType>(
input: &PrimitiveArray<T>,
range: std::ops::Range<usize>,
mut f: impl FnMut(T::Native) -> Result<()>,
) -> Result<()> {
let values = &input.values()[range.clone()];
match input.nulls() {
None => {
for v in values {
f(*v)?;
}
}
Some(nulls) => {
for (offset, v) in values.iter().enumerate() {
if nulls.is_valid(range.start + offset) {
f(*v)?;
}
}
}
}
Ok(())
}
fn sum_finite_float64<I: ArrowPrimitiveType>(
out: &mut PrimitiveValues<Float64Type>,
input: &PrimitiveArray<I>,
range: std::ops::Range<usize>,
convert: impl Fn(I::Native) -> f64,
) -> u64 {
let values = &input.values()[range.clone()];
if values.is_empty() {
return 0;
}
let mut sum = out.carry.unwrap_or(0.0);
let accepted = match input.nulls() {
None => {
for &raw in values {
sum += convert(raw);
}
values.len() as u64
}
Some(nulls) => {
let mut count = 0u64;
for (offset, &raw) in values.iter().enumerate() {
if nulls.is_valid(range.start + offset) {
sum += convert(raw);
count += 1;
}
}
count
}
};
if accepted != 0 {
out.carry = Some(sum);
}
accepted
}
fn fold<T: ArrowPrimitiveType, I: ArrowPrimitiveType>(
out: &mut PrimitiveValues<T>,
op: Op,
input: &PrimitiveArray<I>,
range: std::ops::Range<usize>,
convert: impl Fn(I::Native) -> T::Native,
) {
let values = &input.values()[range.clone()];
if values.is_empty() {
return;
}
match (op, input.nulls()) {
(Op::Sum, None) => {
let mut acc = out.carry.unwrap_or(T::Native::ZERO);
for &raw in values {
acc = acc.add_wrapping(convert(raw));
}
out.carry = Some(acc);
}
(Op::Sum, Some(nulls)) => {
let mut acc = out.carry.unwrap_or(T::Native::ZERO);
let mut any = out.carry.is_some();
for (offset, &raw) in values.iter().enumerate() {
if nulls.is_valid(range.start + offset) {
acc = acc.add_wrapping(convert(raw));
any = true;
}
}
if any {
out.carry = Some(acc);
}
}
(Op::Min | Op::Max, None) => {
let ordering = if op == Op::Min {
Ordering::Less
} else {
Ordering::Greater
};
let mut acc = out.carry.unwrap_or_else(|| convert(values[0]));
for &raw in values {
let v = convert(raw);
if v.compare(acc) == ordering {
acc = v;
}
}
out.carry = Some(acc);
}
(Op::Min | Op::Max, Some(nulls)) => {
let ordering = if op == Op::Min {
Ordering::Less
} else {
Ordering::Greater
};
let mut carry = out.carry;
for (offset, &raw) in values.iter().enumerate() {
if nulls.is_valid(range.start + offset) {
let v = convert(raw);
carry = Some(match carry {
Some(prior) if v.compare(prior) != ordering => prior,
_ => v,
});
}
}
out.carry = carry;
}
(Op::Count | Op::Avg, _) => {
unreachable!("fold only handles Sum, Min, and Max")
}
}
}
#[cold]
fn exceptional_float_add(
op: Op,
previous: f64,
value: f64,
field: FieldRef,
memory: &MemoryReservation,
) -> Result<f64> {
use datafusion::functions_aggregate::{average::avg_udaf, sum::sum_udaf};
let scratch = memory.new_empty();
scratch.try_grow(2048)?;
let udf = if op == Op::Avg {
avg_udaf()
} else {
sum_udaf()
};
let mut acc = udf.create_groups_accumulator(AccumulatorArgs {
return_field: Arc::clone(&field),
schema: &Schema::empty(),
ignore_nulls: false,
order_bys: &[],
is_reversed: false,
name: "selected",
is_distinct: false,
exprs: &[],
expr_fields: std::slice::from_ref(&field),
})?;
let pair: ArrayRef = Arc::new(Float64Array::from(vec![previous, value]));
acc.update_batch(&[pair], &[0, 0], None, 1)?;
let sums = if op == Op::Avg {
acc.state(EmitTo::All)?.pop().expect("AVG sum state")
} else {
acc.evaluate(EmitTo::All)?
};
Ok(sums.as_primitive::<Float64Type>().value(0))
}
impl SummaryOutputStorage {
fn reduction_mut(
&mut self,
index: usize,
) -> Result<(&ExecutableDirectCountSummary, &mut ReductionColumn)> {
if let Self::DirectCounts {
summaries,
reductions: Some(reductions),
..
} = self
&& let Some(slot) = reductions.slots.get_mut(index).and_then(Option::as_mut)
{
return Ok((&summaries[index], slot));
}
internal_err!("selected output {index} is not a bound reduction")
}
}
impl OutputBatchBuilder {
pub(in crate::execution::storage) fn update_reduction(
&mut self,
index: usize,
source: &ArrayRef,
first: usize,
rows: usize,
) -> Result<()> {
let (summary, slot) = self.summary_output.reduction_mut(index)?;
slot.update(summary, source, first, rows, &self.memory)
}
pub(in crate::execution::storage) fn reset_reductions(&mut self) {
if let SummaryOutputStorage::DirectCounts {
summaries,
reductions: Some(reductions),
..
} = &mut self.summary_output
{
for (slot, summary) in reductions.slots.iter_mut().zip(summaries.iter()) {
if let Some(slot) = slot {
slot.reset(summary.reduction().expect("bound reduction").op);
}
}
}
}
pub(in crate::execution::storage) fn set_reduction(
&mut self,
index: usize,
value: WinningValue,
) -> Result<()> {
let (summary, slot) = self.summary_output.reduction_mut(index)?;
slot.set(summary.reduction().expect("bound reduction"), value)
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
#[test]
fn selected_decimal_float64_reductions_match_arrow_cast_bits() -> Result<()> {
use crate::core::MatchSummaryField;
use crate::execution::common::memory::new_unbounded_state_memory;
use datafusion::arrow::array::Decimal128Array;
use datafusion::arrow::compute::cast;
use datafusion::arrow::datatypes::Field;
for scale in [2, -5, -23, 23, 25] {
for magnitude in [
17_i128,
(1_i128 << 53) + 1,
(1_i128 << 53) + 3,
12_345_678_901_234_567_890_123_456_789_012_345_678,
] {
for raw in [magnitude, -magnitude] {
for nullable in [false, true] {
let values = if nullable {
vec![None, Some(raw), None]
} else {
vec![Some(raw)]
};
let source: ArrayRef = Arc::new(
Decimal128Array::from(values)
.with_precision_and_scale(38, scale)?,
);
let casted = cast(&source, &DataType::Float64)?;
let expected = casted
.as_primitive::<Float64Type>()
.value(usize::from(nullable))
.to_bits();
for op in [Op::Sum, Op::Avg, Op::Min, Op::Max] {
let summary = ExecutableDirectCountSummary::new_reduction(
MatchSummaryField::new(
0,
Arc::new(Field::new("v", DataType::Float64, true)),
),
None,
ExecutableReduction {
op,
input_column: 0,
input_type: source.data_type().clone(),
output_type: DataType::Float64,
managed_aggregate: None,
},
);
let spec = summary.reduction().unwrap();
let memory = new_unbounded_state_memory();
let mut column = ReductionColumn::new(spec, &memory)?;
for row in 0..source.len() {
column.update(&summary, &source, row, 1, &memory)?;
}
column.reserve(spec)?;
let PrimitiveResult::Float64(result) = &column.result else {
panic!("expected Float64 reduction");
};
assert_eq!(
result.carry.unwrap().to_bits(),
expected,
"{op:?}, raw={raw}, scale={scale}, nullable={nullable}"
);
}
}
}
}
}
Ok(())
}