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.

use std::collections::HashMap;

use crate::core::RepetitionQuantifier::*;
use crate::core::test_support::all_matches;
use crate::core::{NormalizedPattern, Pattern, Symbol};

use super::symbol_runs::normalize_symbol_runs;
use super::{PatternOptimizer, SymbolStatus};
use crate::nfa::CompiledAutomaton;

fn symbol(name: &str) -> Pattern {
    Pattern::Symbol(Symbol::Named(name.into()))
}

fn repeat(pattern: Pattern, quantifier: crate::core::RepetitionQuantifier) -> Pattern {
    Pattern::Repetition(Box::new(pattern), quantifier)
}

#[test]
fn same_symbol_run_normalization_matrix() {
    let a = symbol("A");
    let excluded = Pattern::Exclude(Symbol::Named("A".into()));
    let cases = [
        (
            "adjacent symbols",
            Pattern::Concat(vec![a.clone(), a.clone()]),
        ),
        (
            "adjacent intervals",
            Pattern::Concat(vec![
                repeat(a.clone(), Range(1, 3)),
                repeat(a.clone(), Range(2, 4)),
            ]),
        ),
        (
            "adjacent reluctant intervals",
            Pattern::Concat(vec![
                repeat(a.clone(), RangeReluctant(1, 3)),
                repeat(a.clone(), RangeReluctant(2, 4)),
            ]),
        ),
        (
            "fixed counts have no preference",
            Pattern::Concat(vec![
                repeat(a.clone(), ExactlyReluctant(2)),
                repeat(a.clone(), AtMostOne),
            ]),
        ),
        (
            "unbounded adjacent run",
            Pattern::Concat(vec![
                repeat(a.clone(), OneOrMoreReluctant),
                repeat(a.clone(), Exactly(2)),
            ]),
        ),
        (
            "fixed outer greedy interval",
            repeat(repeat(a.clone(), Range(2, 3)), Exactly(3)),
        ),
        (
            "fixed outer reluctant interval",
            repeat(repeat(a.clone(), RangeReluctant(2, 3)), Exactly(3)),
        ),
        (
            "nullable greedy inner",
            repeat(repeat(a.clone(), AtMostOne), Range(2, 5)),
        ),
        (
            "nullable reluctant inner",
            repeat(repeat(a.clone(), AtMostOneReluctant), RangeReluctant(2, 5)),
        ),
        (
            "positive greedy inner",
            repeat(repeat(a.clone(), Range(1, 3)), Range(2, 4)),
        ),
        (
            "positive reluctant inner",
            repeat(
                repeat(a.clone(), RangeReluctant(1, 3)),
                RangeReluctant(2, 4),
            ),
        ),
        (
            "unbounded nested run",
            repeat(repeat(a.clone(), OneOrMoreReluctant), OneOrMoreReluctant),
        ),
        (
            "identical excluded runs",
            Pattern::Concat(vec![repeat(excluded.clone(), AtMostOne), excluded.clone()]),
        ),
        (
            "neutral wrappers and zero counts",
            Pattern::Concat(vec![
                Pattern::Group(Box::new(repeat(a.clone(), AtMostOne))),
                repeat(symbol("B"), Exactly(0)),
                Pattern::Concat(vec![
                    Pattern::Concat(vec![]),
                    repeat(a.clone(), Exactly(2)),
                ]),
            ]),
        ),
        (
            "nested fixed counts",
            repeat(repeat(a.clone(), Exactly(3)), ExactlyReluctant(2)),
        ),
    ];
    let transcript = cases
        .map(|(label, pattern)| {
            let original = pattern.to_string();
            let normalized = normalize_symbol_runs(pattern);
            // Display can hide AST wrappers; keep the canonical atom shape checked.
            let Pattern::Repetition(atom, _) = &normalized else {
                panic!("{label}: expected a repeated atom, got {normalized:?}");
            };
            assert!(
                matches!(atom.as_ref(),
                    Pattern::Symbol(Symbol::Named(name))
                        | Pattern::Exclude(Symbol::Named(name)) if name == "A"),
                "{label}: expected a direct A atom, got {normalized:?}"
            );
            format!("{label}: {original} -> {normalized}")
        })
        .join("\n");
    assert_eq!(
        transcript,
        "\
adjacent symbols: A A -> A{2}
adjacent intervals: A{1,3} A{2,4} -> A{3,7}
adjacent reluctant intervals: A{1,3}? A{2,4}? -> A{3,7}?
fixed counts have no preference: A{2}? A? -> A{2,3}
unbounded adjacent run: A+? A{2} -> A{3,}?
fixed outer greedy interval: (A{2,3}){3} -> A{6,9}
fixed outer reluctant interval: (A{2,3}?){3} -> A{6,9}?
nullable greedy inner: (A?){2,5} -> A{0,5}
nullable reluctant inner: (A??){2,5}? -> A{0,5}?
positive greedy inner: (A{1,3}){2,4} -> A{2,12}
positive reluctant inner: (A{1,3}?){2,4}? -> A{2,12}?
unbounded nested run: (A+?)+? -> A+?
identical excluded runs: ({- A -}?) ({- A -}) -> {- A -}{1,2}
neutral wrappers and zero counts: (A?) B{0}  A{2} -> A{2,3}
nested fixed counts: (A{3}){2}? -> A{6}"
    );
}

