datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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.

//! Calculates row-count bounds, anchor and exclusion flags, and compact-path
//! information from a pattern.

use super::{Pattern, RepetitionQuantifier, Symbol};

/// Row bounds and flags derived from one recursive walk over a pattern AST.
///
/// This bundles the planner-side properties that are otherwise frequently
/// recomputed independently by row-bounds, anchor checks, exclusion checks,
/// and downstream compilation metadata extraction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PatternStructuralInfo {
    min_match_rows: usize,
    max_match_rows: Option<usize>,
    has_anchors: bool,
    has_exclusions: bool,
    anchored_at_end: bool,
}

/// Information about a pattern with fixed prefix/suffix and a variable middle.
///
/// This enables compact path reconstruction from `(start_row, end_row)` when a
/// pattern has one unbounded middle symbol surrounded by fixed-width prefix and
/// suffix segments.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FixedPrefixSuffixInfo {
    /// Fixed named-symbol runs before the variable middle, in pattern order.
    pub prefix: Vec<(String, usize)>,
    /// Name of the single unbounded middle symbol.
    pub middle: String,
    /// Fixed named-symbol runs after the variable middle, in pattern order.
    pub suffix: Vec<(String, usize)>,
    /// Total rows consumed by `prefix`.
    pub prefix_rows: usize,
    /// Total rows consumed by `suffix`.
    pub suffix_rows: usize,
    /// Minimum rows consumed by the variable middle.
    pub middle_min_rows: usize,
}

/// Combined result of the structural and compact-path analyses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PatternAnalysisSummary {
    structural_info: PatternStructuralInfo,
    compact_single_symbol_name: Option<String>,
    fixed_prefix_suffix: Option<FixedPrefixSuffixInfo>,
}

