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.

//! Builds the private, mutable draft automaton for a `MATCH_RECOGNIZE`
//! [`Pattern`]. The compilation sealer consumes this draft to create the public
//! immutable graph.

use crate::core::{Pattern, Symbol};
use datafusion::common::{DataFusionError, Result};
use smallvec::SmallVec;

use super::compilation::cost::{
    METRIC_NFA_STATES, PatternCompileLimits, compile_cost_err,
};
use super::compilation::permute;
use crate::nfa::types::AnchorPredicate;

use super::compilation::concat_alt::{compile_alternation, compile_concat};

fn representational_exhaustion(resource: &str) -> DataFusionError {
    DataFusionError::ResourcesExhausted(format!(
        "MATCH_RECOGNIZE NFA {resource} exhausted its representational domain"
    ))
}

fn checked_next_state_count(current: usize) -> Result<usize> {
    current
        .checked_add(1)
        .ok_or_else(|| representational_exhaustion("state identifier"))
}

/// One epsilon edge while the automaton is under construction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DraftEpsilonTransition {
    pub(crate) target: usize,
    pub(crate) predicate: Option<AnchorPredicate>,
}

/// The single row-consuming edge owned by a draft state.
#[derive(Debug, Clone)]
pub(crate) struct DraftSymbolTransition {
    pub(crate) symbol: String,
    pub(crate) target: usize,
}

/// One mutable, name-keyed state while the automaton is under construction.
#[derive(Debug, Clone)]
pub(crate) struct DraftState {
    pub(crate) is_accepting: bool,
    pub(crate) symbol_transition: Option<DraftSymbolTransition>,
    pub(crate) epsilon_transitions: SmallVec<[DraftEpsilonTransition; 2]>,
    pub(crate) is_excluded: bool,
}

/// Possessive-loop decision edge recorded during draft construction.
///
/// At `from_state`, the engine can either continue via `continue_state` or exit
/// via `exit_state`. For possessive quantifiers, the exit branch should be
/// suppressed when the continue branch can consume the current row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DraftPossessiveDecisionEdge {
    pub(crate) from_state: usize,
    pub(crate) continue_state: usize,
    pub(crate) exit_state: usize,
}

/// Unbounded-loop back-edge recorded during draft construction.
///
/// Closure computation suppresses `from_state -> continue_state` once
/// `continue_state` is already active on the current zero-row DFS stack so
/// nullable iterations exit at their SQL:2016 precedence rank without cycling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DraftLoopBackEdge {
    pub(crate) from_state: usize,
    pub(crate) continue_state: usize,
    pub(crate) is_possessive: bool,
}

/// Complete private graph consumed by the automaton sealer.
#[derive(Debug)]
pub(crate) struct DraftAutomaton {
    pub(crate) states: Vec<DraftState>,
    pub(crate) start_state: usize,
    pub(crate) possessive_decisions: Vec<DraftPossessiveDecisionEdge>,
    pub(crate) loop_back_edges: Vec<DraftLoopBackEdge>,
    pub(crate) has_choices: bool,
    pub(crate) pattern_display: String,
}

#[derive(Debug, Default)]
pub(crate) struct NfaBuilder {
    states: Vec<DraftState>,
    /// Constructed preference sites, kept separate from closure size so route
    /// selection retains its established behavior for nullable and fixed graphs.
    has_choices: bool,
    /// Possessive loop decisions captured during quantifier compilation.
    possessive_decisions: Vec<DraftPossessiveDecisionEdge>,
    /// Unbounded quantifier back-edges captured during quantifier compilation.
    loop_back_edges: Vec<DraftLoopBackEdge>,
    limits: PatternCompileLimits,
    pattern_display: String,
}

impl NfaBuilder {
    /// Create a fresh, empty builder.
    fn new(limits: PatternCompileLimits, pattern_display: String) -> Self {
        Self {
            states: Vec::new(),
            has_choices: false,
            possessive_decisions: Vec::new(),
            loop_back_edges: Vec::new(),
            limits,
            pattern_display,
        }
    }

    /// Compile a [`Pattern`] into a private mutable draft.
    pub(crate) fn build(
        pattern: &Pattern,
        limits: PatternCompileLimits,
    ) -> Result<DraftAutomaton> {
        let mut b = Self::new(limits, pattern.to_string());
        let (start, end) = b.build_pattern(pattern)?;

        // Add a single accepting sink so the compiled NFA always has exactly
        // one accepting state reachable from the pattern.
        let sink = b.new_state(true)?;
        b.add_epsilon(end, sink);

        Ok(b.finish(start))
    }

    /// Build the canonical one-state draft for a pattern that can never match.
    pub(crate) fn build_never(
        limits: PatternCompileLimits,
        pattern_display: String,
    ) -> Result<DraftAutomaton> {
        let mut b = Self::new(limits, pattern_display);
        let start = b.new_state(false)?;
        Ok(b.finish(start))
    }

    /// Insert a new state and return its identifier.
    pub(crate) fn new_state(&mut self, is_accepting: bool) -> Result<usize> {
        self.new_state_with_exclusion(is_accepting, false)
    }

