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.

//! Builds NFA fragments for repetition quantifiers in `MATCH_RECOGNIZE` patterns.
//!
//! Bounded optional tails (`{m,n}` where `n > m`) share one lowering helper so
//! preferred continuation or exit transitions are built the same way for
//! zero and positive minimums.

use super::super::compiler::NfaBuilder;
use crate::core::{Pattern, RepetitionPreference, RepetitionQuantifier};
use datafusion::common::Result;

/// Compile a quantified sub-pattern.
///
/// Adds the states for a repetition (`*`, `+`, or `{m,n}`) of `inner` to the
/// supplied `NfaBuilder` and returns the fragment's start and end states.
pub(crate) fn compile_quantifier(
    b: &mut NfaBuilder,
    inner: &Pattern,
    quant: &RepetitionQuantifier,
) -> Result<(usize, usize)> {
    let bounds = quant.bounds();
    let min = bounds.min as usize;
    let max = bounds.max.map(|max| max as usize);
    let preference = bounds.preference;
    if let Some(max) = max
        && min > max
    {
        return datafusion::common::plan_err!(
            "MATCH_RECOGNIZE pattern quantifier lower bound {} exceeds upper bound {}",
            min,
            max
        );
    }

    // Degenerate {0} pattern – single empty state.
    if min == 0 && max == Some(0) {
        let s = b.new_state(false)?;
        return Ok((s, s));
    }

    // Give zero-minimum repeats a stable entry state for the bypass edge.
    let entry = if min == 0 {
        let entry = b.new_state(false)?;
        Some(entry)
    } else {
        None
    };

    let mut first_start = entry;
    let mut last_end = entry;
    let mut last_copy_start = None; // for looping

    // Build the required copies first.
    for i in 0..min {
        let (s, e) = b.build_pattern(inner)?;
        if i == 0 {
            first_start = Some(entry.unwrap_or(s));
        }
        if let Some(last_end_state) = last_end {
            b.add_epsilon(last_end_state, s);
        }
        last_end = Some(e);
        last_copy_start = Some(s);
    }

    // Add the optional copies up to the upper bound.
    if let Some(max_bound) = max {
        let remaining = max_bound.saturating_sub(min);
        if remaining > 0 {
            last_end = Some(compile_bounded_optional_tail(
                b,
                inner,
                last_end.expect("bounded tail requires an entry state"),
                remaining,
                preference,
            )?);
        }
    }

    // Add a loop for +, *, and {m,}.
    if max.is_none() {
        b.record_choice();
        if last_copy_start.is_none() {
            // `*` needs one copy to serve as the loop body.
            let (s, e) = b.build_pattern(inner)?;
            last_copy_start = Some(s);
            last_end = Some(e);
        }

        let exit = b.new_state(false)?;

        let last_end_state =
            last_end.expect("unbounded quantifier requires an end state");

        let continuation =
            last_copy_start.expect("unbounded quantifier requires a loop start");
        for target in ordered_targets(preference, continuation, exit) {
            b.add_epsilon(last_end_state, target);
        }
        b.record_loop_back_edge(
            last_end_state,
            continuation,
            preference == RepetitionPreference::Possessive,
        );

        if preference == RepetitionPreference::Possessive {
            // Record the split point so runtime can suppress the exit branch when
            // the continue branch can still consume the current row.
            b.record_possessive_decision(last_end_state, continuation, exit);

            // Keep the exit edge for rows the loop cannot consume. The recorded
            // decision tells runtime to suppress it whenever the loop can continue.
        }
        if min == 0 {
            let entry = first_start.expect("zero-min quantifier requires an entry state");
            for target in ordered_targets(preference, continuation, exit) {
                b.add_epsilon(entry, target);
            }
        }

        last_end = Some(exit);
    }

    Ok((
        first_start.expect("quantifier compilation must produce a start state"),
        last_end.expect("quantifier compilation must produce an end state"),
    ))
}

fn ordered_targets(
    preference: RepetitionPreference,
    continuation: usize,
    exit: usize,
) -> [usize; 2] {
    if preference == RepetitionPreference::Reluctant {
        [exit, continuation]
    } else {
        [continuation, exit]
    }
}

fn compile_bounded_optional_tail(
    b: &mut NfaBuilder,
    inner: &Pattern,
    tail_start: usize,
    remaining: usize,
    preference: RepetitionPreference,
) -> Result<usize> {
    b.record_choice();
    let exit = b.new_state(false)?;
    let mut last_end = tail_start;
    for _ in 0..remaining {
        let (s, e) = b.build_pattern(inner)?;
        for target in ordered_targets(preference, s, exit) {
            b.add_epsilon(last_end, target);
        }
        last_end = e;
    }

    b.add_epsilon(last_end, exit);
    Ok(exit)
}