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.

//! Graph-derived necessary Boolean conditions before allocating candidate state.
use super::fallible_vec::{filled, reserved};
use crate::core::SymbolId;
use crate::execution::matching::{ResolvedBoolColumn, SymbolColumn};
use crate::nfa::{AnchorEnvironment, CompiledAutomaton};
use datafusion::common::{DataFusionError, Result};

/// Necessary conditions at consecutive row offsets before opening a candidate.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct StaticStartWindow {
    first: Option<Box<[StartCondition]>>,
    second: Option<Box<[StartCondition]>>,
}

/// Alternatives at one depth. A leading AND extraction rejects only on FALSE.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum StartCondition {
    StaticSymbol(SymbolId),
    NecessaryAnd(Box<[ResolvedBoolColumn]>),
}

impl StaticStartWindow {
    pub(crate) fn retained_size_bytes(&self) -> Result<usize> {
        let mut total = Some(size_of::<Self>() + 2 * size_of::<usize>());
        for conditions in self.first.iter().chain(&self.second) {
            total = total.and_then(|n| n.checked_add(size_of_val(conditions.as_ref())));
            for condition in conditions.iter() {
                if let StartCondition::NecessaryAnd(columns) = condition {
                    total =
                        total.and_then(|n| n.checked_add(size_of_val(columns.as_ref())));
                }
            }
        }
        total.ok_or_else(|| {
            DataFusionError::ResourcesExhausted(
                "MATCH_RECOGNIZE retained start-symbol plan exceeds usize".into(),
            )
        })
    }
    fn build_conditions<'a>(
        symbol_ids: &[SymbolId],
        has_static_column: &[bool],
        necessary_columns: &impl Fn(SymbolId) -> &'a [ResolvedBoolColumn],
    ) -> Result<Option<Box<[StartCondition]>>> {
        if symbol_ids.is_empty() {
            return Ok(None);
        }
        let mut conditions = Vec::new();
        conditions
            .try_reserve_exact(symbol_ids.len())
            .map_err(|error| {
                DataFusionError::ResourcesExhausted(format!(
                    "MATCH_RECOGNIZE start-symbol conditions could not reserve {} entries: {error}",
                    symbol_ids.len()
                ))
            })?;
        for &symbol_id in symbol_ids {
            if has_static_column[symbol_id.index()] {
                conditions.push(StartCondition::StaticSymbol(symbol_id));
            } else {
                let necessary = necessary_columns(symbol_id);
                if necessary.is_empty() {
                    return Ok(None);
                }
                let mut copied = reserved(necessary.len(), "program entries")?;
                copied.extend_from_slice(necessary);
                conditions.push(StartCondition::NecessaryAnd(copied.into_boxed_slice()));
            }
        }
        Ok(Some(conditions.into_boxed_slice()))
    }

    pub(crate) fn try_new_with_conditions<'a>(
        compiled: &CompiledAutomaton,
        symbol_columns: &[SymbolColumn],
        necessary_columns: impl Fn(SymbolId) -> &'a [ResolvedBoolColumn],
        can_cross: impl Fn(SymbolId) -> bool,
    ) -> Result<Self> {
        let symbol_slots = compiled.num_symbols();
        let mut has_static_column = filled(symbol_slots, false, "program entries")?;
        for column in symbol_columns {
            let dense_index = column.id.index();
            let Some(slot) = has_static_column.get_mut(dense_index) else {
                return Err(DataFusionError::Internal(format!(
                    "MATCH_RECOGNIZE start-symbol column {} is outside the compiled automaton's {symbol_slots}-slot table",
                    column.id
                )));
            };
            *slot = true;
        }

        if compiled.min_match_rows() == 0 {
            return Ok(Self::default());
        }
        let nfa = compiled.nfa();
        let start = nfa.start_state();
        let anchored = compiled.has_anchors();
        // A mandatory ^ uses only the physical-start closure. An interior
        // alternative must retain the union; later anchors stay with the matcher.
        let sources = if anchored {
            [
                Some(
                    compiled
                        .anchor_dispatch_closure(AnchorEnvironment::PhysicalStart, start),
                ),
                (!compiled.has_mandatory_start_anchor_prefix()).then(|| {
                    compiled.anchor_dispatch_closure(
                        AnchorEnvironment::PhysicalInterior,
                        start,
                    )
                }),
            ]
        } else {
            [Some(nfa.state(start).unconditional_dispatch()), None]
        };
        let accepts_empty = if anchored {
            compiled
                .anchor_first_accepting_state(AnchorEnvironment::PhysicalStart, start)
                .is_some()
                || (!compiled.has_mandatory_start_anchor_prefix()
                    && compiled
                        .anchor_first_accepting_state(
                            AnchorEnvironment::PhysicalInterior,
                            start,
                        )
                        .is_some())
        } else {
            compiled.unconditional_first_accepting_state()[start.index()].is_some()
        };
        if accepts_empty {
            return Ok(Self::default());
        }
        let mut seen_sources = filled(nfa.state_count(), false, "start-window sources")?;
        let mut seen_symbols = filled(symbol_slots, false, "start-window symbols")?;
        let mut symbols = reserved(symbol_slots, "start-window symbols")?;
        for group in sources.into_iter().flatten() {
            collect_symbols(
                compiled,
                group,
                &mut seen_sources,
                &mut seen_symbols,
                &mut symbols,
            );
        }
        let mut window = Self {
            first: Self::build_conditions(
                &symbols,
                &has_static_column,
                &necessary_columns,
            )?,
            ..Self::default()
        };
        if window.first.is_none() || anchored || compiled.min_match_rows() < 2 {
            return Ok(window);
        }
        // A later impossible row must not suppress a demanded residual predicate
        // or fallible aggregate update on the first row.
        if !symbols
            .iter()
            .all(|id| has_static_column[id.index()] && can_cross(*id))
        {
            return Ok(window);
        }
        seen_sources.fill(false);
        seen_symbols.fill(false);
        symbols.clear();
        // Only the immediate successors of the start closure are needed. Shared
        // dispatch sources are visited once, without a frontier or depth queue.
        for &source in nfa.state(start).unconditional_dispatch() {
            for (_, targets) in nfa.state(source).transition_rows() {
                for &target in targets {
                    if compiled.unconditional_first_accepting_state()[target.index()]
                        .is_some()
                    {
                        return Ok(window);
                    }
                    collect_symbols(
                        compiled,
                        nfa.state(target).unconditional_dispatch(),
                        &mut seen_sources,
                        &mut seen_symbols,
                        &mut symbols,
                    );
                }
            }
        }
        window.second =
            Self::build_conditions(&symbols, &has_static_column, &necessary_columns)?;
        Ok(window)
    }

    #[inline]
    pub(crate) fn enabled_conditions(&self) -> Option<&[StartCondition]> {
        self.first.as_ref().map(AsRef::as_ref)
    }

    #[inline]
    pub(crate) fn enabled_successor_conditions(&self) -> Option<&[StartCondition]> {
        self.second.as_ref().map(AsRef::as_ref)
    }
}

/// Collect one row's alternatives, visiting each dispatch source once.
fn collect_symbols(
    compiled: &CompiledAutomaton,
    sources: &[crate::nfa::AutomatonStateId],
    seen_sources: &mut [bool],
    seen_symbols: &mut [bool],
    symbols: &mut Vec<SymbolId>,
) {
    for &source in sources {
        if std::mem::replace(&mut seen_sources[source.index()], true) {
            continue;
        }
        for (symbol, targets) in compiled.nfa().state(source).transition_rows() {
            if !targets.is_empty()
                && !std::mem::replace(&mut seen_symbols[symbol.index()], true)
            {
                symbols.push(symbol);
            }
        }
    }
}