datafusion-match-recognize 0.56.1

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
Documentation
// Licensed 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.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

//! Primitive aggregates evaluated over rows assigned to the winning match.
use super::{LogicalSelectedMatchSummary, assigned_classifier};
use crate::core::is_reserved_internal_column_name;
use datafusion::arrow::datatypes::DataType;
use datafusion::common::{Column, DFSchema};
use datafusion::functions_aggregate::{average, count, min_max, sum};
use datafusion::logical_expr::{AggregateUDF, Expr, ExprSchemable};
use std::sync::Arc;

/// Reduction over an original primitive input column in match order.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SelectedReductionOp {
    /// Number of selected, non-NULL values.
    Count,
    /// Sum of the non-NULL values, with DataFusion's aggregate widening.
    Sum,
    /// Least non-NULL value.
    Min,
    /// Greatest non-NULL value.
    Max,
    /// Arithmetic mean of the non-NULL values.
    Avg,
}

impl SelectedReductionOp {
    fn from_udaf(func: &AggregateUDF) -> Option<Self> {
        let (builtin, op) = match func.name() {
            "count" => (count::count_udaf(), Self::Count),
            "sum" => (sum::sum_udaf(), Self::Sum),
            "min" => (min_max::min_udaf(), Self::Min),
            "max" => (min_max::max_udaf(), Self::Max),
            "avg" => (average::avg_udaf(), Self::Avg),
            _ => return None,
        };
        Arc::ptr_eq(func.inner(), builtin.inner()).then_some(op)
    }

    /// Whether the typed winner reducer implements this exact input and result.
    pub fn accepts(self, input: &DataType, output: &DataType) -> bool {
        use DataType::{Decimal128, Float32, Float64, Int32, Int64};
        if !matches!(input, Int32 | Int64 | Float32 | Float64 | Decimal128(..)) {
            return false;
        }
        match self {
            Self::Count => *output == Int64,
            Self::Min | Self::Max => {
                (matches!(input, Int32 | Int64 | Float64 | Decimal128(..))
                    && input == output)
                    || (*input == Int32 && *output == Int64)
                    || (matches!(input, Int32 | Int64 | Float32 | Decimal128(..))
                        && *output == Float64)
            }
            Self::Sum => match input {
                Int32 | Int64 => matches!(output, Int64 | Float64),
                Float32 | Float64 => *output == Float64,
                Decimal128(..) => {
                    *output == Float64
                        || sum::sum_udaf()
                            .return_type(std::slice::from_ref(input))
                            .is_ok_and(|ty| ty == *output)
                }
                _ => false,
            },
            Self::Avg => match input {
                // DataFusion widens the intermediate to Decimal256 above p=25.
                Decimal128(p, s) => {
                    *output == Float64
                        || (*p <= 25
                            && *s >= 0
                            && average::avg_udaf()
                                .return_type(std::slice::from_ref(input))
                                .is_ok_and(|ty| ty == *output))
                }
                _ => *output == Float64,
            },
        }
    }

    fn input_column_and_cast<'a>(
        self,
        expr: &'a Expr,
        schema: &DFSchema,
    ) -> Option<(&'a Column, Option<&'a DataType>)> {
        let (arg, cast) = match expr {
            Expr::Cast(cast) => (cast.expr.as_ref(), Some(cast.field.data_type())),
            _ => (expr, None),
        };
        let Expr::Column(column) = arg else {
            return None;
        };
        let input = schema
            .field(schema.maybe_index_of_column(column)?)
            .data_type();
        // Infallible widening casts (inserted by coercion or written explicitly)
        // preserve NULLs and match the direct typed reducer's conversion.
        // All other casts retain their ordinary evaluation and failure semantics.
        match (self, input, cast) {
            (_, _, None)
            | (
                Self::Sum | Self::Min | Self::Max | Self::Avg,
                DataType::Int32,
                Some(DataType::Int64),
            )
            | (
                Self::Sum | Self::Min | Self::Max | Self::Avg,
                DataType::Int32
                | DataType::Int64
                | DataType::Float32
                | DataType::Decimal128(..),
                Some(DataType::Float64),
            ) => Some((column, cast)),
            _ => None,
        }
    }

    fn input_column<'a>(self, expr: &'a Expr, schema: &DFSchema) -> Option<&'a Column> {
        self.input_column_and_cast(expr, schema)
            .map(|(column, _)| column)
    }
}

