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.

//! Concatenation optimization passes.
//!
//! This module provides optimization for concatenation patterns, including:
//! - Failure propagation (if any required part fails, the whole concat fails)
//! - Empty elimination (skip epsilon/empty patterns)
//! - Possessive promotion (convert unbounded greedy quantifiers when safe)
//!
//! ## Possessive Promotion with Optional Lookahead
//!
//! The possessive promotion logic uses multi-step lookahead to handle optional
//! patterns. For example, in `A+ B? C` where A is disjoint from both B and C,
//! `A+` can become `A++` because whether B matches or is skipped, the next
//! row-consuming symbol is still disjoint from A. The same follow-set is
//! threaded into nested groups and alternations so a repetition is not promoted
//! before an overlapping symbol that only appears in an enclosing concat suffix.

use std::collections::HashSet;

use crate::core::{NormalizedPattern, Pattern, RepetitionQuantifier};

use crate::nfa::pattern_optimizer::optimizer::PatternOptimizer;
use crate::nfa::pattern_optimizer::types::RowsConsumed;

impl<'a> PatternOptimizer<'a> {
    /// Optimize a concatenation pattern.
    pub(crate) fn optimize_concat(
        &self,
        pats: &[Pattern],
        following_symbols: &[String],
        suffix_can_match_empty: bool,
        rows_before: RowsConsumed,
        has_anchors: bool,
    ) -> NormalizedPattern {
        if pats.is_empty() {
            return NormalizedPattern::Epsilon;
        }

        let Some(mut simplified_pats) = self.collect_concat_parts(
            pats,
            following_symbols,
            suffix_can_match_empty,
            rows_before,
            has_anchors,
        ) else {
            return NormalizedPattern::Never;
        };

        if simplified_pats.is_empty() {
            return NormalizedPattern::Epsilon;
        }

        let result_pat = if simplified_pats.len() == 1 {
            simplified_pats.pop().expect("one optimized concat part")
        } else {
            Pattern::Concat(simplified_pats)
        };

        NormalizedPattern::Ast(result_pat)
    }

    /// Try to promote an unbounded greedy quantifier to possessive. With row-consuming
    /// following symbols, every inner-vs-following pair must be disjoint. At a terminal
    /// position, where `following_symbols` is empty, the inner symbols
    /// themselves must be pairwise disjoint.
    pub(crate) fn try_promote_repetition(
        &self,
        inner: &Pattern,
        quant: &RepetitionQuantifier,
        following_symbols: &[String],
        suffix_can_match_empty: bool,
    ) -> Option<RepetitionQuantifier> {
        // Only unbounded loops emit executable exit-suppression controls.
        // Finite copies keep their ordinary preference and Lane eligibility.
        if quant.max_repetitions().is_some() {
            return None;
        }
        let new_quant = quant.possessive_variant()?;
        // A nullable reluctant inner can prefer accepting before consuming a
        // row. Disjoint symbols do not justify suppressing that acceptance.
        if inner.has_reluctant_choice() {
            return None;
        }
        let info = inner.structural_info();
        // A nullable body gives the continuation an unconditional zero-row path
        // through the loop end to the exit, leaking exit symbols into the
        // continuation's transition bitmap and pruning valid exits at runtime.
        if info.can_match_empty() {
            return None;
        }
        // A nullable suffix can accept here even if the next iteration starts
        // successfully and then fails on a later row or anchor.
        if suffix_can_match_empty
            && (info.has_anchors()
                || info.min_match_rows() != 1
                || info.max_match_rows() != Some(1))
        {
            return None;
        }
        let inner_symbols = self.pattern_facts.fact(inner).leading_symbols;

        if inner_symbols.is_empty() {
            return None;
        }

        if !following_symbols.is_empty() {
            if !self.all_pairs_disjoint(&inner_symbols, following_symbols) {
                return None;
            }
        } else {
            if inner_symbols.len() <= 1 {
                return None;
            }
            if !self.are_symbols_pairwise_disjoint(&inner_symbols) {
                return None;
            }
        }

        Some(new_quant)
    }

    fn all_pairs_disjoint(&self, left: &[String], right: &[String]) -> bool {
        left.iter()
            .all(|s1| right.iter().all(|s2| self.symbols_are_disjoint(s1, s2)))
    }

    fn are_symbols_pairwise_disjoint(&self, symbols: &[String]) -> bool {
        (0..symbols.len()).all(|i| {
            ((i + 1)..symbols.len())
                .all(|j| self.symbols_are_disjoint(&symbols[i], &symbols[j]))
        })
    }

    fn collect_concat_parts(
        &self,
        pats: &[Pattern],
        following_symbols: &[String],
        outer_suffix_can_match_empty: bool,
        rows_before: RowsConsumed,
        has_anchors: bool,
    ) -> Option<Vec<Pattern>> {
        // An inherited position proves a leading anchor will fail before this
        // branch can evaluate a DEFINE. After a potentially consuming child,
        // preserve that work unless this concat was already structurally impossible.
        let mut first_possible = None;
        let mut first_required = None;
        if has_anchors {
            for (index, pat) in pats.iter().enumerate() {
                let info = self.pattern_facts.fact(pat).structural_info;
                if info.max_match_rows() != Some(0) {
                    first_possible.get_or_insert(index);
                }
                if !info.can_match_empty() {
                    first_required = Some(index);
                    break;
                }
            }
        }
        // Followers are an unordered disjointness proof, not pattern preference.
        // Walk backward with one unique suffix summary instead of retaining a
        // copied nullable suffix for every part. Reverse the output back below.
        let mut suffix = following_symbols.to_vec();
        let mut suffix_can_match_empty = outer_suffix_can_match_empty;
        let mut seen = HashSet::new();
        suffix.retain(|symbol| seen.insert(symbol.to_ascii_lowercase()));
        let mut parts = Vec::with_capacity(pats.len());
        for (index, pat) in pats.iter().enumerate().rev() {
            let child_rows_before = if first_required.is_some_and(|first| index > first)
                || (!rows_before.could_be_zero()
                    && first_possible.is_none_or(|first| index <= first))
            {
                RowsConsumed::Positive
            } else {
                RowsConsumed::Zero
            };
            match self.optimize_with_context(
                pat,
                &suffix,
                suffix_can_match_empty,
                child_rows_before,
            ) {
                NormalizedPattern::Never => return None,
                NormalizedPattern::Epsilon => {}
                NormalizedPattern::Ast(mut part) => {
                    if let Pattern::Repetition(inner, quant) = &mut part
                        && let Some(promoted) = self.try_promote_repetition(
                            inner,
                            quant,
                            &suffix,
                            suffix_can_match_empty,
                        )
                    {
                        *quant = promoted;
                    }
                    parts.push(part);
                }
            }

            // Use original structural facts, just as forward suffix lookahead
            // did: pruning a child must not weaken an earlier promotion proof.
            let fact = self.pattern_facts.fact(pat);
            if !fact.structural_info.can_match_empty() {
                suffix_can_match_empty = false;
                suffix.clear();
                seen.clear();
            }
            for symbol in fact.leading_symbols {
                if seen.insert(symbol.to_ascii_lowercase()) {
                    suffix.push(symbol);
                }
            }
        }
        parts.reverse();
        Some(parts)
    }
}