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.

//! Executable per-symbol programs, evaluators, and static prechecks.

use std::sync::Arc;

use crate::core::{SymbolEvalMode, SymbolId};
use datafusion::physical_plan::PhysicalExpr;

use super::bindings::ResolvedBoolColumn;
use super::program::contracts::PhysicalHybridGuardExpr;
use super::program::validated_vm::{
    ExecutableAccumulationProgram, ExecutableEvaluatorKernel, ExecutableNavigationProgram,
};
use super::row_loop;

/// Runtime behavior for one contiguous numeric NFA symbol ID.
///
/// Slot zero represents the NFA's empty symbol. Every user slot stores its
/// chosen evaluator, aggregate updates, static checks, and prediction data.
#[derive(Clone)]
#[allow(
    clippy::large_enum_variant,
    reason = "the dense symbol table keeps user programs contiguous for row-loop access; boxing would add one allocation and pointer chase per symbol"
)]
pub(crate) enum ExecutableSymbolProgram {
    Empty,
    User(ExecutableUserSymbolProgram),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DefineCachePolicy {
    Disabled,
    MatchStart,
}

impl DefineCachePolicy {
    #[inline]
    pub(crate) const fn for_match_start_reuse(enabled: bool) -> Self {
        if enabled {
            Self::MatchStart
        } else {
            Self::Disabled
        }
    }

    #[inline]
    pub(crate) const fn lookup_enabled(self) -> bool {
        matches!(self, Self::MatchStart)
    }
}

/// Exact local predicate implementation selected during executable construction.
#[derive(Clone)]
pub(crate) enum ExecutableIncrementalEvaluator {
    Direct {
        predicate: row_loop::direct_predicate::BoundPredicate,
        source_expr: Arc<dyn PhysicalExpr>,
    },
    Physical {
        expr: Arc<dyn PhysicalExpr>,
    },
}

impl ExecutableIncrementalEvaluator {
    #[inline]
    pub(crate) fn source_expr(&self) -> &Arc<dyn PhysicalExpr> {
        match self {
            Self::Direct { source_expr, .. } => source_expr,
            Self::Physical { expr } => expr,
        }
    }

    pub(super) fn append_physical_expr_roots(
        &self,
        roots: &mut Vec<Arc<dyn PhysicalExpr>>,
    ) {
        match self {
            // Bound predicates load their own row and managed sources. The retained
            // source expression is diagnostic/fallback provenance only.
            Self::Direct { .. } => {}
            Self::Physical { expr } => roots.push(Arc::clone(expr)),
        }
    }
}

/// The evaluator selected for one pattern variable.
#[derive(Clone)]
pub(crate) enum ExecutableSymbolEvaluator {
    Static,
    Incremental(ExecutableIncrementalEvaluator),
    /// The history predicate can have a leading locally evaluable guard.
    History(Option<LeadingGuard>),
}

#[derive(Clone)]
pub(crate) struct LeadingGuard {
    pub(super) expression: PhysicalHybridGuardExpr,
    pub(super) source_expr: Arc<dyn PhysicalExpr>,
}

impl ExecutableSymbolEvaluator {
    #[inline]
    pub(crate) const fn kernel(&self) -> ExecutableEvaluatorKernel {
        match self {
            Self::Static => ExecutableEvaluatorKernel::Static,
            Self::Incremental(ExecutableIncrementalEvaluator::Direct { .. }) => {
                ExecutableEvaluatorKernel::Typed
            }
            _ => ExecutableEvaluatorKernel::Unsupported,
        }
    }

    #[inline]
    pub(crate) const fn may_read_history(&self) -> bool {
        matches!(self, Self::History(_))
    }

    #[inline]
    pub(crate) const fn has_bound_source(&self) -> bool {
        matches!(self, Self::Incremental(_) | Self::History(Some(_)))
    }

    #[inline]
    pub(crate) const fn mode(&self) -> SymbolEvalMode {
        match self {
            Self::Static => SymbolEvalMode::Static,
            Self::Incremental(_) => SymbolEvalMode::Incremental,
            Self::History(Some(_)) => SymbolEvalMode::Hybrid,
            Self::History(None) => SymbolEvalMode::Deferred,
        }
    }

