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.

//! Tests that static extraction preserves each condition's result.

use super::*;
use crate::core;
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::common::{Column, ScalarValue, exec_err};
use datafusion::functions::{math::random, string::uuid};
use datafusion::logical_expr::{Volatility, col, create_udf, lit, when};
use std::ops::Mul;
use std::sync::{Arc, LazyLock};

static INPUT_SCHEMA: LazyLock<DFSchema> = LazyLock::new(|| {
    DFSchema::try_from(Schema::new(vec![
        Field::new("price", DataType::Float64, true),
        Field::new("tax", DataType::Float64, true),
        Field::new("flag", DataType::Boolean, true),
        Field::new("denominator", DataType::Int64, true),
    ]))
    .unwrap()
});

fn generated_match_columns() -> BTreeSet<String> {
    [
        core::classifier_bits_col_name("A"),
        core::classifier_bits_col_name("B"),
        core::managed_aggregate_col_name(0),
        core::managed_aggregate_col_name(1),
        core::symbol_col_name("A"),
    ]
    .into_iter()
    .collect()
}

fn extract_for_a(expr: Expr, symbol: &str) -> (Expr, ExtractionContext<'static>) {
    let generated = generated_match_columns();
    let mut ctx = ExtractionContext::new(&INPUT_SCHEMA);
    let analysis = StaticAnalysis::new(&generated);
    let result = extract_static_subexpressions(expr, analysis, &mut ctx, symbol);
    (result, ctx)
}