/// Bound SQL shape for a primitive selected-match aggregate.
pub struct SelectedReduction<'a> {
    /// Original physical input value, before an aggregate's implicit widening.
    pub column: &'a Column,
    /// Built-in reduction to apply.
    pub op: SelectedReductionOp,
    /// Canonical classifier mask, or all assigned rows.
    pub classifier: Option<&'a str>,
}

impl LogicalSelectedMatchSummary {
    /// Recognize a complete typed reduction against the private selected-row schema.
    pub fn selected_reduction(&self, schema: &DFSchema) -> Option<SelectedReduction<'_>> {
        let aggregate = self.aggregate();
        let params = &aggregate.params;
        if params.distinct
            || params.null_treatment.is_some()
            || !params.order_by.is_empty()
        {
            return None;
        }
        let [arg] = params.args.as_slice() else {
            return None;
        };
        let classifier = assigned_classifier(params.filter.as_deref()?)?;
        let op = SelectedReductionOp::from_udaf(&aggregate.func)?;
        let (column, cast) = op.input_column_and_cast(arg, schema)?;
        if is_reserved_internal_column_name(&column.name) {
            return None;
        }
        let input = schema
            .field(schema.maybe_index_of_column(column)?)
            .data_type();
        let result = self.field().arrow_field();
        (op.accepts(input, result.data_type())
            && cast.is_none_or(|cast_ty| op.accepts(cast_ty, result.data_type()))
            && result.is_nullable() == (op != SelectedReductionOp::Count))
            .then_some(SelectedReduction {
                column,
                op,
                classifier,
            })
    }

    /// Check the DEFINE register's function, scope and coerced input against this
    /// reduction. Prepared widening casts are identified by their defining expression.
    pub fn matches_managed_reduction(
        &self,
        managed: &datafusion::logical_expr::expr::AggregateFunction,
        symbol: Option<&str>,
        matcher: &crate::planning::logical::MatchRecognize,
    ) -> bool {
        let schema = matcher.input().schema();
        let Some(reduction) = self.selected_reduction(schema) else {
            return false;
        };
        let params = &managed.params;
        let expected = symbol.map(crate::core::classifier_bits_col_name);
        if reduction.classifier != expected.as_deref()
            || !Arc::ptr_eq(managed.func.inner(), self.aggregate().func.inner())
            || params.filter.is_some()
            || params.distinct
            || params.null_treatment.is_some()
            || !params.order_by.is_empty()
        {
            return false;
        }
        if Expr::AggregateFunction(managed.clone())
            .get_type(schema)
            .ok()
            .as_ref()
            != Some(self.field().arrow_field().data_type())
        {
            return false;
        }
        let [arg] = params.args.as_slice() else {
            return false;
        };
        // A rewritten projection may preserve the alias while changing its value,
        // or may change the public column while retaining the old prepared value.
        // Trace both operands through the actual projections to the same slot.
        reduction.shares_input(arg, matcher.input()) == Some(true)
    }
}