    /// Insert a new state with exclusion flag and return its identifier.
    pub(crate) fn new_state_with_exclusion(
        &mut self,
        is_accepting: bool,
        is_excluded: bool,
    ) -> Result<usize> {
        let next_count = checked_next_state_count(self.states.len())?;
        if next_count > self.limits.max_nfa_states {
            return compile_cost_err(
                METRIC_NFA_STATES,
                next_count,
                self.limits.max_nfa_states,
                &self.pattern_display,
            );
        }
        let id = self.states.len();
        self.states.try_reserve(1).map_err(|error| {
            DataFusionError::ResourcesExhausted(format!(
                "MATCH_RECOGNIZE NFA state allocation failed while compiling pattern {}: {error}",
                self.pattern_display
            ))
        })?;
        self.states.push(DraftState {
            is_accepting,
            symbol_transition: None,
            epsilon_transitions: SmallVec::new(),
            is_excluded,
        });
        Ok(id)
    }

    fn add_symbol_like_transition(&mut self, start: usize, end: usize, sym: &Symbol) {
        match sym {
            Symbol::Named(name) => {
                let transition = &mut self.states[start].symbol_transition;
                debug_assert!(transition.is_none());
                *transition = Some(DraftSymbolTransition {
                    symbol: name.clone(),
                    target: end,
                });
            }
            Symbol::Start => {
                self.states[start]
                    .epsilon_transitions
                    .push(DraftEpsilonTransition {
                        target: end,
                        predicate: Some(AnchorPredicate::StartOfInput),
                    });
            }
            Symbol::End => {
                self.states[start]
                    .epsilon_transitions
                    .push(DraftEpsilonTransition {
                        target: end,
                        predicate: Some(AnchorPredicate::EndOfInput),
                    });
            }
        }
    }

    fn build_symbol_like(
        &mut self,
        sym: &Symbol,
        is_excluded: bool,
    ) -> Result<(usize, usize)> {
        let start = self.new_state_with_exclusion(false, is_excluded)?;
        let end = self.new_state(false)?;
        self.add_symbol_like_transition(start, end, sym);
        Ok((start, end))
    }

    /// Add an epsilon edge in preference order.
    pub(crate) fn add_epsilon(&mut self, from: usize, to: usize) {
        self.states[from]
            .epsilon_transitions
            .push(DraftEpsilonTransition {
                target: to,
                predicate: None,
            });
    }

    /// Record a constructed preference site for execution-route selection.
    pub(crate) fn record_choice(&mut self) {
        self.has_choices = true;
    }

    /// Register a possessive split decision `(continue | exit)` from `from_state`.
    pub(crate) fn record_possessive_decision(
        &mut self,
        from_state: usize,
        continue_state: usize,
        exit_state: usize,
    ) {
        self.possessive_decisions.push(DraftPossessiveDecisionEdge {
            from_state,
            continue_state,
            exit_state,
        });
    }

    /// Register the loop back-edge `from_state -> continue_state` of an unbounded quantifier.
    pub(crate) fn record_loop_back_edge(
        &mut self,
        from_state: usize,
        continue_state: usize,
        is_possessive: bool,
    ) {
        self.loop_back_edges.push(DraftLoopBackEdge {
            from_state,
            continue_state,
            is_possessive,
        });
    }

    /// Build `pat` into the builder and return its local `(start,end)` indices.
    pub(crate) fn build_pattern(&mut self, pat: &Pattern) -> Result<(usize, usize)> {
        match pat {
            // Single symbol or anchor
            Pattern::Symbol(sym) => self.build_symbol_like(sym, false),
            // Build the inner pattern with its states marked as excluded.
            Pattern::Exclude(sym) => self.build_symbol_like(sym, true),
            // Concatenation – sequentially link sub-patterns.
            Pattern::Concat(parts) => compile_concat(self, parts),
            // Alternation – classic Thompson construction.
            Pattern::Alternation(alts) => compile_alternation(self, alts),

            // Quantifiers / repetition.
            Pattern::Repetition(inner, quant) => {
                super::compilation::quantifier::compile_quantifier(self, inner, quant)
            }

            // Explicit grouping uses the inner pattern's fragment.
            Pattern::Group(inner) => self.build_pattern(inner),
            // PERMUTE – delegate to dedicated helper for clarity.
            Pattern::Permute(symbols) => permute::attach_permute(self, symbols),
        }
    }

    /// Consume the builder and return the completed private draft.
    fn finish(self, start_state: usize) -> DraftAutomaton {
        DraftAutomaton {
            states: self.states,
            start_state,
            possessive_decisions: self.possessive_decisions,
            loop_back_edges: self.loop_back_edges,
            has_choices: self.has_choices,
            pattern_display: self.pattern_display,
        }
    }

    pub(crate) fn limits(&self) -> PatternCompileLimits {
        self.limits
    }

    pub(crate) fn pattern_display(&self) -> &str {
        &self.pattern_display
    }
}