use crate::core::vm::{
AggregateKind, SlotValueType, StatisticalPopulation, VarianceProjection,
};
use crate::core::{MatchMetadataColumn, Pattern, Symbol, classifier_bits_col_name};
use datafusion::arrow::datatypes::DataType;
use datafusion::common::{DFSchema, ScalarValue};
use datafusion::logical_expr::{Expr, expr::AggregateFunction};
use crate::planning::extract::is_plain_aggregate;
use crate::planning::logical::{LogicalManagedAggregate, LogicalMatchProgram};
use crate::planning::predicate::direct_column_name;
use crate::planning::semantic_metadata::{
aggregate_references_semantic_metadata, is_managed_classifier_navigation_aggregate,
};
use crate::planning::type_validation::can_have_nulls_outside_bitmap;
use crate::planning::{
AccumulatorInputMode, ManagedAggregateBackend, MatchCompilerOptions, RoutedAggregate,
};
use crate::core::vm::NavigationValueDomain;
use crate::core::{AggregateId, MAX_FIRST_OFFSET, MAX_PREV_DEPTH};
use crate::planning::logical::LogicalSymbolId;
pub(crate) struct AggregateAssembly {
pub(crate) logical: LogicalManagedAggregate,
pub(crate) recipe: ManagedAggregateRecipe,
pub(crate) backend: ManagedAggregateBackend,
}
impl AggregateAssembly {
pub(crate) fn into_routed(self) -> RoutedAggregate {
RoutedAggregate::new(
self.logical,
self.backend,
self.recipe.accumulator_input_mode(),
self.recipe.counts_every_row(),
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ManagedAggregateRecipe {
register: Option<RegisterAggregateRecipe>,
counts_every_row: bool,
accumulator_input_mode: AccumulatorInputMode,
}
impl ManagedAggregateRecipe {
pub(crate) const fn supports_registers(&self) -> bool {
self.register.is_some()
}
pub(crate) const fn counts_every_row(&self) -> bool {
self.counts_every_row
}
pub(crate) const fn accumulator_input_mode(&self) -> AccumulatorInputMode {
self.accumulator_input_mode
}
pub(super) const fn register(&self) -> Option<&RegisterAggregateRecipe> {
self.register.as_ref()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(super) struct NullableAggregateInput {
pub(super) column: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(super) struct TypedAggregateInput {
pub(super) column: String,
pub(super) value_type: SlotValueType,
pub(super) scale: i8,
pub(super) nullable: bool,
pub(super) as_float: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum RegisterAggregateRecipe {
LeadingFirst {
column: String,
},
RowCount,
NonNullCount {
input: NullableAggregateInput,
},
Algebraic {
kind: AggregateKind,
input: TypedAggregateInput,
track_nonnull: bool,
},
Variance {
input: TypedAggregateInput,
projection: VarianceProjection,
},
Navigation(NavigationRequest),
}
pub(crate) fn build_aggregate_assemblies(
program: &LogicalMatchProgram,
input_schema: &DFSchema,
options: MatchCompilerOptions,
) -> Vec<AggregateAssembly> {
program
.managed_aggregates()
.iter()
.map(|aggregate| {
let operation = canonical_operation(aggregate.func());
let recipe = ManagedAggregateRecipe {
counts_every_row: is_predictable_count(aggregate.func(), operation),
accumulator_input_mode: accumulator_input_mode(operation),
register: register_recipe(aggregate, program, input_schema, operation),
};
let backend = if !options.disable_register_aggregate_backend()
&& recipe.supports_registers()
{
ManagedAggregateBackend::Registers
} else {
ManagedAggregateBackend::Accumulator
};
AggregateAssembly {
logical: aggregate.clone(),
recipe,
backend,
}
})
.collect()
}
fn register_recipe(
aggregate: &LogicalManagedAggregate,
program: &LogicalMatchProgram,
input_schema: &DFSchema,
operation: Option<CanonicalOperation>,
) -> Option<RegisterAggregateRecipe> {
let func = aggregate.func();
if (aggregate_references_semantic_metadata(func)
&& !is_managed_classifier_navigation_aggregate(func))
|| !is_plain_aggregate(func)
{
return None;
}
match operation? {
CanonicalOperation::Count => count_recipe(func, input_schema),
CanonicalOperation::Algebraic(kind) => algebraic_recipe(func, input_schema, kind),
CanonicalOperation::Variance(projection) => {
variance_recipe(func, input_schema, projection)
}
CanonicalOperation::Navigation(family) => {
navigation_recipe(aggregate, program, family, input_schema)
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum VmNavigationFunctionFamily {
First,
Last,
Prev,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CanonicalOperation {
Count,
Algebraic(AggregateKind),
Variance(VarianceProjection),
Navigation(VmNavigationFunctionFamily),
}
fn canonical_operation(func: &AggregateFunction) -> Option<CanonicalOperation> {
let udaf = func.func.as_ref();
let (known, operation) = match udaf.name() {
"count" => (
datafusion::functions_aggregate::count::count_udaf(),
CanonicalOperation::Count,
),
"sum" => (
datafusion::functions_aggregate::sum::sum_udaf(),
CanonicalOperation::Algebraic(AggregateKind::Additive),
),
"min" => (
datafusion::functions_aggregate::min_max::min_udaf(),
CanonicalOperation::Algebraic(AggregateKind::Min),
),
"max" => (
datafusion::functions_aggregate::min_max::max_udaf(),
CanonicalOperation::Algebraic(AggregateKind::Max),
),
"avg" => (
datafusion::functions_aggregate::average::avg_udaf(),
CanonicalOperation::Algebraic(AggregateKind::Avg),
),
"bool_and" => (
datafusion::functions_aggregate::bool_and_or::bool_and_udaf(),
CanonicalOperation::Algebraic(AggregateKind::BoolAnd),
),
"bool_or" => (
datafusion::functions_aggregate::bool_and_or::bool_or_udaf(),
CanonicalOperation::Algebraic(AggregateKind::BoolOr),
),
"stddev" => (
datafusion::functions_aggregate::stddev::stddev_udaf(),
CanonicalOperation::Variance(VarianceProjection::Stddev(
StatisticalPopulation::Sample,
)),
),
"stddev_pop" => (
datafusion::functions_aggregate::stddev::stddev_pop_udaf(),
CanonicalOperation::Variance(VarianceProjection::Stddev(
StatisticalPopulation::Population,
)),
),
"var" => (
datafusion::functions_aggregate::variance::var_samp_udaf(),
CanonicalOperation::Variance(VarianceProjection::Variance(
StatisticalPopulation::Sample,
)),
),
"var_pop" => (
datafusion::functions_aggregate::variance::var_pop_udaf(),
CanonicalOperation::Variance(VarianceProjection::Variance(
StatisticalPopulation::Population,
)),
),
"first_value" => (
datafusion_functions_aggregate::first_last::first_value_udaf(),
CanonicalOperation::Navigation(VmNavigationFunctionFamily::First),
),
"__mr_first_agg" => (
crate::functions::udaf::mr_first_offset_udaf(),
CanonicalOperation::Navigation(VmNavigationFunctionFamily::First),
),
"last_value" => (
datafusion_functions_aggregate::first_last::last_value_udaf(),
CanonicalOperation::Navigation(VmNavigationFunctionFamily::Last),
),
"__mr_last_agg" => (
crate::functions::udaf::mr_last_offset_udaf(),
CanonicalOperation::Navigation(VmNavigationFunctionFamily::Last),
),
"__mr_prev_agg" => (
crate::functions::udaf::mr_prev_udaf(),
CanonicalOperation::Navigation(VmNavigationFunctionFamily::Prev),
),
_ => return None,
};
(udaf == known.as_ref()).then_some(operation)
}
fn navigation_recipe(
aggregate: &LogicalManagedAggregate,
program: &LogicalMatchProgram,
family: VmNavigationFunctionFamily,
input_schema: &DFSchema,
) -> Option<RegisterAggregateRecipe> {
if family == VmNavigationFunctionFamily::First
&& aggregate.func().params.args.len() == 1
{
let column = direct_column_name(&aggregate.func().params.args[0])?.to_string();
if !column.eq_ignore_ascii_case(MatchMetadataColumn::Classifier.as_ref()) {
let data_type = input_schema
.fields()
.iter()
.find(|field| field.name() == &column)
.or_else(|| schema_field(input_schema, &column))?
.data_type();
if crate::planning::predicate::vm_type_from_data_type(data_type, true)
.is_some()
&& leading_symbol(program.pattern()).is_some_and(|name| {
aggregate
.symbol()
.is_none_or(|id| program.symbols()[id.index()].name() == name)
})
{
return Some(RegisterAggregateRecipe::LeadingFirst { column });
}
}
}
NavigationRequest::interpret(aggregate, program, family, input_schema)
.map(RegisterAggregateRecipe::Navigation)
}
fn leading_symbol(pattern: &Pattern) -> Option<&str> {
match pattern {
Pattern::Symbol(Symbol::Named(name)) | Pattern::Exclude(Symbol::Named(name)) => {
Some(name)
}
Pattern::Group(inner) => leading_symbol(inner),
Pattern::Concat(parts) => parts.first().and_then(leading_symbol),
Pattern::Repetition(inner, quantifier) if quantifier.min_repetitions() > 0 => {
leading_symbol(inner)
}
Pattern::Alternation(parts) => {
let (first_part, rest) = parts.split_first()?;
let first = leading_symbol(first_part)?;
rest.iter()
.all(|part| leading_symbol(part) == Some(first))
.then_some(first)
}
_ => None,
}
}
fn is_internal_navigation_mask_arg(arg: &Expr, classifier_mask: Option<&str>) -> bool {
matches!(arg, Expr::Literal(ScalarValue::Boolean(Some(true)), _))
|| arg == &crate::planning::logical::valid_match_row_expr()
|| matches!(
arg,
Expr::IsNotNull(inner)
if navigation_mask_column_name(inner)
.is_some_and(|name| name == MatchMetadataColumn::Classifier.as_ref())
)
|| navigation_mask_column_name(arg).is_some_and(|name| {
name == MatchMetadataColumn::Classifier.as_ref()
|| classifier_mask.is_some_and(|expected| name == expected)
})
}
fn navigation_mask_column_name(expr: &Expr) -> Option<String> {
match expr {
Expr::Column(column) => Some(column.name.clone()),
Expr::Alias(alias) => navigation_mask_column_name(&alias.expr),
Expr::Cast(cast) => navigation_mask_column_name(&cast.expr),
_ => None,
}
}
fn count_recipe(
func: &AggregateFunction,
input_schema: &DFSchema,
) -> Option<RegisterAggregateRecipe> {
let args = &func.params.args;
if args.len() > 1 {
return None;
}
if count_args_increment_every_row(args) {
return Some(RegisterAggregateRecipe::RowCount);
}
let arg = args.first()?;
let column = direct_column_name(arg).map(str::to_owned).or_else(|| {
crate::planning::define::preparation::direct_widening_column(arg, input_schema)
.map(|(column, _)| column.name.clone())
})?;
let field = schema_field(input_schema, &column)?;
if field.is_nullable() || can_have_nulls_outside_bitmap(field.data_type()) {
Some(RegisterAggregateRecipe::NonNullCount {
input: NullableAggregateInput { column },
})
} else {
Some(RegisterAggregateRecipe::RowCount)
}
}
fn algebraic_recipe(
func: &AggregateFunction,
input_schema: &DFSchema,
kind: AggregateKind,
) -> Option<RegisterAggregateRecipe> {
let [arg] = func.params.args.as_slice() else {
return None;
};
let widening =
crate::planning::define::preparation::direct_widening_column(arg, input_schema);
let (column, coerced_to_float64) = if let Some((raw, target)) = widening {
(raw.name.clone(), *target == DataType::Float64)
} else if kind == AggregateKind::Avg {
float_state_column_arg(arg)?
} else {
(direct_column_name(arg)?.to_string(), false)
};
let field = schema_field(input_schema, &column)?;
let data_type = widening.map_or(field.data_type(), |(_, target)| target);
let supported = match kind {
AggregateKind::BoolAnd | AggregateKind::BoolOr => {
matches!(data_type, DataType::Boolean)
}
AggregateKind::Avg if coerced_to_float64 => {
is_vm_numeric_accumulator_type(data_type)
}
AggregateKind::Avg => {
const DECIMAL128_REGISTER_MAX_PRECISION: u8 = 25;
is_vm_numeric_accumulator_type(data_type)
&& !matches!(
data_type,
DataType::Decimal128(precision, _)
if *precision > DECIMAL128_REGISTER_MAX_PRECISION
)
}
AggregateKind::Min | AggregateKind::Max => {
is_vm_numeric_accumulator_type(data_type)
|| crate::core::vm::is_temporal_word_type(data_type)
|| (widening.is_none()
&& crate::core::vm::is_retained_row_extrema_type(data_type))
}
AggregateKind::Additive => is_vm_numeric_accumulator_type(data_type),
_ => false,
};
if !supported {
return None;
}
let native_type = slot_value_type(data_type);
let as_float = coerced_to_float64
|| matches!(kind, AggregateKind::Additive | AggregateKind::Avg)
&& native_type == SlotValueType::Float32
|| kind == AggregateKind::Avg && data_type.is_integer();
let value_type = if as_float {
SlotValueType::Float64
} else {
native_type
};
Some(RegisterAggregateRecipe::Algebraic {
kind,
input: TypedAggregateInput {
column,
value_type,
scale: if as_float {
0
} else {
decimal_scale(data_type)
},
nullable: field.is_nullable(),
as_float,
},
track_nonnull: !matches!(kind, AggregateKind::Avg),
})
}
fn variance_recipe(
func: &AggregateFunction,
input_schema: &DFSchema,
projection: VarianceProjection,
) -> Option<RegisterAggregateRecipe> {
let [arg] = func.params.args.as_slice() else {
return None;
};
let input = float_input(arg, input_schema)?;
Some(RegisterAggregateRecipe::Variance { input, projection })
}
fn float_input(expr: &Expr, input_schema: &DFSchema) -> Option<TypedAggregateInput> {
let (column, _) = float_state_column_arg(expr)?;
let field = schema_field(input_schema, &column)?;
if !is_vm_numeric_accumulator_type(field.data_type()) {
return None;
}
Some(TypedAggregateInput {
column,
value_type: SlotValueType::Float64,
scale: 0,
nullable: field.is_nullable(),
as_float: true,
})
}
fn schema_field<'a>(
schema: &'a DFSchema,
column: &str,
) -> Option<&'a datafusion::arrow::datatypes::FieldRef> {
schema
.fields()
.iter()
.find(|field| field.name().eq_ignore_ascii_case(column))
}
fn slot_value_type(data_type: &DataType) -> SlotValueType {
match data_type {
DataType::Decimal128(..) => SlotValueType::Decimal128,
DataType::UInt64 => SlotValueType::UInt64,
DataType::Float32 => SlotValueType::Float32,
DataType::Float64 => SlotValueType::Float64,
ty if crate::core::vm::is_retained_row_extrema_type(ty) => {
SlotValueType::RetainedRow
}
_ => SlotValueType::Int64,
}
}
fn decimal_scale(data_type: &DataType) -> i8 {
match data_type {
DataType::Decimal128(_, scale) => *scale,
_ => 0,
}
}
fn float_state_column_arg(expr: &Expr) -> Option<(String, bool)> {
match expr {
Expr::Column(column) => Some((column.name.clone(), false)),
Expr::Alias(alias) => float_state_column_arg(&alias.expr),
Expr::Cast(cast) if cast.field.data_type() == &DataType::Float64 => {
direct_column_name(&cast.expr).map(|name| (name.to_string(), true))
}
_ => None,
}
}
fn is_vm_numeric_accumulator_type(data_type: &DataType) -> bool {
data_type.is_integer()
|| matches!(
data_type,
DataType::Float32 | DataType::Float64 | DataType::Decimal128(..)
)
}
fn is_predictable_count(
func: &AggregateFunction,
operation: Option<CanonicalOperation>,
) -> bool {
matches!(operation, Some(CanonicalOperation::Count))
&& is_plain_aggregate(func)
&& count_args_increment_every_row(&func.params.args)
}
fn accumulator_input_mode(operation: Option<CanonicalOperation>) -> AccumulatorInputMode {
match operation {
Some(CanonicalOperation::Navigation(VmNavigationFunctionFamily::Prev)) => {
AccumulatorInputMode::PreviousValue
}
_ => AccumulatorInputMode::Batch,
}
}
#[allow(deprecated)]
fn count_args_increment_every_row(args: &[Expr]) -> bool {
args.iter().all(|arg| {
matches!(arg, Expr::Literal(value, _) if !value.is_null())
|| matches!(arg, Expr::Wildcard { .. })
})
}
pub(crate) fn value_domain_for_type(
data_type: &DataType,
) -> Option<NavigationValueDomain> {
match data_type {
DataType::Boolean
| DataType::Int8
| DataType::Int16
| DataType::Int32
| DataType::Int64
| DataType::UInt8
| DataType::UInt16
| DataType::UInt32
| DataType::UInt64
| DataType::Float32
| DataType::Float64 => Some(NavigationValueDomain::Primitive),
DataType::Decimal128(_, _) => Some(NavigationValueDomain::Decimal128),
data_type if crate::core::vm::is_temporal_word_type(data_type) => {
Some(NavigationValueDomain::Primitive)
}
_ => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum NavigationRequestKind {
First {
offset: usize,
default_value: Option<ScalarValue>,
},
LastOffset {
depth: usize,
default_value: Option<ScalarValue>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct NavigationRequest {
pub(super) aggregate_id: AggregateId,
pub(super) scope: Option<LogicalSymbolId>,
pub(super) column: String,
pub(super) domain: NavigationValueDomain,
pub(super) kind: NavigationRequestKind,
}
impl NavigationRequest {
pub(super) fn interpret(
aggregate: &LogicalManagedAggregate,
program: &LogicalMatchProgram,
family: VmNavigationFunctionFamily,
input_schema: &DFSchema,
) -> Option<Self> {
use VmNavigationFunctionFamily::{First, Last, Prev};
let classifier_mask = aggregate
.symbol()
.map(|id| classifier_bits_col_name(program.symbols()[id.index()].name()));
let supported_mask =
|arg: &Expr| is_internal_navigation_mask_arg(arg, classifier_mask.as_deref());
let (column_arg, offset, is_first, default) =
match (family, aggregate.func().params.args.as_slice()) {
(First | Last, [column]) => (column, 0, family == First, None),
(
First | Last,
[column, Expr::Literal(ScalarValue::UInt64(Some(offset)), _)],
) => (column, *offset, family == First, None),
(
Prev,
[
column,
Expr::Literal(ScalarValue::UInt64(Some(offset)), _),
Expr::Literal(default, _),
mask,
valid,
],
) if supported_mask(mask) && supported_mask(valid) => {
(column, *offset, false, Some(default))
}
(
Prev,
[
column,
Expr::Literal(ScalarValue::UInt64(Some(0)), _),
Expr::Literal(default, _),
mask,
valid,
Expr::Literal(ScalarValue::Boolean(Some(is_first)), _),
Expr::Literal(ScalarValue::UInt64(Some(offset)), _),
],
) if supported_mask(mask) && supported_mask(valid) => {
(column, *offset, *is_first, Some(default))
}
_ => return None,
};
let offset = usize::try_from(offset).ok()?;
if offset
> if is_first {
MAX_FIRST_OFFSET
} else {
MAX_PREV_DEPTH
}
{
return None;
}
let raw_column = direct_column_name(column_arg)?;
let (column, data_type, domain) = if raw_column
.eq_ignore_ascii_case(MatchMetadataColumn::Classifier.as_ref())
{
(
MatchMetadataColumn::Classifier.as_ref().to_string(),
DataType::Utf8,
NavigationValueDomain::Classifier,
)
} else {
let data_type = schema_field(input_schema, raw_column)?.data_type().clone();
let domain = value_domain_for_type(&data_type)?;
(raw_column.to_string(), data_type, domain)
};
let default_value = match default {
Some(value) if !value.is_null() => Some(value.cast_to(&data_type).ok()?),
_ => None,
};
let kind = if is_first {
NavigationRequestKind::First {
offset,
default_value,
}
} else {
NavigationRequestKind::LastOffset {
depth: offset,
default_value,
}
};
Some(Self {
aggregate_id: aggregate.id(),
scope: aggregate.symbol(),
column,
domain,
kind,
})
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use datafusion::arrow::datatypes::{Field, Schema};
use datafusion::functions_aggregate::count::count;
use datafusion::logical_expr::expr::AggregateFunctionParams;
use datafusion::logical_expr::{AggregateUDF, col, lit};
use crate::planning::expressions::test_support::SameNameCustomAggregate;
use super::*;
fn function(func: Arc<AggregateUDF>) -> AggregateFunction {
AggregateFunction {
func,
params: AggregateFunctionParams {
args: vec![],
distinct: false,
filter: None,
order_by: vec![],
null_treatment: None,
},
}
}
fn aggregate_function(expr: Expr) -> AggregateFunction {
let Expr::AggregateFunction(func) = expr else {
panic!("expected aggregate function")
};
func
}
#[test]
fn leading_first_proof_rejects_nullable_and_differently_labeled_starts() {
use crate::core::RepetitionQuantifier::{AtMostOne, OneOrMore};
let a = Pattern::Symbol(Symbol::Named("A".into()));
let b = Pattern::Symbol(Symbol::Named("B".into()));
for pattern in [
Pattern::Concat(vec![a.clone(), b.clone(), a.clone()]),
Pattern::Repetition(Box::new(a.clone()), OneOrMore),
Pattern::Alternation(vec![
a.clone(),
Pattern::Concat(vec![a.clone(), b.clone()]),
]),
] {
assert_eq!(leading_symbol(&pattern), Some("A"));
}
for pattern in [
Pattern::Concat(vec![
Pattern::Repetition(Box::new(a.clone()), AtMostOne),
b.clone(),
]),
Pattern::Alternation(vec![a, b]),
Pattern::Concat(vec![]),
] {
assert_eq!(leading_symbol(&pattern), None);
}
}
#[test]
fn leading_symbol_handles_deep_left_nested_alternation() {
let a = Pattern::Symbol(Symbol::Named("A".into()));
let mut pattern = a.clone();
for _ in 0..48 {
pattern = Pattern::Alternation(vec![pattern, a.clone()]);
}
assert_eq!(leading_symbol(&pattern), Some("A"));
}
#[test]
fn canonical_operation_table_uses_exact_udaf_identity() {
use crate::functions::udaf::{
mr_first_offset_udaf, mr_first_udaf, mr_last_offset_udaf, mr_last_udaf,
mr_prev_udaf,
};
use AggregateKind as Kind;
use CanonicalOperation as Operation;
use StatisticalPopulation::{Population, Sample};
use VarianceProjection::{Stddev, Variance};
use VmNavigationFunctionFamily::{First, Last, Prev};
use datafusion::functions_aggregate::{
average::avg_udaf,
bool_and_or::{bool_and_udaf, bool_or_udaf},
count::count_udaf,
min_max::{max_udaf, min_udaf},
stddev::{stddev_pop_udaf, stddev_udaf},
sum::sum_udaf,
variance::{var_pop_udaf, var_samp_udaf},
};
let cases = vec![
(count_udaf(), Operation::Count),
(sum_udaf(), Operation::Algebraic(Kind::Additive)),
(min_udaf(), Operation::Algebraic(Kind::Min)),
(max_udaf(), Operation::Algebraic(Kind::Max)),
(avg_udaf(), Operation::Algebraic(Kind::Avg)),
(bool_and_udaf(), Operation::Algebraic(Kind::BoolAnd)),
(bool_or_udaf(), Operation::Algebraic(Kind::BoolOr)),
(stddev_udaf(), Operation::Variance(Stddev(Sample))),
(stddev_pop_udaf(), Operation::Variance(Stddev(Population))),
(var_samp_udaf(), Operation::Variance(Variance(Sample))),
(var_pop_udaf(), Operation::Variance(Variance(Population))),
(mr_first_udaf(), Operation::Navigation(First)),
(mr_first_offset_udaf(), Operation::Navigation(First)),
(mr_last_udaf(), Operation::Navigation(Last)),
(mr_last_offset_udaf(), Operation::Navigation(Last)),
(mr_prev_udaf(), Operation::Navigation(Prev)),
];
for (udaf, expected) in cases {
assert_eq!(
canonical_operation(&function(udaf.clone())),
Some(expected),
"{} must retain its exact operation recipe",
udaf.name()
);
let custom_name = Box::leak(udaf.name().to_string().into_boxed_str());
let custom = Arc::new(AggregateUDF::new_from_impl(SameNameCustomAggregate {
name: custom_name,
}));
assert_eq!(
canonical_operation(&function(custom)),
None,
"a custom {} implementation must not inherit register semantics",
udaf.name()
);
}
}
#[test]
fn bivariate_statistics_regression_and_integer_bits_retain_upstream_accumulators() {
use datafusion::functions_aggregate::{
bit_and_or_xor, correlation, covariance, regr,
};
for udaf in [
covariance::covar_pop_udaf(),
correlation::corr_udaf(),
regr::regr_slope_udaf(),
bit_and_or_xor::bit_xor_udaf(),
] {
assert_eq!(
canonical_operation(&function(udaf.clone())),
None,
"{}",
udaf.name()
);
}
}
#[test]
fn malformed_variance_arity_has_no_recipe() {
let schema = DFSchema::try_from(Arc::new(Schema::new(vec![Field::new(
"value",
DataType::Float32,
true,
)])))
.unwrap();
let mut malformed = aggregate_function(
datafusion::functions_aggregate::variance::var_pop(col("value")),
);
malformed.params.args.push(col("value"));
assert_eq!(
variance_recipe(
&malformed,
&schema,
VarianceProjection::Variance(StatisticalPopulation::Population)
),
None
);
}
#[test]
fn temporal_recipes_use_signed_words_for_extrema_only() {
use datafusion::arrow::datatypes::TimeUnit;
let mut types = vec![
DataType::Date32,
DataType::Date64,
DataType::Time32(TimeUnit::Second),
DataType::Time32(TimeUnit::Millisecond),
DataType::Time64(TimeUnit::Microsecond),
DataType::Time64(TimeUnit::Nanosecond),
];
for unit in [
TimeUnit::Second,
TimeUnit::Millisecond,
TimeUnit::Microsecond,
TimeUnit::Nanosecond,
] {
types.push(DataType::Duration(unit));
types.push(DataType::Timestamp(unit, Some("Europe/Berlin".into())));
}
let function = aggregate_function(datafusion::functions_aggregate::min_max::min(
col("value"),
));
let schema = |data_type| {
DFSchema::try_from(Arc::new(Schema::new(vec![Field::new(
"value", data_type, true,
)])))
.unwrap()
};
let expected = |kind| {
Some(RegisterAggregateRecipe::Algebraic {
kind,
input: TypedAggregateInput {
column: "value".into(),
value_type: SlotValueType::Int64,
scale: 0,
nullable: true,
as_float: false,
},
track_nonnull: true,
})
};
for data_type in types {
assert_eq!(
algebraic_recipe(&function, &schema(data_type), AggregateKind::Min),
expected(AggregateKind::Min)
);
}
for data_type in [
DataType::Date32,
DataType::Timestamp(TimeUnit::Nanosecond, Some("Europe/Berlin".into())),
] {
let schema = schema(data_type);
assert_eq!(
algebraic_recipe(&function, &schema, AggregateKind::Max),
expected(AggregateKind::Max)
);
for kind in [AggregateKind::Additive, AggregateKind::Avg] {
assert_eq!(algebraic_recipe(&function, &schema, kind), None);
}
}
}
#[test]
fn string_and_binary_min_max_recipes_use_retained_row_state() {
let function = aggregate_function(datafusion::functions_aggregate::min_max::min(
col("value"),
));
for data_type in [
DataType::Utf8,
DataType::LargeUtf8,
DataType::Utf8View,
DataType::Binary,
DataType::LargeBinary,
DataType::BinaryView,
DataType::FixedSizeBinary(8),
DataType::FixedSizeBinary(32),
] {
let schema = DFSchema::try_from(Arc::new(Schema::new(vec![Field::new(
"value", data_type, true,
)])))
.unwrap();
for kind in [AggregateKind::Min, AggregateKind::Max] {
assert_eq!(
algebraic_recipe(&function, &schema, kind),
Some(RegisterAggregateRecipe::Algebraic {
kind,
input: TypedAggregateInput {
column: "value".to_string(),
value_type: SlotValueType::RetainedRow,
scale: 0,
nullable: true,
as_float: false,
},
track_nonnull: true,
})
);
}
for kind in [AggregateKind::Additive, AggregateKind::Avg] {
assert_eq!(algebraic_recipe(&function, &schema, kind), None);
}
}
}
#[test]
fn operation_identity_drives_runtime_side_facts() {
for (arg, predictable) in [
(lit(1_i64), true),
(lit(ScalarValue::Null), false),
(col("value"), false),
] {
let count = aggregate_function(count(arg));
assert_eq!(
is_predictable_count(&count, canonical_operation(&count)),
predictable
);
}
assert_eq!(
accumulator_input_mode(Some(CanonicalOperation::Navigation(
VmNavigationFunctionFamily::First,
))),
AccumulatorInputMode::Batch
);
assert_eq!(
accumulator_input_mode(Some(CanonicalOperation::Navigation(
VmNavigationFunctionFamily::Prev,
))),
AccumulatorInputMode::PreviousValue
);
assert_eq!(
accumulator_input_mode(Some(CanonicalOperation::Count)),
AccumulatorInputMode::Batch
);
let cast_mask = Expr::Cast(datafusion::logical_expr::expr::Cast::new(
Box::new(col(MatchMetadataColumn::Classifier.as_ref())),
DataType::Utf8,
));
assert!(is_internal_navigation_mask_arg(&cast_mask, None));
}
}