impl SelectedReduction<'_> {
    fn shares_input(
        &self,
        managed: &Expr,
        mut input: &datafusion::logical_expr::LogicalPlan,
    ) -> Option<bool> {
        use datafusion::logical_expr::LogicalPlan;
        let mut value = input.schema().maybe_index_of_column(self.column)?;
        let mut register = input
            .schema()
            .maybe_index_of_column(self.op.input_column(managed, input.schema())?)?;
        while value != register {
            match input {
                LogicalPlan::SubqueryAlias(alias) => input = &alias.input,
                LogicalPlan::Projection(projection) => {
                    input = &projection.input;
                    let child_slot = |ordinal: usize| {
                        let expr = projection.expr.get(ordinal)?;
                        let expr = if let Expr::Alias(alias) = expr {
                            alias.expr.as_ref()
                        } else {
                            expr
                        };
                        input.schema().maybe_index_of_column(
                            self.op.input_column(expr, input.schema())?,
                        )
                    };
                    value = child_slot(value)?;
                    register = child_slot(register)?;
                }
                _ => return Some(false),
            }
        }
        Some(true)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use datafusion::common::Result;
    use datafusion::logical_expr::{LogicalPlanBuilder, cast, col, lit};

    #[test]
    fn register_widening_requires_the_same_projected_input() -> Result<()> {
        let stored = col("__mr_expr_0");
        let value = Column::from_name("v");
        let reduction = SelectedReduction {
            column: &value,
            op: SelectedReductionOp::Sum,
            classifier: None,
        };
        for (visible, prepared, shares) in [
            (col("column1"), col("column1"), true),
            (col("column1"), col("column2"), false),
            (col("column1") + lit(1_i32), col("column1"), false),
        ] {
            let input = LogicalPlanBuilder::values(vec![vec![lit(2_i32), lit(3_i32)]])?
                .project(vec![
                    visible.alias("v"),
                    cast(prepared, DataType::Int64).alias("__mr_expr_0"),
                ])?
                .build()?;
            assert_eq!(
                reduction.shares_input(&stored, &input) == Some(true),
                shares
            );
        }
        Ok(())
    }

    #[test]
    fn widening_casts_accept_float64_and_reject_mismatched_managed_types() -> Result<()> {
        use crate::core::MatchSummaryField;
        use datafusion::arrow::datatypes::Field;
        use datafusion::common::ScalarValue;
        use datafusion::logical_expr::expr::{
            AggregateFunction, AggregateFunctionParams,
        };

        let dec = DataType::Decimal128(15, 2);
        for op in [
            SelectedReductionOp::Avg,
            SelectedReductionOp::Sum,
            SelectedReductionOp::Min,
            SelectedReductionOp::Max,
        ] {
            assert!(op.accepts(&dec, &DataType::Float64));
            assert!(op.accepts(&DataType::Float32, &DataType::Float64));
            assert!(op.accepts(&DataType::Int32, &DataType::Float64));
            assert!(op.accepts(&DataType::Int64, &DataType::Float64));
        }
        for op in [
            SelectedReductionOp::Sum,
            SelectedReductionOp::Min,
            SelectedReductionOp::Max,
        ] {
            assert!(op.accepts(&DataType::Int32, &DataType::Int64));
        }
        assert!(!SelectedReductionOp::Avg.accepts(&DataType::Int32, &DataType::Int64));
        assert!(
            !SelectedReductionOp::Sum.accepts(&DataType::Float32, &DataType::Float32)
        );
        assert!(
            !SelectedReductionOp::Min.accepts(&DataType::Float32, &DataType::Float32)
        );
        assert!(SelectedReductionOp::Count.accepts(&DataType::Float32, &DataType::Int64));

        // Selected AVG(CAST(d AS Float64)) must accept Decimal128 input and trace
        // through a projected __mr_expr_0 = CAST(d AS Float64).
        let input = LogicalPlanBuilder::values(vec![vec![lit(
            ScalarValue::Decimal128(Some(1250), 15, 2),
        )]])?
        .project(vec![
            col("column1").alias("d"),
            cast(col("column1"), DataType::Float64).alias("__mr_expr_0"),
        ])?
        .build()?;
        let schema = input.schema();
        let filter = Some(Box::new(super::super::is_matched_expr()));
        let avg_cast_agg = AggregateFunction {
            func: average::avg_udaf(),
            params: AggregateFunctionParams {
                args: vec![cast(col("d"), DataType::Float64)],
                distinct: false,
                filter,
                order_by: vec![],
                null_treatment: None,
            },
        };
        let summary = LogicalSelectedMatchSummary::new(
            MatchSummaryField::new(
                0,
                Arc::new(Field::new("avg_d", DataType::Float64, true)),
            ),
            avg_cast_agg,
        );
        let reduction = summary
            .selected_reduction(schema)
            .expect("AVG(CAST(Decimal128 AS Float64)) should be selected");
        assert_eq!(reduction.column.name, "d");
        assert_eq!(reduction.op, SelectedReductionOp::Avg);
        assert_eq!(
            reduction.shares_input(&col("__mr_expr_0"), &input),
            Some(true)
        );
        // Mismatched managed aggregate type (Decimal128 vs Float64) must differ.
        let managed_dec = AggregateFunction {
            func: average::avg_udaf(),
            params: AggregateFunctionParams {
                args: vec![col("d")],
                distinct: false,
                filter: None,
                order_by: vec![],
                null_treatment: None,
            },
        };
        let managed_f64 = AggregateFunction {
            func: average::avg_udaf(),
            params: AggregateFunctionParams {
                args: vec![col("__mr_expr_0")],
                distinct: false,
                filter: None,
                order_by: vec![],
                null_treatment: None,
            },
        };
        assert_ne!(
            Expr::AggregateFunction(managed_dec).get_type(schema)?,
            DataType::Float64
        );
        assert_eq!(
            Expr::AggregateFunction(managed_f64).get_type(schema)?,
            DataType::Float64
        );
        Ok(())
    }
}