datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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.

//! Algebraic folding for `ONE ROW PER MATCH` measure aggregates.

use datafusion::arrow::datatypes::DataType;
use datafusion::common::float_semantics::has_float_leaf;
use datafusion::common::tree_node::{Transformed, TransformedResult, TreeNode};
use datafusion::common::{DFSchema, Result};
use datafusion::logical_expr::{
    Expr, ExprSchemable, LogicalPlan, WindowFunctionDefinition, expr::Case, lit,
};
use datafusion_optimizer::analyzer::type_coercion::TypeCoercionRewriter;

use crate::core::is_reserved_internal_column_name;
use crate::planning::NamedExpr;
use crate::planning::logical::{
    SelectedReductionOp, assigned_classifier, is_matched_expr, selected_row_filter_expr,
    sequence_sort_expr,
};
use crate::planning::type_validation::can_have_nulls_outside_bitmap;

/// Fold counts of required input columns and reuse exact partition values
/// before choosing the complete summary route.
/// Computed keys have already been materialized and rebased, so this never
/// mistakes an input to a noninjective key expression for the key itself.
pub(crate) fn simplify_one_row_measures(
    measures: &mut [NamedExpr],
    partition_by: &[Expr],
    define_windows: &[Expr],
    input: &LogicalPlan,
    schema: &DFSchema,
    matches_are_nonempty: bool,
) -> Result<()> {
    let input_schema = input.schema();
    // Pruning a computed column could suppress its SQL error or volatile call.
    // A relation alias only renames the underlying stored columns.
    let mut source = input;
    while let LogicalPlan::SubqueryAlias(alias) = source {
        source = &alias.input;
    }
    let stored_columns = matches!(source, LogicalPlan::TableScan(scan)
        if scan.source.table_type() == datafusion::logical_expr::TableType::Base
            && scan.source.get_logical_plan().is_none());
    let classified = is_matched_expr();
    let edge_filter = selected_row_filter_expr();
    let first = datafusion_functions_aggregate::first_last::first_value_udaf();
    let last = datafusion_functions_aggregate::first_last::last_value_udaf();
    let count = datafusion_functions_aggregate::count::count_udaf();
    // A DEFINE count may already own a register for this input and classifier.
    // Keep the argument so physical planning can verify and reuse that register.
    let define_counts = define_windows
        .iter()
        .filter_map(|expr| {
            let Expr::WindowFunction(window) = expr else {
                return None;
            };
            let WindowFunctionDefinition::AggregateUDF(udaf) = &window.fun else {
                return None;
            };
            let [Expr::Column(column)] = window.params.args.as_slice() else {
                return None;
            };
            let index = input_schema.maybe_index_of_column(column)?;
            (std::sync::Arc::ptr_eq(udaf.inner(), count.inner())
                && !window.params.distinct
                && window.params.null_treatment.is_none()
                && SelectedReductionOp::Count
                    .accepts(input_schema.field(index).data_type(), &DataType::Int64))
            .then_some((
                index,
                window.params.filter.as_deref().unwrap_or(&classified),
            ))
        })
        .collect::<Vec<_>>();
    let min_max = [
        datafusion_functions_aggregate::min_max::min_udaf(),
        datafusion_functions_aggregate::min_max::max_udaf(),
    ];
    let boolean = [
        datafusion_functions_aggregate::bool_and_or::bool_and_udaf(),
        datafusion_functions_aggregate::bool_and_or::bool_or_udaf(),
    ];
    let bitwise = [
        datafusion_functions_aggregate::bit_and_or_xor::bit_and_udaf(),
        datafusion_functions_aggregate::bit_and_or_xor::bit_or_udaf(),
    ];
    for measure in measures {
        measure.expr = measure
            .expr
            .clone()
            .transform_up(|node| {
                let Expr::AggregateFunction(aggregate) = &node else {
                    return Ok(Transformed::no(node));
                };
                let [argument] = aggregate.params.args.as_slice() else {
                    return Ok(Transformed::no(node));
                };
                if argument.is_volatile()
                    || aggregate.params.distinct
                    || aggregate.params.null_treatment.is_some()
                {
                    return Ok(Transformed::no(node));
                }
                let filter = aggregate.params.filter.as_deref();
                let counts_assigned_rows =
                    std::sync::Arc::ptr_eq(aggregate.func.inner(), count.inner())
                        && aggregate.params.order_by.is_empty()
                        && filter.and_then(assigned_classifier).is_some_and(|scope| {
                            scope.is_none_or(|name| {
                                schema.has_column_with_unqualified_name(name)
                            })
                        });
                if counts_assigned_rows
                    && let Expr::Column(column) = argument
                    && let Some(index) = input_schema.maybe_index_of_column(column)
                    && filter
                        .is_some_and(|filter| define_counts.contains(&(index, filter)))
                {
                    return Ok(Transformed::no(node));
                }
                let partition_key = partition_by.iter().find(|key| {
                    if *key == argument {
                        return true;
                    }
                    let (Expr::Column(left), Expr::Column(right)) = (key, argument)
                    else {
                        return false;
                    };
                    // Qualified and unqualified spellings must bind to the
                    // same field, rather than merely sharing a column name.
                    matches!(
                        (schema.index_of_column(left), schema.index_of_column(right)),
                        (Ok(left), Ok(right)) if left == right
                    )
                });
                // Count only assigned rows. A required input can still contain
                // logical NULLs via Arrow dictionary or run-end encoding.
                let required_count_column = || {
                    let Expr::Column(column) = argument else {
                        return None;
                    };
                    if !stored_columns
                        || !counts_assigned_rows
                        || is_reserved_internal_column_name(&column.name)
                    {
                        return None;
                    }
                    let field =
                        input_schema.field(input_schema.maybe_index_of_column(column)?);
                    (!field.is_nullable()
                        && !can_have_nulls_outside_bitmap(field.data_type()))
                    .then_some(argument)
                };
                let Some(key) = partition_key.or_else(required_count_column) else {
                    return Ok(Transformed::no(node));
                };
                let is_first = aggregate.func.as_ref() == first.as_ref();
                let is_last = aggregate.func.as_ref() == last.as_ref();
                let is_min_max = min_max
                    .iter()
                    .any(|function| aggregate.func.as_ref() == function.as_ref());
                let is_boolean = boolean
                    .iter()
                    .any(|function| aggregate.func.as_ref() == function.as_ref());
                let is_bitwise = bitwise
                    .iter()
                    .any(|function| aggregate.func.as_ref() == function.as_ref());
                // Bare ONE ROW scalar leaves lower to this simpler LAST form.
                let unqualified_edge = filter == Some(&edge_filter)
                    || (is_last && filter == Some(&classified));
                let replacement = if matches_are_nonempty
                    && (is_first || is_last)
                    && aggregate.params.order_by.as_slice() == [sequence_sort_expr()]
                    && unqualified_edge
                    && !has_float_leaf(&key.get_type(schema)?)
                {
                    // Float grouping identifies -0.0 and +0.0 while FIRST/LAST
                    // preserve the signed value, including inside nested keys.
                    key.clone()
                } else if matches_are_nonempty
                    && (is_min_max || is_boolean || is_bitwise)
                    && aggregate.params.order_by.is_empty()
                    && filter == Some(&classified)
                    // Bitwise coercion can preserve encoded integer types even
                    // though DataFusion's accumulator only supports raw integers.
                    && (!is_bitwise || key.get_type(schema)?.is_integer())
                    && (!is_min_max || {
                        let data_type = key.get_type(schema)?;
                        supports_partition_extrema(&data_type)
                            && !has_float_leaf(&data_type)
                    })
                {
                    // A whole, nonempty match repeats this exact partition key.
                    // These reductions return that value, including NULL for a
                    // NULL key. Float grouping can identify -0.0 and +0.0 while
                    // MIN/MAX distinguish them, including inside nested values.
                    key.clone()
                } else if counts_assigned_rows {
                    let mut rows = aggregate.clone();
                    rows.params.args = vec![lit(1_i64)];
                    // NULL is a valid partition key. Its rows still match, but
                    // COUNT(S.key) counts none of them, including absent symbols.
                    let rows = Expr::AggregateFunction(rows);
                    // Inspect the materialized input key before selected-row
                    // passthrough makes it nullable. Some Arrow types carry
                    // logical NULLs even when the input field is required.
                    if key.nullable(input_schema.as_ref())?
                        || can_have_nulls_outside_bitmap(
                            &key.get_type(input_schema.as_ref())?,
                        )
                    {
                        Expr::Case(Case::new(
                            None,
                            vec![(Box::new(key.clone().is_null()), Box::new(lit(0_i64)))],
                            Some(Box::new(rows)),
                        ))
                    } else {
                        rows
                    }
                } else {
                    return Ok(Transformed::no(node));
                };
                // This runs before DataFusion's analyzer. Invalid signatures
                // must survive so TypeCoercion reports them, and dictionary
                // coercion must not be mistaken for a wrapper-preserving fold.
                let Ok(coerced) = node
                    .clone()
                    .rewrite(&mut TypeCoercionRewriter::new(schema))
                    .data()
                else {
                    return Ok(Transformed::no(node));
                };
                let before = coerced.to_field(schema)?.1;
                let after = replacement.to_field(schema)?.1;
                if before.data_type() != after.data_type()
                    || before.metadata() != after.metadata()
                {
                    return Ok(Transformed::no(node));
                }
                Ok(Transformed::yes(replacement))
            })
            .data()?;
    }
    Ok(())
}