enum PatternElement<'a> {
    Fixed(&'a str, usize),
    Variable(&'a str, usize),
}

impl PatternStructuralInfo {
    const fn new(
        min_match_rows: usize,
        max_match_rows: Option<usize>,
        has_anchors: bool,
        has_exclusions: bool,
        anchored_at_end: bool,
    ) -> Self {
        Self {
            min_match_rows,
            max_match_rows,
            has_anchors,
            has_exclusions,
            anchored_at_end,
        }
    }

    fn analyze(pattern: &Pattern) -> Self {
        match pattern {
            Pattern::Symbol(symbol) => Self::symbol_info(symbol, false),
            Pattern::Exclude(symbol) => Self::symbol_info(symbol, true),
            Pattern::Permute(symbols) => Self::for_permute(symbols),
            Pattern::Concat(patterns) => {
                let child_info = patterns.iter().map(Self::analyze).collect::<Vec<_>>();
                Self::from_concat_children(&child_info)
            }
            Pattern::Group(inner) => Self::analyze(inner),
            Pattern::Alternation(patterns) => {
                let child_info = patterns.iter().map(Self::analyze).collect::<Vec<_>>();
                Self::from_alternation_children(&child_info)
            }
            Pattern::Repetition(inner, quantifier) => {
                Self::from_repetition_child(Self::analyze(inner), quantifier)
            }
        }
    }

    const fn symbol_info(symbol: &Symbol, is_excluded: bool) -> Self {
        match symbol {
            Symbol::Named(_) => Self::new(1, Some(1), false, is_excluded, false),
            Symbol::Start => Self::new(0, Some(0), true, is_excluded, false),
            Symbol::End => Self::new(0, Some(0), true, is_excluded, !is_excluded),
        }
    }

    /// Structural facts for a `PERMUTE(...)` sequence.
    pub fn for_permute(symbols: &[Symbol]) -> Self {
        let mut named_count = 0usize;
        let mut has_anchors = false;
        for symbol in symbols {
            match symbol {
                Symbol::Named(_) => named_count += 1,
                Symbol::Start | Symbol::End => has_anchors = true,
            }
        }
        Self::new(named_count, Some(named_count), has_anchors, false, false)
    }

    /// Structural facts for a concatenation computed from child summaries.
    pub fn from_concat_children(child_info: &[Self]) -> Self {
        let mut min_match_rows = 0usize;
        let mut max_match_rows = Some(0usize);
        let mut has_anchors = false;
        let mut has_exclusions = false;
        let mut anchored_at_end = false;

        for info in child_info {
            min_match_rows = min_match_rows.saturating_add(info.min_match_rows);
            max_match_rows = match (max_match_rows, info.max_match_rows) {
                (Some(lhs), Some(rhs)) => lhs.checked_add(rhs),
                _ => None,
            };
            has_anchors |= info.has_anchors;
            has_exclusions |= info.has_exclusions;
            anchored_at_end = if info.can_match_empty() {
                anchored_at_end || info.anchored_at_end
            } else {
                info.anchored_at_end
            };
        }

        Self::new(
            min_match_rows,
            max_match_rows,
            has_anchors,
            has_exclusions,
            anchored_at_end,
        )
    }

    /// Structural facts for an alternation computed from child summaries.
    pub fn from_alternation_children(child_info: &[Self]) -> Self {
        let mut min_match_rows: Option<usize> = None;
        let mut max_match_rows = Some(0usize);
        let mut has_anchors = false;
        let mut has_exclusions = false;
        let mut anchored_at_end = !child_info.is_empty();

        for info in child_info {
            min_match_rows =
                Some(min_match_rows.map_or(info.min_match_rows, |current| {
                    current.min(info.min_match_rows)
                }));
            max_match_rows = match (max_match_rows, info.max_match_rows) {
                (Some(lhs), Some(rhs)) => Some(lhs.max(rhs)),
                _ => None,
            };
            has_anchors |= info.has_anchors;
            has_exclusions |= info.has_exclusions;
            anchored_at_end &= info.anchored_at_end;
        }

        Self::new(
            min_match_rows.unwrap_or(0),
            max_match_rows,
            has_anchors,
            has_exclusions,
            anchored_at_end,
        )
    }

    /// Structural facts for a repetition computed from the inner child summary.
    pub fn from_repetition_child(
        inner_info: Self,
        quantifier: &RepetitionQuantifier,
    ) -> Self {
        let min_match_rows = inner_info
            .min_match_rows
            .saturating_mul(quantifier.min_repetitions() as usize);
        let max_match_rows =
            match (inner_info.max_match_rows, quantifier.max_repetitions()) {
                (Some(0), _) | (_, Some(0)) => Some(0),
                (Some(inner_max), Some(count)) => inner_max.checked_mul(count as usize),
                _ => None,
            };

        Self::new(
            min_match_rows,
            max_match_rows,
            inner_info.has_anchors,
            inner_info.has_exclusions,
            quantifier.fixed_count() == Some(1) && inner_info.anchored_at_end,
        )
    }

    /// Return the structural minimum, saturating at `usize::MAX` on overflow.
    pub const fn min_match_rows(self) -> usize {
        self.min_match_rows
    }

    /// Return a structural upper bound, or `None` if unbounded or larger than `usize`.
    pub const fn max_match_rows(self) -> Option<usize> {
        self.max_match_rows
    }

    /// Returns `true` when the pattern contains any anchors.
    pub const fn has_anchors(self) -> bool {
        self.has_anchors
    }

    /// Returns `true` when the pattern contains any exclusions.
    pub const fn has_exclusions(self) -> bool {
        self.has_exclusions
    }

    /// Returns `true` when the pattern is structurally anchored at the end.
    pub const fn anchored_at_end(self) -> bool {
        self.anchored_at_end
    }

    /// Returns `true` when the pattern can match without consuming any rows.
    pub const fn can_match_empty(self) -> bool {
        self.min_match_rows == 0
    }
}

impl Pattern {
    /// Returns the shared pattern-analysis summary for this pattern.
    ///
    /// Use this when a caller needs an owned bundle of structural and
    /// compact-path facts from the same AST.
    pub(crate) fn analysis_summary(&self) -> PatternAnalysisSummary {
        PatternAnalysisSummary::analyze(self)
    }

    /// Returns shared structural facts for this pattern.
    ///
    /// This calculates the pattern properties commonly needed by planning,
    /// optimization, and compilation in one traversal.
    pub fn structural_info(&self) -> PatternStructuralInfo {
        PatternStructuralInfo::analyze(self)
    }

    fn flatten_to_elements(&self) -> Option<Vec<PatternElement<'_>>> {
        let mut elements = Vec::new();
        self.append_elements(&mut elements)?;
        Some(elements)
    }

    fn append_elements<'a>(
        &'a self,
        elements: &mut Vec<PatternElement<'a>>,
    ) -> Option<()> {
        match self {
            Pattern::Symbol(Symbol::Named(name)) => {
                elements.push(PatternElement::Fixed(name, 1));
            }
            Pattern::Symbol(Symbol::Start | Symbol::End)
            | Pattern::Exclude(_)
            | Pattern::Permute(_)
            | Pattern::Alternation(_) => return None,
            Pattern::Group(inner) => inner.append_elements(elements)?,
            Pattern::Concat(patterns) => {
                for pattern in patterns {
                    pattern.append_elements(elements)?;
                }
            }
            Pattern::Repetition(inner, quantifier) => {
                let name = inner.get_single_named_symbol()?;
                let quantifier = quantifier.normalized();

                if quantifier.is_reluctant() && quantifier.fixed_count().is_none() {
                    return None;
                }
                let element = if let Some(count) = quantifier.fixed_count() {
                    PatternElement::Fixed(name, count as usize)
                } else if quantifier.max_repetitions().is_none() {
                    PatternElement::Variable(name, quantifier.min_repetitions() as usize)
                } else {
                    return None;
                };
                elements.push(element);
            }
        }
        Some(())
    }
}

