datafusion-match-recognize 0.55.0

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.

//! Builds an optional local guard for a history-backed `DEFINE` condition.
//!
//! The guard preserves `AND`, `OR`, and `NOT`. Leaves that need candidate
//! history remain unknown until the synchronous history evaluator runs.
//! A conclusive local result settles the candidate without reading history.

use std::collections::BTreeSet;
use std::str::FromStr;

use crate::core::MatchMetadataColumn;
use datafusion::common::tree_node::TreeNode;
use datafusion::logical_expr::{BinaryExpr, Expr, Operator};

/// A guard whose result can be true, false, or unknown.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum LogicalHybridGuardExpr {
    /// A subtree the row loop can evaluate immediately.
    Local(Expr),
    /// A subtree whose truth requires candidate history.
    Unknown,
    /// Three-valued conjunction.
    And(Box<LogicalHybridGuardExpr>, Box<LogicalHybridGuardExpr>),
    /// Three-valued disjunction.
    Or(Box<LogicalHybridGuardExpr>, Box<LogicalHybridGuardExpr>),
    /// Three-valued negation.
    Not(Box<LogicalHybridGuardExpr>),
}

impl LogicalHybridGuardExpr {
    /// Return whether any leaf still requires candidate history.
    pub fn contains_unknown(&self) -> bool {
        match self {
            Self::Unknown => true,
            Self::Local(_) => false,
            Self::And(left, right) | Self::Or(left, right) => {
                left.contains_unknown() || right.contains_unknown()
            }
            Self::Not(inner) => inner.contains_unknown(),
        }
    }
}

/// Build a local guard from a normalized history-backed DEFINE expression.
///
/// The result is a tri-state guard where:
/// - `Local(expr)` leaves are fully local-evaluable subtrees.
/// - `Unknown` leaves require candidate history.
/// - `And` / `Or` / `Not` preserve boolean structure for tri-state evaluation.
pub fn build_logical_hybrid_guard(
    expr: &Expr,
    deferred_columns: &BTreeSet<String>,
) -> LogicalHybridGuardExpr {
    match expr {
        Expr::Alias(alias) => build_logical_hybrid_guard(&alias.expr, deferred_columns),
        Expr::BinaryExpr(BinaryExpr { left, op, right })
            if *op == Operator::And || *op == Operator::Or =>
        {
            let left_guard = build_logical_hybrid_guard(left, deferred_columns);
            let right_guard = build_logical_hybrid_guard(right, deferred_columns);
            if *op == Operator::And {
                LogicalHybridGuardExpr::And(Box::new(left_guard), Box::new(right_guard))
            } else {
                LogicalHybridGuardExpr::Or(Box::new(left_guard), Box::new(right_guard))
            }
        }
        Expr::Not(inner) => LogicalHybridGuardExpr::Not(Box::new(
            build_logical_hybrid_guard(inner, deferred_columns),
        )),
        _ => {
            if is_deferred_dependent_expr(expr, deferred_columns) {
                LogicalHybridGuardExpr::Unknown
            } else {
                LogicalHybridGuardExpr::Local(expr.clone())
            }
        }
    }
}