/// Mirror the scalar/container domains supported by DataFusion min_batch/max_batch.
/// Encodings and unsupported nested values must retain the aggregate, including
/// its coercion and execution errors, even when grouping repeats one value.
fn supports_partition_extrema(data_type: &DataType) -> bool {
    match data_type {
        DataType::List(field)
        | DataType::LargeList(field)
        | DataType::FixedSizeList(field, _) => {
            supports_partition_extrema_leaf(field.data_type())
        }
        DataType::Struct(fields) => fields.iter().all(|field| {
            // Struct comparison supports nested structs, but list comparison
            // invokes Arrow's scalar comparator and rejects nested containers.
            match field.data_type() {
                nested @ DataType::Struct(_) => supports_partition_extrema(nested),
                leaf => supports_partition_extrema_leaf(leaf),
            }
        }),
        other => supports_partition_extrema_leaf(other),
    }
}

fn supports_partition_extrema_leaf(data_type: &DataType) -> bool {
    use datafusion::arrow::datatypes::TimeUnit;
    matches!(
        data_type,
        DataType::Null
            | DataType::Boolean
            | DataType::Int8
            | DataType::Int16
            | DataType::Int32
            | DataType::Int64
            | DataType::UInt8
            | DataType::UInt16
            | DataType::UInt32
            | DataType::UInt64
            | DataType::Float16
            | DataType::Float32
            | DataType::Float64
            | DataType::Decimal32(_, _)
            | DataType::Decimal64(_, _)
            | DataType::Decimal128(_, _)
            | DataType::Decimal256(_, _)
            | DataType::Utf8
            | DataType::LargeUtf8
            | DataType::Utf8View
            | DataType::Binary
            | DataType::LargeBinary
            | DataType::BinaryView
            | DataType::FixedSizeBinary(_)
            | DataType::Timestamp(_, _)
            | DataType::Date32
            | DataType::Date64
            | DataType::Time32(TimeUnit::Second | TimeUnit::Millisecond)
            | DataType::Time64(TimeUnit::Microsecond | TimeUnit::Nanosecond)
            | DataType::Duration(_)
            | DataType::Interval(_)
    )
}