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.

//! MEASURES planning for MATCH_RECOGNIZE.
//!
//! Earlier lowering has already validated each expression and chosen the
//! DataFusion aggregate or window function that implements it. This module
//! admits complete `ONE ROW PER MATCH` summary programs for matcher-owned
//! finalization. Other programs add the required downstream Window nodes and,
//! for one-row output, group matcher rows by partition keys and match number.

mod simplify;
mod summaries;
#[cfg(test)]
mod tests;

pub(crate) use simplify::simplify_one_row_measures;
#[cfg(test)]
use summaries::SelectedMatchSummaryPlan;
pub(crate) use summaries::plan_selected_match_summaries;

use datafusion::common::Result;
use datafusion::common::tree_node::{Transformed, TransformedResult, TreeNode};
use datafusion::logical_expr::{
    Expr, ExprSchemable, LogicalPlan, LogicalPlanBuilder, WindowFunctionDefinition, col,
    expr::Case,
};

use crate::core::MatchMetadataColumn;
use crate::planning::NamedExpr;
use crate::planning::logical::is_matched_expr;
use crate::planning::logical::utils::{
    ExprBindings, guard_navigation_value, prepare_windows,
};

/// Every emitted row in an ordinary nonempty match has a classifier. Lowering
/// adds this exact filter to whole-match aggregates without a source FILTER.
/// Symbol-scoped measures carry their symbol mask; user FILTERs retain their
/// condition, including its SQL NULL semantics.
pub(crate) fn omit_classified_row_filter(measures: &mut [NamedExpr]) -> Result<()> {
    let classified = is_matched_expr();
    for measure in measures {
        measure.expr = measure
            .expr
            .clone()
            .transform_up(|mut expr| {
                if let Expr::WindowFunction(window) = &mut expr
                    && matches!(window.fun, WindowFunctionDefinition::AggregateUDF(_))
                    && window.params.filter.as_deref() == Some(&classified)
                {
                    window.params.filter = None;
                    return Ok(Transformed::yes(expr));
                }
                Ok(Transformed::no(expr))
            })
            .data()?;
    }
    Ok(())
}

/// Return whether a Window expression implements physical row-offset navigation
/// (`PREV` / `NEXT`) that requires synthetic halo buffer rows.
fn is_navigation_window_expr(expr: &Expr) -> bool {
    use crate::functions::udwf::{mr_next_udwf, mr_prev_udwf};

    let Expr::WindowFunction(window_func) = expr else {
        return false;
    };
    matches!(
        &window_func.fun,
        WindowFunctionDefinition::WindowUDF(udf)
            if udf.as_ref() == mr_prev_udwf().as_ref()
                || udf.as_ref() == mr_next_udwf().as_ref()
    )
}

/// Materialize matching windows at the current output stage.
pub(crate) fn apply_windows_and_rebase_measures(
    plan: LogicalPlan,
    mut measures: Vec<NamedExpr>,
    navigation: bool,
) -> Result<(LogicalPlan, Vec<NamedExpr>)> {
    let reserved = measures
        .iter()
        .map(|measure| measure.name.clone())
        .collect::<Vec<_>>();
    let (plan, _) = prepare_windows(
        plan,
        measures.iter_mut().map(|measure| &mut measure.expr),
        reserved.iter().map(String::as_str),
        |expr| is_navigation_window_expr(expr) == navigation,
    )?;
    Ok((plan, measures))
}

pub(crate) fn one_row_group_exprs(partition_by_exprs: &[Expr]) -> Vec<Expr> {
    partition_by_exprs
        .iter()
        .cloned()
        .chain(std::iter::once(col(
            MatchMetadataColumn::MatchNumber.as_ref()
        )))
        .collect()
}

/// Build the ordinary DataFusion aggregate, evaluating observable inputs only
/// on selected rows. This also covers FIRST/LAST leaves extracted from measures.
pub(crate) fn aggregate_selected_rows(
    plan: LogicalPlan,
    groups: Vec<Expr>,
    mut aggregates: Vec<Expr>,
) -> Result<LogicalPlan> {
    use crate::functions::udaf::{mr_next_udaf, mr_prev_udaf};

    for expr in &mut aggregates {
        let expr = match expr {
            Expr::Alias(alias) => alias.expr.as_mut(),
            other => other,
        };
        if let Expr::AggregateFunction(aggregate) = expr
            && (aggregate.func.as_ref() == mr_prev_udaf().as_ref()
                || aggregate.func.as_ref() == mr_next_udaf().as_ref())
        {
            // PREV/NEXT keep all rows for physical offsets and carry their
            // anchor mask in args[4], with no FILTER to guard eager evaluation.
            guard_navigation_value(
                &mut aggregate.params.args,
                Some(4),
                aggregate.func.as_ref() == mr_prev_udaf().as_ref(),
                plan.schema(),
            )?;
        }
    }
    let plan = prepare_filtered_inputs(
        plan,
        aggregates.iter_mut().filter_map(|expr| {
            let expr = match expr {
                Expr::Alias(alias) => alias.expr.as_mut(),
                other => other,
            };
            let Expr::AggregateFunction(aggregate) = expr else {
                return None;
            };
            Some((
                &mut aggregate.params.filter,
                &mut aggregate.params.args,
                &mut aggregate.params.order_by,
            ))
        }),
        &[],
    )?;
    LogicalPlanBuilder::from(plan)
        .aggregate(groups, aggregates)?
        .build()
}

