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.

//! Common semantic admission and preparation of complete static DEFINEs.
//!
//! Dependency is independent of evaluator selection and compiler diagnostics.
//! Input-only predicates can still be volatile or fallible. Preparation keeps
//! those predicates on the matcher so only a reached transition observes them.

use crate::core::{MatchMetadataColumn, classifier_bits_col_name};
use crate::planning::logical::{BoundMatchSource, LoweredMatchSpec};
use crate::planning::{
    BoundMatchSpec, MatchRecognizePlanningCapabilities, MatchRecognizePlanningContext,
};
use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion::common::{Result, plan_err};
use datafusion::logical_expr::{Expr, LogicalPlan, WindowFunctionDefinition};
use std::collections::BTreeSet;
use std::str::FromStr;

mod cross_symbol_navigation;
pub(crate) mod preparation;

/// Borrowed semantic identities used to recognize candidate-state reads.
///
/// Lowered expressions never encode pattern-variable references as
/// `Expr::Column` table qualifiers; those are already lowered into navigation
/// windows or classifier masks. Any remaining `Expr::Column` whose name is
/// neither a generated match column nor a fixed match metadata column is an
/// ordinary input column, even when its table qualifier shares a pattern
/// variable's name.
#[derive(Clone, Copy)]
pub(crate) struct StaticAnalysis<'a> {
    generated_match_columns: &'a BTreeSet<String>,
}

impl<'a> StaticAnalysis<'a> {
    pub(crate) fn new(generated_match_columns: &'a BTreeSet<String>) -> Self {
        Self {
            generated_match_columns,
        }
    }
}

/// Recognize unresolved built-in placeholders by implementation identity.
/// Same-named user functions remain ordinary scalar input work.
pub(crate) fn is_metadata_placeholder(
    function: &datafusion::logical_expr::ScalarUDF,
) -> bool {
    use crate::functions::udf::metadata::{
        ClassifierUdf, ExcludedUdf, MatchNumberUdf, MatchSequenceNumberUdf,
    };
    let implementation = function.inner();
    implementation.is::<ClassifierUdf>()
        || implementation.is::<ExcludedUdf>()
        || implementation.is::<MatchNumberUdf>()
        || implementation.is::<MatchSequenceNumberUdf>()
}

/// Direct navigation window implementations require structured source leaves.
/// Distinct same-named user windows remain ordinary input work.
pub(crate) fn is_navigation_window(function: &WindowFunctionDefinition) -> bool {
    match function {
        WindowFunctionDefinition::WindowUDF(udf) => crate::functions::udwf::functions()
            .iter()
            .any(|known| known.as_ref() == udf.as_ref()),
        WindowFunctionDefinition::AggregateUDF(udaf) => {
            crate::functions::udaf::functions()
                .iter()
                .any(|known| known.as_ref() == udaf.as_ref())
        }
    }
}

/// Semantic support required by a single normalized symbol predicate.
#[derive(Clone, Debug, PartialEq)]
pub struct DefineRequirement {
    symbol: String,
    expression: Expr,
    match_aware: bool,
}

impl DefineRequirement {
    /// Defining symbol in canonical spelling.
    pub fn symbol(&self) -> &str {
        &self.symbol
    }
    /// Predicate after the common safe semantic normalization.
    pub fn expression(&self) -> &Expr {
        &self.expression
    }
    /// Whether the normalized DEFINE remains match-aware.
    pub const fn requires_match_aware_defines(&self) -> bool {
        self.match_aware
    }
}

/// Normalized DEFINE requirements for each pattern symbol.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MatchRecognizeRequirements {
    definitions: Vec<DefineRequirement>,
}

impl MatchRecognizeRequirements {
    /// Per-symbol requirements in source order.
    pub fn definitions(&self) -> &[DefineRequirement] {
        &self.definitions
    }
    /// Whether any normalized DEFINE remains match-aware.
    pub fn requires_match_aware_defines(&self) -> bool {
        self.definitions
            .iter()
            .any(DefineRequirement::requires_match_aware_defines)
    }
}

pub(crate) fn requirements_for_lowered(
    spec: &LoweredMatchSpec,
) -> MatchRecognizeRequirements {
    let generated = spec
        .symbols
        .iter()
        .map(|symbol| classifier_bits_col_name(symbol))
        .collect();
    let analysis = StaticAnalysis::new(&generated);
    MatchRecognizeRequirements {
        definitions: spec
            .definitions
            .iter()
            .map(|definition| DefineRequirement {
                symbol: definition.symbol.clone(),
                expression: definition.predicate.clone(),
                match_aware: !is_static(&definition.predicate, analysis),
            })
            .collect(),
    }
}

/// Analyze a request using the same validation and safe normalization as planning.
///
/// Source-adapter capabilities restrict which expressions the adapter can represent.
///
/// # Errors
/// Returns source validation, binding, normalization, or type-resolution errors.
pub fn analyze_match_recognize_requirements(
    context: &mut dyn MatchRecognizePlanningContext,
    input: &LogicalPlan,
    spec: &BoundMatchSpec,
    capabilities: MatchRecognizePlanningCapabilities,
) -> Result<MatchRecognizeRequirements> {
    let source =
        BoundMatchSource::try_new(context, input.clone(), spec.clone(), capabilities)?;
    Ok(source.requirements().clone())
}