impl PatternAnalysisSummary {
    fn analyze(pattern: &Pattern) -> Self {
        Self {
            structural_info: pattern.structural_info(),
            compact_single_symbol_name: pattern.single_symbol_name().map(str::to_string),
            fixed_prefix_suffix: pattern
                .flatten_to_elements()
                .as_deref()
                .and_then(fixed_prefix_suffix_from_elements),
        }
    }

    /// Return the pattern's row limits and structural flags.
    pub const fn structural_info(&self) -> PatternStructuralInfo {
        self.structural_info
    }

    /// Returns the compact-path single-symbol name, if the pattern can be
    /// reduced to a single named symbol with repetition.
    pub fn compact_single_symbol_name(&self) -> Option<&str> {
        self.compact_single_symbol_name.as_deref()
    }

    /// Returns the fixed prefix/suffix structure, if present.
    pub fn fixed_prefix_suffix_structure(&self) -> Option<&FixedPrefixSuffixInfo> {
        self.fixed_prefix_suffix.as_ref()
    }
}

fn fixed_prefix_suffix_from_elements(
    elements: &[PatternElement<'_>],
) -> Option<FixedPrefixSuffixInfo> {
    let (variable_idx, middle_name, middle_min_rows) = elements
        .iter()
        .enumerate()
        .find_map(|(index, element)| match *element {
            PatternElement::Variable(name, min_rows) => Some((index, name, min_rows)),
            PatternElement::Fixed(_, _) => None,
        })?;

    let fixed_runs = |elements: &[PatternElement<'_>]| {
        let mut runs = Vec::new();
        let mut rows = 0usize;
        for element in elements {
            let PatternElement::Fixed(name, count) = *element else {
                return None;
            };
            rows = rows.checked_add(count)?;
            runs.push((name.to_string(), count));
        }
        Some((runs, rows))
    };
    let (prefix, prefix_rows) = fixed_runs(&elements[..variable_idx])?;
    let (suffix, suffix_rows) = fixed_runs(&elements[variable_idx + 1..])?;

    Some(FixedPrefixSuffixInfo {
        prefix,
        middle: middle_name.to_string(),
        suffix,
        prefix_rows,
        suffix_rows,
        middle_min_rows,
    })
}