/// Return whether any part of this expression requires candidate history.
pub(super) fn is_deferred_dependent_expr(
    expr: &Expr,
    deferred_columns: &BTreeSet<String>,
) -> bool {
    expr.exists(|node| {
        let is_deferred = match node {
            Expr::WindowFunction(_) | Expr::AggregateFunction(_) => true,
            Expr::ScalarSubquery(_) | Expr::Exists(_) | Expr::InSubquery(_) => true,
            Expr::Column(col) => {
                let metadata_requires_deferred = MatchMetadataColumn::from_str(&col.name)
                    .map(|meta| {
                        !matches!(
                            meta,
                            MatchMetadataColumn::MatchNumber
                                | MatchMetadataColumn::MatchSequenceNumber
                                | MatchMetadataColumn::Excluded
                        )
                    })
                    .unwrap_or(false);
                deferred_columns.contains(&col.name) || metadata_requires_deferred
            }
            _ => false,
        };
        Ok(is_deferred)
    })
    .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;
    use datafusion::logical_expr::{
        WindowFunctionDefinition, col, expr::WindowFunction, lit,
    };

    #[test]
    fn hybrid_guards_preserve_boolean_structure_and_exact_local_leaves() {
        use LogicalHybridGuardExpr as Guard;
        let local = col("__mr_static_predicate_and_0");
        let deferred = col("__mr_classifier_a");
        let excluded = col(MatchMetadataColumn::Excluded.as_ref());
        let columns = BTreeSet::from(["__mr_classifier_a".into()]);
        for (expression, expected, contains_unknown) in [
            (
                local.clone().and(deferred.clone()),
                Guard::And(
                    Box::new(Guard::Local(local.clone())),
                    Box::new(Guard::Unknown),
                ),
                true,
            ),
            (
                local.clone().or(deferred.clone()),
                Guard::Or(Box::new(Guard::Local(local)), Box::new(Guard::Unknown)),
                true,
            ),
            (
                Expr::Not(Box::new(deferred)),
                Guard::Not(Box::new(Guard::Unknown)),
                true,
            ),
            (
                Expr::Not(Box::new(excluded.clone())),
                Guard::Not(Box::new(Guard::Local(excluded))),
                false,
            ),
        ] {
            let actual = build_logical_hybrid_guard(&expression, &columns);
            assert_eq!(actual, expected);
            assert_eq!(actual.contains_unknown(), contains_unknown);
            assert_eq!(
                is_deferred_dependent_expr(&expression, &columns),
                contains_unknown,
            );
        }
    }

    #[test]
    fn hybrid_leaf_policy_preserves_local_values_and_marks_deferred_dependencies() {
        use LogicalHybridGuardExpr as Guard;
        let columns = BTreeSet::from(["__mr_managed_agg_9".into()]);
        for (expression, local) in [
            (col("__mr_managed_agg_0").gt(lit(3_i64)), true),
            (col("__mr_managed_agg_0").is_null(), true),
            (col("__mr_match_number").is_null(), true),
            (col("__mr_match_sequence_number").is_null(), true),
            (col("__mr_path_id").is_null(), false),
            (col("__mr_managed_agg_9").gt(lit(0_i64)), false),
        ] {
            let expected = if local {
                Guard::Local(expression.clone())
            } else {
                Guard::Unknown
            };
            assert_eq!(
                build_logical_hybrid_guard(&expression, &columns),
                expected,
                "{expression}"
            );
        }
    }

    #[test]
    fn treats_window_with_local_arguments_as_unknown() {
        let window = WindowFunction::new(
            WindowFunctionDefinition::AggregateUDF(
                datafusion::functions_aggregate::count::count_udaf(),
            ),
            vec![lit(1_i64)],
        );
        let expr = Expr::WindowFunction(Box::new(window)).gt(lit(0_i64));

        let guard = build_logical_hybrid_guard(&expr, &BTreeSet::new());

        assert!(matches!(guard, LogicalHybridGuardExpr::Unknown));
    }

    #[test]
    fn hybrid_guards_peel_aliases_around_boolean_structure_and_leaves() {
        use LogicalHybridGuardExpr as Guard;
        let local = col("x").gt(lit(2_i64));
        let deferred = col("__mr_managed_agg_0").gt(lit(0_i64));
        let columns = BTreeSet::from(["__mr_managed_agg_0".into()]);
        for (expression, expected) in [
            (
                local
                    .clone()
                    .alias("lhs")
                    .and(deferred.clone().alias("rhs"))
                    .alias("outer"),
                Guard::And(
                    Box::new(Guard::Local(local.clone())),
                    Box::new(Guard::Unknown),
                ),
            ),
            (
                local.clone().or(deferred.clone()).alias("outer"),
                Guard::Or(
                    Box::new(Guard::Local(local.clone())),
                    Box::new(Guard::Unknown),
                ),
            ),
            (
                Expr::Not(Box::new(local.clone().and(deferred).alias("inner")))
                    .alias("outer"),
                Guard::Not(Box::new(Guard::And(
                    Box::new(Guard::Local(local)),
                    Box::new(Guard::Unknown),
                ))),
            ),
        ] {
            let actual = build_logical_hybrid_guard(&expression, &columns);
            assert_eq!(actual, expected);
            assert!(actual.contains_unknown());
        }
    }
}