/// Check a constructor-supplied static expression independently of its tag.
pub(crate) fn validate_static_predicate(
    symbol: &str,
    expression: &Expr,
    symbols: &BTreeSet<String>,
) -> Result<()> {
    let generated = symbols
        .iter()
        .flat_map(|name| {
            [
                crate::core::symbol_col_name(name),
                classifier_bits_col_name(name),
            ]
        })
        .collect();
    if expression
        .column_refs()
        .iter()
        .any(|column| column.name.starts_with("__mr_managed_agg_"))
        || !is_static(expression, StaticAnalysis::new(&generated))
    {
        return plan_err!(
            "MATCH_RECOGNIZE symbol '{symbol}' has a match-aware DEFINE predicate '{expression}' supplied as static input. Use 'plan_match_recognize_from_source' or supply a prepared match-aware 'LogicalSymbolInput'."
        );
    }
    Ok(())
}

#[cfg(test)]
mod tests;

/// Return whether one node reads candidate-match state.
///
/// Match state includes columns generated by this planning pass, fixed matcher
/// metadata, match aggregates, and match navigation window functions.
fn is_match_aware_node(expr: &Expr, analysis: StaticAnalysis<'_>) -> bool {
    match expr {
        Expr::Column(col) => {
            let name = &col.name;
            analysis.generated_match_columns.contains(name)
                || MatchMetadataColumn::from_str(name).is_ok()
        }
        // Lowering normally replaces these; a raw aggregate is still match-scoped.
        Expr::AggregateFunction(_) => true,
        // Low-level callers can supply unresolved placeholder objects without
        // going through structured source normalization. Their scalar return
        // types do not make them input-only expressions.
        Expr::ScalarFunction(call) => is_metadata_placeholder(&call.func),
        // Low-level callers can also supply raw match navigation window UDFs or
        // UDAFs without metadata arguments; those still depend on candidate-match state.
        Expr::WindowFunction(window) => is_navigation_window(&window.fun),
        _ => false,
    }
}

/// Return whether a window function or any of its semantic inputs reads
/// candidate-match state.
pub(crate) fn is_match_scoped_window(
    wf: &datafusion::logical_expr::expr::WindowFunction,
    analysis: StaticAnalysis<'_>,
) -> bool {
    is_navigation_window(&wf.fun)
        || wf
            .params
            .args
            .iter()
            .chain(&wf.params.partition_by)
            .chain(wf.params.filter.as_deref())
            .chain(wf.params.order_by.iter().map(|sort| &sort.expr))
            .any(|expr| contains_match_aware_expr(expr, analysis))
}

/// Return whether an expression tree references match state.
fn contains_match_aware_expr(expr: &Expr, analysis: StaticAnalysis<'_>) -> bool {
    let mut found = false;
    // DataFusion's visitor includes window arguments, partition keys, filters,
    // and ordering expressions.
    let _ = expr.apply(|node| {
        if is_match_aware_node(node, analysis) {
            found = true;
            return Ok(TreeNodeRecursion::Stop);
        }
        Ok(TreeNodeRecursion::Continue)
    });
    found
}

/// Return whether the expression depends only on ordered input rows.
/// Volatility and fallibility are checked separately before eager preparation.
pub(crate) fn is_static(expr: &Expr, analysis: StaticAnalysis<'_>) -> bool {
    !contains_match_aware_expr(expr, analysis)
}

#[cfg(test)]
mod analysis_tests {
    use super::*;
    use datafusion::logical_expr::{
        SortExpr, WindowFunctionDefinition, col, expr::WindowFunction,
    };
    use std::collections::BTreeSet;

    fn test_window(value: Expr) -> WindowFunction {
        WindowFunction::new(
            WindowFunctionDefinition::AggregateUDF(
                datafusion::functions_aggregate::sum::sum_udaf(),
            ),
            vec![value],
        )
    }

    #[test]
    fn static_analysis_treats_input_table_qualifiers_as_static() {
        use datafusion::common::{Column, TableReference};

        let generated = BTreeSet::from(["__mr_classifier_a".into()]);
        let analysis = StaticAnalysis::new(&generated);
        for qualifier in [
            TableReference::bare("src.A"),
            TableReference::partial("schema", "src.A"),
            TableReference::full("catalog", "schema", "src.A"),
            TableReference::bare("a"),
            TableReference::partial("src.with.dots", "a"),
            TableReference::full("cat.with.dots", "schema", "A"),
        ] {
            let expression = Expr::Column(Column::new(Some(qualifier.clone()), "value"));
            assert!(is_static(&expression, analysis), "{qualifier:?}");
        }

        let generated_col = Expr::Column(Column::new(
            Some(TableReference::bare("a")),
            "__mr_classifier_a",
        ));
        assert!(!is_static(&generated_col, analysis));
    }

    #[test]
    fn window_scope_checks_each_expression_input_independently() {
        let mut filtered = test_window(col("value"));
        filtered.params.filter = Some(Box::new(col("__mr_classifier_a")));
        let mut ordered = test_window(col("value"));
        ordered.params.order_by = vec![SortExpr::new(col("__mr_path_id"), true, false)];
        let mut partitioned = test_window(col("value"));
        partitioned.params.partition_by = vec![col("__mr_path_id")];
        let nested =
            |value| test_window(Expr::WindowFunction(Box::new(test_window(value))));
        let generated = BTreeSet::from(["__mr_classifier_a".into()]);
        let analysis = StaticAnalysis::new(&generated);
        for (window, match_scoped) in [
            (nested(col("value")), false),
            (filtered, true),
            (ordered, true),
            (partitioned, true),
            (nested(col("__mr_classifier_a")), true),
        ] {
            assert_eq!(is_match_scoped_window(&window, analysis), match_scoped);
            let expression = Expr::WindowFunction(Box::new(window));
            assert_eq!(
                is_static(&expression, analysis),
                !match_scoped,
                "{expression}"
            );
        }
    }
}