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.

//! Structural normalization of named-symbol runs and adjacent identical anchors.
//!
//! Different paths through such a run are indistinguishable only when they
//! consume the same number of rows with the same exclusion flag. Preserve the
//! order in which distinct lengths first become available, as well as the set
//! of lengths. No predicate truth or symbol relationships are needed.

use crate::core::pattern::QuantifierBounds;
use crate::core::{Pattern, RepetitionPreference, RepetitionQuantifier, Symbol};

/// Merge symbol runs exposed by optimization.
pub(super) fn normalize_symbol_runs(pattern: Pattern) -> Pattern {
    normalize_runs(pattern, false)
}

/// Normalize the input tree even when optional data-derived pruning is disabled.
pub(super) fn normalize_symbol_and_anchor_runs(pattern: Pattern) -> Pattern {
    normalize_runs(pattern, true)
}

fn normalize_runs(pattern: Pattern, dedup_anchors: bool) -> Pattern {
    match pattern {
        Pattern::Group(inner) => normalize_runs(*inner, dedup_anchors),
        Pattern::Concat(parts) => {
            let mut normalized = Vec::with_capacity(parts.len());
            for part in parts {
                match normalize_runs(part, dedup_anchors) {
                    Pattern::Concat(parts) => {
                        for part in parts {
                            push_concat_part(&mut normalized, part, dedup_anchors);
                        }
                    }
                    part => push_concat_part(&mut normalized, part, dedup_anchors),
                }
            }
            if normalized.len() == 1 {
                normalized.pop().expect("one normalized concat part")
            } else {
                Pattern::Concat(normalized)
            }
        }
        Pattern::Alternation(parts) => Pattern::Alternation(
            parts
                .into_iter()
                .map(|part| normalize_runs(part, dedup_anchors))
                .collect(),
        ),
        Pattern::Repetition(inner, quantifier) => {
            let inner = normalize_runs(*inner, dedup_anchors);
            let quantifier = quantifier.normalized();
            let outer = quantifier.bounds();
            // Invalid programmatic bounds still belong to the compiler's
            // existing diagnostic; do not erase them through an empty child.
            if !valid_bounds(outer) {
                return Pattern::Repetition(Box::new(inner), quantifier);
            }
            if outer.fixed_count() == Some(0)
                || matches!(&inner, Pattern::Concat(parts) if parts.is_empty())
            {
                return Pattern::Concat(vec![]);
            }
            if outer.fixed_count() == Some(1) {
                return inner;
            }
            if matches!(&inner, Pattern::Repetition(_, _))
                && let Some((leaf, bounds)) = symbol_run(&inner)
                && let Some(bounds) = nested_bounds(bounds, outer)
            {
                return run_pattern(leaf.clone(), bounds);
            }
            Pattern::Repetition(Box::new(inner), quantifier)
        }
        other => other,
    }
}

fn push_concat_part(parts: &mut Vec<Pattern>, part: Pattern, dedup_anchors: bool) {
    if dedup_anchors
        && matches!(&part, Pattern::Symbol(Symbol::Start | Symbol::End))
        && parts.last() == Some(&part)
    {
        return;
    }
    let merged = parts.last().and_then(|previous| {
        let (left, left_bounds) = symbol_run(previous)?;
        let (right, right_bounds) = symbol_run(&part)?;
        if left != right {
            return None;
        }
        // A fixed count has no preference decision. Otherwise both runs must
        // enumerate lengths in the same direction. Possessive runs cannot give
        // rows back to a following run, even one with the same symbol.
        // In a shared direction the first distinct total lengths have that
        // same order; later splits only repeat identical classified histories.
        let preference = common_preference(left_bounds, right_bounds)?;
        let bounds = QuantifierBounds {
            min: left_bounds.min.checked_add(right_bounds.min)?,
            max: add_max(left_bounds.max, right_bounds.max)?,
            preference,
        };
        Some(run_pattern(left.clone(), bounds))
    });
    if let Some(merged) = merged {
        *parts.last_mut().expect("merged a preceding concat part") = merged;
    } else {
        parts.push(part);
    }
}

/// Return a flat named-symbol run; anchors and different exclusion flags are
/// never interchangeable. Exact name identity also preserves caller aliases.
fn symbol_run(pattern: &Pattern) -> Option<(&Pattern, QuantifierBounds)> {
    match pattern {
        Pattern::Symbol(Symbol::Named(_)) | Pattern::Exclude(Symbol::Named(_)) => {
            Some((pattern, RepetitionQuantifier::Exactly(1).bounds()))
        }
        Pattern::Repetition(inner, quantifier)
            if matches!(
                inner.as_ref(),
                Pattern::Symbol(Symbol::Named(_)) | Pattern::Exclude(Symbol::Named(_))
            ) && valid_bounds(quantifier.bounds()) =>
        {
            Some((inner, quantifier.bounds()))
        }
        _ => None,
    }
}

fn valid_bounds(bounds: QuantifierBounds) -> bool {
    bounds.max.is_none_or(|max| bounds.min <= max)
}

fn common_preference(
    left: QuantifierBounds,
    right: QuantifierBounds,
) -> Option<RepetitionPreference> {
    match (left.fixed_count(), right.fixed_count()) {
        (Some(_), Some(_)) => Some(RepetitionPreference::Greedy),
        (Some(_), None) if !right.is_possessive() => Some(right.preference),
        (None, Some(_)) if !left.is_possessive() => Some(left.preference),
        (None, None) if left.preference == right.preference && !left.is_possessive() => {
            Some(left.preference)
        }
        _ => None,
    }
}

fn nested_bounds(
    inner: QuantifierBounds,
    outer: QuantifierBounds,
) -> Option<QuantifierBounds> {
    let preference = common_preference(inner, outer)?;
    // A fixed number of inner intervals is a sum of intervals. With a variable
    // outer count, min <= 1 makes neighboring counts overlap or touch, and the
    // first distinct lengths remain ordered by the shared preference: leaving
    // or adding a copy cannot skip an attainable length between those counts.
    //
    // Contiguous lengths alone are insufficient: (A{2,3}){1,2} can prefer
    // three rows over four, because the first inner greedily takes three and
    // the outer repeat can exit before that inner gives a row back.
    if outer.fixed_count().is_none() && inner.min > 1 {
        return None;
    }
    Some(QuantifierBounds {
        min: inner.min.checked_mul(outer.min)?,
        max: match (inner.max, outer.max) {
            (Some(inner), Some(outer)) => Some(inner.checked_mul(outer)?),
            _ => None,
        },
        preference,
    })
}

fn add_max(left: Option<u32>, right: Option<u32>) -> Option<Option<u32>> {
    Some(match (left, right) {
        (Some(left), Some(right)) => Some(left.checked_add(right)?),
        _ => None,
    })
}

fn run_pattern(leaf: Pattern, bounds: QuantifierBounds) -> Pattern {
    if bounds.fixed_count() == Some(0) {
        return Pattern::Concat(vec![]);
    }
    if bounds.fixed_count() == Some(1) {
        return leaf;
    }
    let quantifier = match bounds.max {
        Some(max) => RepetitionQuantifier::Range(bounds.min, max),
        None => RepetitionQuantifier::AtLeast(bounds.min),
    };
    let quantifier = if bounds.is_reluctant() {
        quantifier
            .reluctant_variant()
            .expect("constructed a greedy quantifier")
    } else {
        quantifier
    };
    Pattern::Repetition(Box::new(leaf), quantifier.normalized())
}