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.

//! Immutable physical-planning decisions for one checked match program.

use crate::core::vm::{RegisterLayout, RegisterWriter};
use crate::core::{AggregateId, SymbolEvalMode};
use crate::planning::deferred_program::is_dense;
use crate::planning::logical::{LogicalManagedAggregate, LogicalSymbolId};
use crate::planning::predicate::{DirectPredicatePlan, VmCompileError};
use crate::planning::{
    DeferredProgramSpec, LogicalHybridGuardExpr, ManagedAggregateBackend,
    VmAssemblyDowngrade,
};
use datafusion::common::{Result, internal_err};
use datafusion::logical_expr::Expr;

/// Options that affect immutable match-program routing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct MatchCompilerOptions {
    disable_register_aggregate_backend: bool,
}

impl MatchCompilerOptions {
    /// Build the route-affecting options for one compilation.
    pub const fn new(disable_register_aggregate_backend: bool) -> Self {
        Self {
            disable_register_aggregate_backend,
        }
    }

    pub(crate) const fn disable_register_aggregate_backend(self) -> bool {
        self.disable_register_aggregate_backend
    }
}

/// The evaluator selected for one symbol.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RoutedEvaluator {
    /// The symbol predicate is already materialized on each input row.
    Static,
    /// The matcher evaluates this predicate as the candidate grows.
    Local(Expr),
    /// Evaluate synchronously against candidate history, optionally checking
    /// a local guard first.
    History {
        /// Local predicate and its three-valued guard, when available.
        local_guard: Option<RoutedHistoryGuard>,
    },
}

/// An optional local check on a history route.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RoutedHistoryGuard {
    pub(crate) source: Expr,
    pub(crate) expression: LogicalHybridGuardExpr,
}

impl RoutedEvaluator {
    /// Return the diagnostic mode represented by this route.
    pub const fn mode(&self) -> SymbolEvalMode {
        match self {
            Self::Static => SymbolEvalMode::Static,
            Self::Local(_) => SymbolEvalMode::Incremental,
            Self::History { local_guard: None } => SymbolEvalMode::Deferred,
            Self::History {
                local_guard: Some(_),
            } => SymbolEvalMode::Hybrid,
        }
    }

    /// Return the locally evaluated predicate, when this route has one.
    pub fn local_predicate(&self) -> Option<&Expr> {
        match self {
            Self::Local(expr) => Some(expr),
            Self::History {
                local_guard: Some(local),
            } => Some(&local.source),
            Self::Static | Self::History { local_guard: None } => None,
        }
    }

    /// Return the local guard on a history route, when present.
    pub fn hybrid_guard(&self) -> Option<&LogicalHybridGuardExpr> {
        match self {
            Self::History {
                local_guard: Some(local),
            } => Some(&local.expression),
            _ => None,
        }
    }
}

/// Canonical VM compilation result retained for one local predicate.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RoutedPredicate {
    /// This evaluator has no local predicate to compile.
    NotApplicable,
    /// The local predicate compiled to a typed, source-resolved expression.
    Direct(DirectPredicatePlan),
    /// The local predicate could not compile to a typed predicate program.
    Rejected(VmCompileError),
}

impl RoutedPredicate {
    /// Return the compile outcome's stable diagnostic tag.
    ///
    /// Physical EXPLAIN checks the final evaluator and navigation-state
    /// selection before displaying this candidate annotation. Compile binding
    /// rejections can describe unavailable VM sources; hard physical binding
    /// and predicate-validation errors still fail planning.
    pub fn route_tag(&self) -> Option<&'static str> {
        Some(match self {
            Self::NotApplicable => return None,
            Self::Direct(_) => "vm:direct-expr",
            Self::Rejected(error) => match error {
                VmCompileError::TypeResolutionFailure => "vm:fallback:type-resolution",
                VmCompileError::UnsupportedFunctionSignature => "vm:fallback:function",
                VmCompileError::UnsupportedCast => "vm:fallback:cast",
                VmCompileError::UnsupportedSourceDomain => "vm:fallback:source-domain",
                VmCompileError::UnsupportedNumericTypeCombination => {
                    "vm:fallback:numeric-types"
                }
                VmCompileError::ExpressionTooLarge => "vm:fallback:expression-budget",
                VmCompileError::ProgramTooLarge => "vm:fallback:program-budget",
                VmCompileError::StackDepthExceeded => "vm:fallback:stack-budget",
                VmCompileError::EmissionFailure => "vm:fallback:emission",
                VmCompileError::BindingFailure => "vm:fallback:binding",
            },
        })
    }
}

