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.

//! Alternation optimization passes.
//!
//! Failure and duplicate branches can disappear. Implication can remove only a
//! later subset branch, preserving left-to-right preference; unconditional
//! truth never discards later ordered branches.

use std::collections::HashSet;

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

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

impl<'a> PatternOptimizer<'a> {
    /// Optimize an alternation pattern.
    pub(crate) fn optimize_alternation(
        &self,
        pats: &[Pattern],
        following_symbols: &[String],
        suffix_can_match_empty: bool,
        rows_before: RowsConsumed,
    ) -> NormalizedPattern {
        let mut branches = Vec::with_capacity(pats.len());
        let mut seen = HashSet::with_capacity(pats.len());

        for pat in pats {
            match self.optimize_with_context(
                pat,
                following_symbols,
                suffix_can_match_empty,
                rows_before,
            ) {
                NormalizedPattern::Never => {}
                NormalizedPattern::Epsilon => {
                    let empty = Pattern::Concat(vec![]);
                    if seen.insert(empty.clone()) {
                        branches.push(empty);
                    }
                }
                NormalizedPattern::Ast(p) => {
                    if !self.is_subsumed_by_existing(&p, &branches)
                        && seen.insert(p.clone())
                    {
                        branches.push(p);
                    }
                }
            }
        }

        if branches.is_empty() {
            return if pats.is_empty() {
                NormalizedPattern::Ast(Pattern::Alternation(Vec::new()))
            } else {
                NormalizedPattern::Never
            };
        }

        if branches.len() == 1 {
            return match branches.pop().expect("one optimized alternation branch") {
                Pattern::Concat(parts) if parts.is_empty() => NormalizedPattern::Epsilon,
                branch => NormalizedPattern::Ast(branch),
            };
        }

        NormalizedPattern::Ast(Pattern::Alternation(branches))
    }

    /// Return whether an earlier alternative already accepts every match of `pat`.
    ///
    /// This implementation handles single named symbols. If `P1` implies `P2`,
    /// every row accepted by `P1` is also accepted by `P2`.
    ///
    /// For example, in `(B | A)` where `A` implies `B`, the later `A` branch is
    /// redundant under the caller's history-independence guarantee: every row it
    /// accepts can use the earlier `B` branch without changing later decisions.
    /// The reverse order is not safe because `B` may accept rows that
    /// `A` does not. `MATCH_RECOGNIZE` alternatives are tried left to right.
    pub(crate) fn is_subsumed_by_existing(
        &self,
        pat: &Pattern,
        existing: &[Pattern],
    ) -> bool {
        // Only direct named symbols have implication facts at this stage.
        if let Pattern::Symbol(Symbol::Named(pat_sym)) = pat {
            for existing_pat in existing {
                if let Pattern::Symbol(Symbol::Named(existing_sym)) = existing_pat {
                    // The later symbol is redundant when it is equal to, or a
                    // subset of, the earlier symbol.
                    if pat_sym.eq_ignore_ascii_case(existing_sym)
                        || self.symbol_implies(pat_sym, existing_sym)
                    {
                        return true;
                    }
                }
            }
        }

        false
    }
}