#[test]
fn ambiguous_or_unrepresentable_runs_remain_separate() {
    let a = symbol("A");
    let cases = [
        Pattern::Concat(vec![
            repeat(a.clone(), AtMostOne),
            repeat(a.clone(), AtMostOneReluctant),
        ]),
        repeat(repeat(a.clone(), AtMostOne), OneOrMoreReluctant),
        repeat(repeat(a.clone(), Exactly(2)), AtMost(2)),
        // The accepted interval is contiguous, but the winning length is not
        // monotone: with four A rows, greedy prefers three over four.
        repeat(repeat(a.clone(), Range(2, 3)), Range(1, 2)),
        repeat(
            repeat(a.clone(), RangeReluctant(2, 3)),
            RangeReluctant(1, 2),
        ),
        Pattern::Concat(vec![repeat(a.clone(), OneOrMorePossessive), a.clone()]),
        repeat(repeat(a.clone(), OneOrMorePossessive), Exactly(2)),
        Pattern::Concat(vec![a.clone(), symbol("a")]),
        Pattern::Concat(vec![a.clone(), Pattern::Exclude(Symbol::Named("A".into()))]),
        Pattern::Concat(vec![a.clone(), Pattern::Symbol(Symbol::End), a.clone()]),
        repeat(
            Pattern::Alternation(vec![a.clone(), symbol("B")]),
            Exactly(2),
        ),
        Pattern::Concat(vec![repeat(a.clone(), Exactly(u32::MAX)), a.clone()]),
        repeat(repeat(a.clone(), Range(1, u32::MAX)), Exactly(2)),
        repeat(repeat(a, Exactly(u32::MAX)), Exactly(2)),
        repeat(Pattern::Concat(vec![]), Range(2, 1)),
    ];
    for pattern in cases {
        assert_eq!(normalize_symbol_runs(pattern.clone()), pattern, "{pattern}");
    }
}

#[test]
fn wide_optional_prefix_normalizes_without_pruning_or_larger_compile_limits() {
    let pattern = Pattern::Concat(vec![
        repeat(repeat(symbol("A"), AtMostOne), Exactly(4000)),
        repeat(symbol("A"), Exactly(4000)),
    ]);
    let expected = NormalizedPattern::Ast(repeat(symbol("A"), Range(4000, 8000)));
    for pruning in [false, true] {
        let status = HashMap::new();
        let actual = PatternOptimizer::new(&status)
            .with_allow_pruning(pruning)
            .optimize(&pattern);
        assert_eq!(actual, expected);
    }
    let compiled = CompiledAutomaton::compile(&expected, &["A".into(), "unused".into()])
        .expect("the normalized run fits default compile limits");
    assert_eq!(compiled.nfa().states().len(), 16_002);
    assert_eq!(compiled.symbols_iter().count(), 2);
}

#[test]
fn simplification_exposes_wide_runs_before_compile_limits() {
    let expected = NormalizedPattern::Ast(repeat(symbol("A"), Range(4000, 8000)));
    for (label, alternative, statuses) in [
        (
            "duplicate alternative",
            Pattern::Alternation(vec![symbol("A"), symbol("A")]),
            HashMap::new(),
        ),
        (
            "complete-scope false alternative",
            Pattern::Alternation(vec![symbol("A"), symbol("B")]),
            HashMap::from([("B".into(), SymbolStatus::False)]),
        ),
    ] {
        let pattern = Pattern::Concat(vec![
            repeat(repeat(alternative, AtMostOne), Exactly(4000)),
            repeat(symbol("A"), Exactly(4000)),
        ]);
        let normalized = PatternOptimizer::new(&statuses)
            .with_allow_pruning(!statuses.is_empty())
            .optimize(&pattern);
        assert_eq!(normalized, expected, "{label}");
        CompiledAutomaton::compile(&normalized, &["A".into(), "B".into()])
            .expect("exposed run fits default compile limits");
    }
}

#[test]
fn symbol_run_rewrites_preserve_reference_classifiers_and_preference() {
    // Exercise finite/unbounded, nullable/required, matching/mixed preference,
    // and contiguous-but-preference-sensitive nested intervals. The reference
    // builds its own ordered graph from the original tree. A suffix B over AB
    // rows makes a changed winning length observable in the classified history.
    let quantifiers = [
        Exactly(0),
        Exactly(1),
        Exactly(2),
        AtMostOne,
        AtMostOneReluctant,
        Range(1, 3),
        RangeReluctant(1, 3),
        Range(2, 3),
        RangeReluctant(2, 3),
        ZeroOrMore,
        ZeroOrMoreReluctant,
        OneOrMore,
        OneOrMoreReluctant,
    ];
    let status = HashMap::new();
    let optimizer = PatternOptimizer::new(&status);
    for left in &quantifiers {
        for right in &quantifiers {
            let patterns = [
                Pattern::Concat(vec![
                    repeat(symbol("A"), left.clone()),
                    repeat(symbol("A"), right.clone()),
                ]),
                repeat(repeat(symbol("A"), left.clone()), right.clone()),
            ];
            for prefix in patterns {
                for pattern in
                    [prefix.clone(), Pattern::Concat(vec![prefix, symbol("B")])]
                {
                    let normalized = match optimizer.optimize(&pattern) {
                        NormalizedPattern::Ast(pattern) => pattern,
                        NormalizedPattern::Epsilon => Pattern::Concat(vec![]),
                        NormalizedPattern::Never => {
                            panic!("no impossible symbols or anchors")
                        }
                    };
                    for length in 0..=7 {
                        for rows in [vec!["A"; length], vec!["AB"; length]] {
                            assert_eq!(
                                all_matches(&normalized, &rows),
                                all_matches(&pattern, &rows),
                                "{pattern} -> {normalized}, rows={rows:?}"
                            );
                        }
                    }
                }
            }
        }
    }
}