#[test]
fn test_static_classification_uses_declared_match_inputs() {
    let generated = generated_match_columns();
    let analysis = StaticAnalysis::new(&generated);

    let qualified = Expr::Column(Column::new(Some("A"), "price"));
    assert!(is_static(&qualified, analysis));
    for (name, expected) in [
        ("__mr_classifier_a", false),
        ("__mr_managed_agg_0", false),
        ("__mr_symbol_a", false),
        ("__mr_path_id", false),
        ("__mr_classifier_fake", true),
        (r#""__mr_classifier_A""#, true),
        ("__mr_managed_agg_fake", true),
        ("__mr_symbol_fake", true),
    ] {
        assert_eq!(is_static(&col(name), analysis), expected, "{name}");
    }
}

#[test]
fn static_or_trivial_predicates_do_not_add_cached_columns() {
    for expr in [
        col("price").gt(lit(100)).and(col("price").lt(lit(500))),
        col("__mr_managed_agg_0").lt(col("price")),
    ] {
        let (result, ctx) = extract_for_a(expr.clone(), "A");
        assert!(ctx.extractions.is_empty());
        assert_eq!(result, expr);
    }
}

#[test]
fn shared_static_expression_keeps_both_symbol_owners() {
    let generated = generated_match_columns();
    let analysis = StaticAnalysis::new(&generated);
    let mut ctx = ExtractionContext::new(&INPUT_SCHEMA);
    let static_part = col("price").gt(lit(100));
    for (symbol, classifier) in [("A", "__mr_classifier_a"), ("B", "__mr_classifier_b")] {
        let dynamic = col(classifier).eq(lit(true));
        let result = extract_static_subexpressions(
            static_part.clone().and(dynamic.clone()),
            analysis,
            &mut ctx,
            symbol,
        );
        assert_eq!(result, col("__mr_static_predicate_and_0").and(dynamic));
    }
    let actual = ctx
        .extractions
        .iter()
        .map(|e| {
            (
                e.kind,
                e.column_name.as_str(),
                e.expr.clone(),
                e.symbols.clone(),
            )
        })
        .collect::<Vec<_>>();
    assert_eq!(
        actual,
        [(
            ExtractionKind::BooleanAnd,
            "__mr_static_predicate_and_0",
            static_part,
            vec!["A".to_string(), "B".to_string()]
        )]
    );
}

#[test]
fn static_extraction_pins_sources_names_and_complete_rewrites() {
    use ExtractionKind::{BooleanAnd, BooleanOr, Scalar};
    let predicate = col("price").gt(lit(100));
    let arithmetic = col("price").mul(col("tax"));
    let classifier = col("__mr_classifier_a").eq(lit(true));
    let and_column = col("__mr_static_predicate_and_0");
    let or_column = col("__mr_static_predicate_or_0");
    let scalar_column = col("__mr_static_scalar_0");
    for (label, input, expected_expr, expected_extractions) in [
        (
            "AND condition",
            predicate.clone().and(classifier.clone()),
            and_column.clone().and(classifier.clone()),
            vec![(BooleanAnd, "__mr_static_predicate_and_0", predicate.clone())],
        ),
        (
            "OR condition",
            predicate.clone().or(classifier.clone()),
            or_column.clone().or(classifier.clone()),
            vec![(BooleanOr, "__mr_static_predicate_or_0", predicate.clone())],
        ),
        (
            "double NOT De Morgan AND under OR",
            Expr::Not(Box::new(
                Expr::Not(Box::new(predicate.clone().and(classifier.clone())))
                    .or(col("tax").gt(lit(0))),
            )),
            Expr::Not(Box::new(
                Expr::Not(Box::new(and_column.clone().and(classifier.clone())))
                    .or(col("tax").gt(lit(0))),
            )),
            vec![(BooleanAnd, "__mr_static_predicate_and_0", predicate.clone())],
        ),
        (
            "double NOT De Morgan OR under AND",
            Expr::Not(Box::new(
                Expr::Not(Box::new(predicate.clone().or(classifier.clone())))
                    .and(col("tax").gt(lit(0))),
            )),
            Expr::Not(Box::new(
                Expr::Not(Box::new(or_column.or(classifier))).and(col("tax").gt(lit(0))),
            )),
            vec![(BooleanOr, "__mr_static_predicate_or_0", predicate.clone())],
        ),
        (
            "Boolean and scalar extraction together",
            predicate
                .clone()
                .and(col("__mr_managed_agg_0").lt(arithmetic.clone())),
            and_column.and(col("__mr_managed_agg_0").lt(scalar_column.clone())),
            vec![
                (BooleanAnd, "__mr_static_predicate_and_0", predicate),
                (Scalar, "__mr_static_scalar_0", arithmetic.clone()),
            ],
        ),
        (
            "scalar value under NOT",
            Expr::Not(Box::new(col("__mr_managed_agg_0").lt(arithmetic.clone()))),
            Expr::Not(Box::new(
                col("__mr_managed_agg_0").lt(scalar_column.clone()),
            )),
            vec![(Scalar, "__mr_static_scalar_0", arithmetic.clone())],
        ),
        (
            "scalar value under Boolean comparison",
            col("__mr_managed_agg_0")
                .lt(arithmetic.clone())
                .eq(lit(false)),
            col("__mr_managed_agg_0")
                .lt(scalar_column.clone())
                .eq(lit(false)),
            vec![(Scalar, "__mr_static_scalar_0", arithmetic.clone())],
        ),
        (
            "scalar value under DISTINCT comparison",
            Expr::BinaryExpr(BinaryExpr::new(
                Box::new(col("__mr_managed_agg_0").lt(arithmetic.clone())),
                Operator::IsDistinctFrom,
                Box::new(lit(false)),
            )),
            Expr::BinaryExpr(BinaryExpr::new(
                Box::new(col("__mr_managed_agg_0").lt(scalar_column)),
                Operator::IsDistinctFrom,
                Box::new(lit(false)),
            )),
            vec![(Scalar, "__mr_static_scalar_0", arithmetic)],
        ),
    ] {
        let (result, ctx) = extract_for_a(input, "A");
        let mut actual = ctx
            .extractions
            .iter()
            .map(|e| {
                assert_eq!(e.symbols, ["A"], "{label}");
                (e.kind, e.column_name.as_str(), e.expr.clone())
            })
            .collect::<Vec<_>>();
        actual.sort_by(|left, right| left.1.cmp(right.1));
        assert_eq!(actual, expected_extractions, "{label}");
        assert_eq!(result, expected_expr, "{label}");
    }
}

#[test]
fn boolean_extraction_leaves_static_suffixes_in_place() {
    let flag = col("flag");
    let candidate = col("__mr_managed_agg_0").lt(lit(50));
    let fallible = (lit(10) / col("denominator")).gt(lit(0));
    for input in [
        flag.clone().or(candidate.clone()),
        candidate.clone().or(flag.clone()),
        candidate.clone().and(fallible.clone()),
        flag.or(candidate).or(fallible),
    ] {
        let (result, ctx) = extract_for_a(input.clone(), "A");
        assert!(ctx.extractions.is_empty());
        assert_eq!(result, input);
    }
}

#[test]
fn volatile_operands_remain_at_the_candidate_evaluation_site() {
    let random = random().call(vec![]);
    let bytes = |value| lit(ScalarValue::Binary(Some(vec![value])));
    let case = when(random.clone().lt(lit(2.0)), bytes(b'a'))
        .otherwise(bytes(b'b'))
        .unwrap();
    let candidate = col("__mr_managed_agg_0");
    for operand in [case, uuid().call(vec![])] {
        let input = candidate.clone().eq(operand);
        let (result, ctx) = extract_for_a(input.clone(), "A");
        assert!(ctx.extractions.is_empty());
        assert_eq!(result, input);
    }

    let fallible_udf = create_udf(
        "random",
        vec![],
        DataType::Float64,
        Volatility::Volatile,
        Arc::new(|_| exec_err!("user function failed")),
    );
    for operand in [
        lit(10) / col("denominator") + random,
        fallible_udf.call(vec![]),
    ] {
        let input = col("flag").or(candidate.clone().lt(operand));
        let (result, ctx) = extract_for_a(input.clone(), "A");
        assert!(ctx.extractions.is_empty(), "{input}");
        assert_eq!(result, input);
    }
}

#[test]
fn partial_extraction_keeps_fallible_input_work_inline() {
    let flag = col("flag");
    let candidate = col("__mr_managed_agg_0");
    let division = lit(10) / col("denominator");
    for input in [
        flag.clone().or(candidate.clone().lt(division.clone())),
        flag.or(division.clone().gt(lit(0)))
            .or(candidate.gt(lit(50))),
    ] {
        let (result, ctx) = extract_for_a(input.clone(), "A");
        assert!(ctx.extractions.is_empty());
        assert_eq!(result, input);
    }
}

#[test]
fn cached_boolean_decisions_respect_polarity_and_nesting() {
    let predicate = col("price").gt(lit(100));
    let dynamic = col("__mr_managed_agg_0").lt(lit(50));
    let mixed_and = predicate.clone().and(dynamic.clone());
    let mixed_or = predicate.or(dynamic.clone());
    let negated_and = Expr::Not(Box::new(mixed_and.clone()));
    let negated_or = Expr::Not(Box::new(mixed_or.clone()));
    let classifier_a = col("__mr_classifier_a").eq(lit(true));
    let classifier_b = col("__mr_classifier_b").eq(lit(true));
    for (label, input) in [
        (
            "AND operand compared with false",
            mixed_and.clone().eq(lit(false)),
        ),
        (
            "OR operand compared with false",
            mixed_or.clone().eq(lit(false)),
        ),
        (
            "two dynamic comparison operands",
            mixed_and.clone().eq(mixed_or.clone()),
        ),
        (
            "AND operand of DISTINCT comparison",
            Expr::BinaryExpr(BinaryExpr::new(
                Box::new(mixed_and.clone()),
                Operator::IsDistinctFrom,
                Box::new(lit(true)),
            )),
        ),
        (
            "double NOT operand compared with false",
            Expr::Not(Box::new(negated_and.clone())).eq(lit(false)),
        ),
        ("AND under NOT", negated_and.clone()),
        (
            "negated AND under OR",
            negated_and.clone().or(classifier_a.clone()),
        ),
        ("OR under NOT", negated_or.clone()),
        (
            "negated OR under AND",
            negated_or.clone().and(classifier_a.clone()),
        ),
        (
            "double NOT De Morgan OR under OR",
            Expr::Not(Box::new(negated_or.or(col("tax").gt(lit(0))))),
        ),
        (
            "double NOT De Morgan AND under AND",
            Expr::Not(Box::new(negated_and.and(col("tax").gt(lit(0))))),
        ),
        (
            "double NOT after an earlier OR operand",
            dynamic.or(Expr::Not(Box::new(Expr::Not(Box::new(mixed_or.clone()))))),
        ),
        (
            "AND branches under OR",
            mixed_and.clone().or(col("price")
                .lt(lit(20))
                .and(col("__mr_managed_agg_1").gt(lit(10)))),
        ),
        (
            "OR branches under AND",
            mixed_or.and(
                col("price")
                    .lt(lit(200))
                    .or(col("__mr_managed_agg_1").gt(lit(10))),
            ),
        ),
        (
            "AND under OR under AND",
            mixed_and.or(classifier_a).and(classifier_b),
        ),
    ] {
        let (result, ctx) = extract_for_a(input.clone(), "A");
        assert!(ctx.extractions.is_empty(), "{label}");
        assert_eq!(result, input, "{label}");
    }
}