    #[inline]
    pub(crate) fn source_expr(&self) -> Option<&Arc<dyn PhysicalExpr>> {
        match self {
            Self::Incremental(local) => Some(local.source_expr()),
            Self::History(Some(guard)) => Some(&guard.source_expr),
            Self::Static | Self::History(None) => None,
        }
    }

    pub(super) fn append_physical_expr_roots(
        &self,
        roots: &mut Vec<Arc<dyn PhysicalExpr>>,
    ) {
        match self {
            Self::Incremental(local) => local.append_physical_expr_roots(roots),
            Self::History(Some(guard)) => {
                guard.expression.append_physical_expr_roots(roots)
            }
            Self::Static | Self::History(None) => {}
        }
    }
}

/// Aggregate-state work that accompanies one symbol transition.
#[derive(Debug, Clone, Default)]
pub(crate) struct ExecutableAggregateStateProgram {
    pub(super) accumulation: ExecutableAccumulationProgram,
    pub(super) navigation: ExecutableNavigationProgram,
}

/// Bound Boolean prechecks evaluated once per input row.
#[derive(Clone, Default)]
pub(crate) struct ExecutableStaticPrecheckProgram {
    pub(super) and_columns: Vec<ResolvedBoolColumn>,
    pub(super) or_columns: Vec<ResolvedBoolColumn>,
}

#[derive(Clone)]
pub(crate) struct ExecutableUserSymbolProgram {
    pub(super) id: SymbolId,
    pub(super) evaluator: ExecutableSymbolEvaluator,
    pub(super) define_cache: DefineCachePolicy,
    pub(super) aggregate_state: ExecutableAggregateStateProgram,
    pub(super) static_prechecks: ExecutableStaticPrecheckProgram,
}

impl ExecutableSymbolProgram {
    #[inline]
    pub(crate) fn user(&self) -> Option<&ExecutableUserSymbolProgram> {
        match self {
            Self::Empty => None,
            Self::User(program) => Some(program),
        }
    }

    #[inline]
    #[cfg(test)]
    pub(crate) fn mode(&self) -> SymbolEvalMode {
        self.user()
            .map(ExecutableUserSymbolProgram::mode)
            .unwrap_or(SymbolEvalMode::Static)
    }
}

impl ExecutableUserSymbolProgram {
    #[inline]
    pub(crate) fn id(&self) -> SymbolId {
        self.id
    }

    #[inline]
    #[cfg(test)]
    pub(crate) fn mode(&self) -> SymbolEvalMode {
        self.evaluator.mode()
    }

    #[inline]
    pub(crate) fn evaluator(&self) -> &ExecutableSymbolEvaluator {
        &self.evaluator
    }

    #[inline]
    pub(crate) const fn define_cache(&self) -> DefineCachePolicy {
        self.define_cache
    }

    #[inline]
    pub(crate) fn accumulation_program(&self) -> &ExecutableAccumulationProgram {
        &self.aggregate_state.accumulation
    }

    #[inline]
    pub(crate) fn navigation_program(&self) -> &ExecutableNavigationProgram {
        &self.aggregate_state.navigation
    }

    #[inline]
    pub(crate) fn incremental_define(&self) -> Option<&Arc<dyn PhysicalExpr>> {
        self.evaluator.source_expr()
    }

    #[inline]
    pub(crate) fn static_predicate_and_columns(&self) -> &[ResolvedBoolColumn] {
        &self.static_prechecks.and_columns
    }

    #[inline]
    pub(crate) fn static_predicate_or_columns(&self) -> &[ResolvedBoolColumn] {
        &self.static_prechecks.or_columns
    }
}

impl ExecutableAggregateStateProgram {
    pub(super) fn new(
        accumulation: ExecutableAccumulationProgram,
        navigation: ExecutableNavigationProgram,
    ) -> Self {
        Self {
            accumulation,
            navigation,
        }
    }
}