/// How a DataFusion accumulator receives one accepted matcher row.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AccumulatorInputMode {
    /// Pass the aggregate's ordinary argument batch to DataFusion.
    Batch,
    /// Pass stored history to a low-level `PREV` accumulator.
    /// SQL physical offsets use prepared LAG values with offset zero.
    PreviousValue,
}

/// Immutable routing facts for one dense logical symbol.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RoutedSymbol {
    id: LogicalSymbolId,
    evaluator: RoutedEvaluator,
    register_writers: Vec<RegisterWriter>,
    predicate_outcome: RoutedPredicate,
}

impl RoutedSymbol {
    pub(crate) fn new(
        id: LogicalSymbolId,
        evaluator: RoutedEvaluator,
        register_writers: Vec<RegisterWriter>,
        predicate_outcome: RoutedPredicate,
    ) -> Self {
        Self {
            id,
            evaluator,
            register_writers,
            predicate_outcome,
        }
    }

    /// Return this symbol's zero-based logical identity.
    pub const fn id(&self) -> LogicalSymbolId {
        self.id
    }

    /// Return the symbol's single selected evaluator route.
    pub fn evaluator(&self) -> &RoutedEvaluator {
        &self.evaluator
    }

    /// Return the evaluation mode implied by the selected route.
    pub const fn mode(&self) -> SymbolEvalMode {
        self.evaluator.mode()
    }

    /// Return the register aggregates advanced when this symbol is accepted.
    pub fn register_writers(&self) -> &[RegisterWriter] {
        &self.register_writers
    }

    /// Return the canonical typed-predicate outcome for this symbol.
    pub fn predicate_outcome(&self) -> &RoutedPredicate {
        &self.predicate_outcome
    }

    /// Return the compile annotation for an Incremental predicate outcome.
    ///
    /// Physical EXPLAIN derives its annotation from the executable symbol table,
    /// which also checks the final evaluator and navigation-state selection.
    #[cfg(test)]
    pub fn route_tag(&self) -> Option<&'static str> {
        if !matches!(self.evaluator, RoutedEvaluator::Local(_)) {
            return None;
        }
        self.predicate_outcome.route_tag()
    }
}

/// One logical aggregate paired with its final runtime backend.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RoutedAggregate {
    logical: LogicalManagedAggregate,
    backend: ManagedAggregateBackend,
    accumulator_input_mode: AccumulatorInputMode,
    counts_every_row: bool,
}

impl RoutedAggregate {
    pub(crate) fn new(
        logical: LogicalManagedAggregate,
        backend: ManagedAggregateBackend,
        accumulator_input_mode: AccumulatorInputMode,
        counts_every_row: bool,
    ) -> Self {
        Self {
            logical,
            backend,
            accumulator_input_mode,
            counts_every_row,
        }
    }

    /// Return the validated logical aggregate facts.
    pub fn logical(&self) -> &LogicalManagedAggregate {
        &self.logical
    }

    /// Return this aggregate's dense typed identity.
    pub const fn id(&self) -> AggregateId {
        self.logical.id()
    }

    /// Return the symbol that scopes updates, or `None` for every symbol.
    pub const fn owner(&self) -> Option<LogicalSymbolId> {
        self.logical.symbol()
    }

    /// Return the selected runtime state backend.
    pub const fn backend(&self) -> ManagedAggregateBackend {
        self.backend
    }

    /// Return how the DataFusion accumulator receives one accepted row.
    pub const fn accumulator_input_mode(&self) -> AccumulatorInputMode {
        self.accumulator_input_mode
    }

    /// Whether one accepted row always increments this aggregate by one.
    pub const fn counts_every_row(&self) -> bool {
        self.counts_every_row
    }
}