/// DataFusion evaluates aggregate arguments and hard sort keys before FILTER.
/// Share each effective filter with CASE guards, so rejected rows cannot raise
/// scalar errors or invoke volatile calls. Leave discardable inputs unchanged.
/// Keep successfully foldable constants visible to literal-only UDAF arguments;
/// retain the expression so later folding uses the query's session settings.
/// Aggregate windows use the same preparation after their match rows exist.
pub(crate) fn prepare_filtered_inputs<'a>(
    mut plan: LogicalPlan,
    inputs: impl IntoIterator<
        Item = (
            &'a mut Option<Box<Expr>>,
            &'a mut Vec<Expr>,
            &'a mut Vec<datafusion::logical_expr::SortExpr>,
        ),
    >,
    reserved: &[String],
) -> Result<LogicalPlan> {
    let mut guards = None;
    let mut guarded = Vec::new();
    for (filter, args, order_by) in inputs {
        let Some(filter) = filter else {
            continue;
        };
        let values = args
            .iter_mut()
            .chain(order_by.iter_mut().map(|key| &mut key.expr))
            .filter(|value| {
                !crate::planning::expr_safety::can_discard_scalar(
                    value,
                    Some(plan.schema()),
                ) && crate::planning::bound_expr_lowering::simplified_literal(
                    value,
                    &Default::default(),
                )
                .is_none()
            })
            .collect::<Vec<_>>();
        if values.is_empty() {
            continue;
        }
        if !matches!(filter.as_ref(), Expr::Column(_)) {
            let guards = guards.get_or_insert_with(|| {
                ExprBindings::new(plan.schema(), reserved.iter().map(String::as_str))
            });
            **filter = Expr::Column(guards.register_occurrence((**filter).clone()));
        }
        guarded.push(((**filter).clone(), values));
    }
    if let Some(guards) = guards {
        plan = append_prepared(plan, &guards)?;
    }
    if !guarded.is_empty() {
        let mut values =
            ExprBindings::new(plan.schema(), reserved.iter().map(String::as_str));
        for (guard, inputs) in guarded {
            for input in inputs {
                let selected = Expr::Case(Case::new(
                    None,
                    vec![(Box::new(guard.clone()), Box::new(input.clone()))],
                    None,
                ));
                // CASE has no field metadata of its own. FIRST/LAST and
                // metadata-aware UDAFs must still see the argument's metadata.
                let metadata = input.metadata(plan.schema().as_ref())?;
                let selected = if metadata.is_empty() {
                    selected
                } else {
                    selected.alias_with_metadata(
                        input.schema_name().to_string(),
                        Some(metadata),
                    )
                };
                *input = Expr::Column(values.register_occurrence(selected));
            }
        }
        plan = append_prepared(plan, &values)?;
    }
    Ok(plan)
}

fn append_prepared(plan: LogicalPlan, bindings: &ExprBindings) -> Result<LogicalPlan> {
    let columns = plan.schema().columns().into_iter().map(Expr::Column);
    let outputs = columns
        .chain(bindings.aliased_expressions_from(0))
        .collect::<Vec<_>>();
    LogicalPlanBuilder::from(plan).project(outputs)?.build()
}

/// Reduce the matcher's row-level output to one row per match.
///
/// The returned expressions refer to columns produced by the new Aggregate node.
///
/// Scalar-to-aggregate wrapping is handled during bound-expression lowering, so this
/// function only creates the aggregate plan node.
pub(crate) fn apply_aggregate_and_rebase_measures(
    plan: LogicalPlan,
    measures_exprs: Vec<NamedExpr>,
    partition_by_exprs: &[Expr],
) -> Result<(LogicalPlan, Vec<NamedExpr>, Vec<Expr>)> {
    // Bound lowering has already wrapped scalar measures as aggregates.
    let group_exprs = one_row_group_exprs(partition_by_exprs);
    let mut bindings = ExprBindings::new(
        plan.schema(),
        measures_exprs.iter().map(|measure| measure.name.as_str()),
    );
    let groups = group_exprs
        .iter()
        .cloned()
        .map(|expr| bindings.bind(expr))
        .collect::<Vec<_>>();
    let group_binding_count = bindings.binding_count();
    let measures = measures_exprs
        .into_iter()
        .map(|measure| {
            let expr = measure
                .expr
                .unalias_nested()
                .data
                .transform_down(|node| {
                    if matches!(node, Expr::AggregateFunction(_)) {
                        let column = bindings.register_occurrence(node);
                        Ok(Transformed::yes(Expr::Column(column)))
                    } else {
                        Ok(Transformed::no(node))
                    }
                })
                .data()?;
            Ok(NamedExpr {
                expr: bindings.rebase_non_literal(&expr)?,
                name: measure.name,
            })
        })
        .collect::<Result<Vec<_>>>()?;
    let aggregates = bindings
        .aliased_expressions_from(group_binding_count)
        .collect();
    let plan = aggregate_selected_rows(plan, groups, aggregates)?;
    // Computed partition keys are no longer expressions over source columns
    // after Aggregate. Preserve their public names while selecting bound outputs.
    let partitions = partition_by_exprs
        .iter()
        .map(|expr| {
            let rebased = bindings.rebase(expr)?;
            Ok(if &rebased == expr {
                rebased
            } else {
                let (relation, name) = expr.qualified_name();
                rebased.alias_qualified(relation, name)
            })
        })
        .collect::<Result<Vec<_>>>()?;
    Ok((plan, measures, partitions))
}