/// One coherent, immutable routing result for a checked logical match program.
#[derive(Clone, Debug)]
pub struct RoutedMatchProgram {
    symbols: Vec<RoutedSymbol>,
    aggregates: Vec<RoutedAggregate>,
    register_layout: RegisterLayout,
    #[cfg_attr(not(test), allow(dead_code))]
    downgrade_reason: Option<VmAssemblyDowngrade>,
    deferred: Option<DeferredProgramSpec>,
}

impl RoutedMatchProgram {
    pub(crate) fn try_new(
        symbols: Vec<RoutedSymbol>,
        aggregates: Vec<RoutedAggregate>,
        register_layout: RegisterLayout,
        downgrade_reason: Option<VmAssemblyDowngrade>,
        deferred: Option<DeferredProgramSpec>,
    ) -> Result<Self> {
        if !is_dense(&symbols, |s| s.id().index())
            || !is_dense(&aggregates, |a| a.id().index())
        {
            return internal_err!("MATCH_RECOGNIZE routed table is not dense");
        }
        let requires_deferred = symbols.iter().any(|s| s.mode().requires_deferred());
        let aligned = deferred.as_ref().is_none_or(|spec| {
            spec.predicates().len() == symbols.len()
                && symbols
                    .iter()
                    .zip(spec.predicates())
                    .all(|(symbol, predicate)| {
                        predicate.as_ref().map(|p| p.symbol_id())
                            == symbol.mode().requires_deferred().then_some(symbol.id())
                    })
        });
        if deferred.is_some() != requires_deferred || !aligned {
            return internal_err!("Deferred program disagrees with routes");
        }
        Ok(Self {
            symbols,
            aggregates,
            register_layout,
            downgrade_reason,
            deferred,
        })
    }

    /// Return the dense routed symbol table.
    pub fn symbols(&self) -> &[RoutedSymbol] {
        &self.symbols
    }

    /// Return the dense routed aggregate table.
    pub fn aggregates(&self) -> &[RoutedAggregate] {
        &self.aggregates
    }

    /// Return the final register layout after any atomic downgrade.
    pub fn register_layout(&self) -> &RegisterLayout {
        &self.register_layout
    }

    /// Return the whole-program reason register routes were downgraded.
    #[cfg(test)]
    pub(crate) fn downgrade_reason(&self) -> Option<&VmAssemblyDowngrade> {
        self.downgrade_reason.as_ref()
    }

    /// Return the validated Deferred program when any symbol requires it.
    pub const fn deferred(&self) -> Option<&DeferredProgramSpec> {
        self.deferred.as_ref()
    }
}

#[cfg(test)]
mod tests {
    use super::{RoutedEvaluator, RoutedPredicate, RoutedSymbol};
    use crate::planning::logical::LogicalSymbolId;
    use crate::planning::predicate::VmCompileError;
    use datafusion::logical_expr::lit;

    #[test]
    fn compile_rejection_tags_are_stable() {
        use VmCompileError::*;
        for (error, tag) in [
            (TypeResolutionFailure, "vm:fallback:type-resolution"),
            (UnsupportedFunctionSignature, "vm:fallback:function"),
            (UnsupportedCast, "vm:fallback:cast"),
            (UnsupportedSourceDomain, "vm:fallback:source-domain"),
            (
                UnsupportedNumericTypeCombination,
                "vm:fallback:numeric-types",
            ),
            (ExpressionTooLarge, "vm:fallback:expression-budget"),
            (ProgramTooLarge, "vm:fallback:program-budget"),
            (StackDepthExceeded, "vm:fallback:stack-budget"),
            (EmissionFailure, "vm:fallback:emission"),
            (BindingFailure, "vm:fallback:binding"),
        ] {
            let symbol = RoutedSymbol::new(
                LogicalSymbolId::for_test(0),
                RoutedEvaluator::Local(lit(true)),
                Vec::new(),
                RoutedPredicate::Rejected(error),
            );
            assert_eq!(symbol.route_tag(), Some(tag));
        }
        assert_eq!(RoutedPredicate::NotApplicable.route_tag(), None);
    }
}