datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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.

//! Prepares the pattern and DataFusion properties stored by the physical node.
//!
//! Physical planning normalizes and compiles the pattern, builds the executable
//! program, and then derives ordering, partitioning, and schema properties from
//! that program and the child plan. Structural normalization is always applied.
//! Optional exact-statistics facts can additionally remove static symbols that
//! cannot match anywhere in the complete input.

use std::collections::HashMap;
use std::sync::Arc;

use crate::execution::matching::{
    ExecutableMatchProgram, OutputPartitionBindings, PartitionPassthrough,
};
use crate::nfa::{CompiledAutomaton, PatternCompileLimits, SymbolStatus};
use datafusion::arrow::compute::SortOptions;
use datafusion::catalog::Session;
use datafusion::logical_expr::physical_planning_context::PhysicalPlanningContext;
use datafusion::physical_planner::PhysicalPlanner;
use datafusion_common::{DataFusionError, Result, internal_err};
use datafusion_physical_expr::PhysicalExpr;
use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
use datafusion_physical_plan::ExecutionPlan;

use crate::execution::physical::properties::{
    PhysicalPropertiesInput, PropertiesBuilder, ordered_partition_by_indices,
};

use crate::core::{NormalizedPattern, Pattern, SymbolId};
use crate::nfa::display_pattern_or_clone;
use crate::planning::logical::{LogicalMatchProgram, MatchRecognize};

/// Display, normalized, and compiled forms of one prepared pattern.
#[derive(Clone)]
pub(crate) struct PreparedPattern {
    pub(crate) display_pattern: Pattern,
    pub(crate) normalized_pattern: NormalizedPattern,
    pub(crate) compiled_automaton: Arc<CompiledAutomaton>,
}

/// Child plan and derived DataFusion properties stored by the physical node.
#[derive(Debug, Clone)]
pub(crate) struct MatchPlanLayout {
    pub(super) input: Arc<dyn ExecutionPlan>,
    pub(super) grouped_input: bool,
    pub(super) bypass_never_ordering: bool,
    pub(super) partition_by: Vec<Arc<dyn PhysicalExpr>>,
    pub(super) order_by: Option<LexOrdering>,
    pub(super) cache: Arc<datafusion_physical_plan::execution_plan::PlanProperties>,
    pub(super) maintains_input_order: bool,
    pub(super) ordered_partition_by_indices: Vec<usize>,
    pub(super) output_bindings: OutputPartitionBindings,
}

/// Pattern semantics needed to normalize and compile an automaton.
pub(crate) struct PatternPreparationInput<'a> {
    pub(crate) pattern: &'a Pattern,
    pub(crate) symbols: &'a [String],
    pub(crate) disjoint_symbols: &'a [(String, String)],
    pub(crate) implies_symbols: &'a [(String, String)],
    pub(crate) symbol_status: &'a HashMap<String, SymbolStatus>,
    pub(crate) pattern_compile_limits: PatternCompileLimits,
}

/// Bind dense logical symbols after the runtime's reserved empty-symbol slot.
pub(crate) fn runtime_symbol_ids(logical_len: usize) -> Result<Vec<SymbolId>> {
    let Some(runtime_len) = logical_len.checked_add(1) else {
        return internal_err!("MATCH_RECOGNIZE symbol count overflow");
    };
    (1..runtime_len)
        .map(|index| SymbolId::try_new(index, runtime_len))
        .collect::<Option<_>>()
        .ok_or_else(|| DataFusionError::Internal("invalid runtime symbol table".into()))
}

/// Preserve the logical symbol identities when compilation rewrites the pattern.
pub(crate) fn validate_compiled_symbol_alignment(
    program: &LogicalMatchProgram,
    runtime_symbols: &[SymbolId],
    automaton: &CompiledAutomaton,
) -> Result<()> {
    let aligned =
        automaton.num_symbols() == runtime_symbols.len() + 1
            && automaton.id_to_symbol().first() == Some(&None)
            && program.symbols().iter().zip(runtime_symbols).all(
                |(symbol, runtime_id)| {
                    automaton.id_to_symbol()[runtime_id.index()].as_deref()
                        == Some(symbol.name())
                },
            );
    if !aligned {
        return internal_err!(
            "MATCH_RECOGNIZE compiled symbol table disagrees with the logical program"
        );
    }
    Ok(())
}

fn normalize_pattern_for_compilation(
    input: &PatternPreparationInput<'_>,
) -> NormalizedPattern {
    use crate::nfa::PatternOptimizer;

    let pattern = input.pattern;
    let static_optimizer = PatternOptimizer::new(input.symbol_status)
        .with_disjoint_symbols(input.disjoint_symbols)
        .with_implies_symbols(input.implies_symbols)
        .with_allow_pruning(!input.symbol_status.is_empty());

    let normalized = static_optimizer.optimize(pattern);

    match &normalized {
        NormalizedPattern::Ast(optimized) if optimized != pattern => {
            log::debug!(
                "Construction-time pattern normalization applied: {pattern:?} -> {optimized:?}"
            );
        }
        NormalizedPattern::Never => {
            log::debug!(
                "Construction-time pattern normalization detected Never for pattern: {pattern:?}"
            );
        }
        NormalizedPattern::Epsilon => {
            log::debug!(
                "Construction-time pattern normalization detected Epsilon for pattern: {pattern:?}"
            );
        }
        NormalizedPattern::Ast(_) => {}
    }

    normalized
}

pub(crate) fn prepare_pattern(
    pattern_input: PatternPreparationInput<'_>,
) -> Result<PreparedPattern> {
    let normalized_pattern = normalize_pattern_for_compilation(&pattern_input);
    let display_pattern =
        display_pattern_or_clone(&normalized_pattern, pattern_input.pattern);
    let compiled_automaton = Arc::new(CompiledAutomaton::compile_with_limits(
        &normalized_pattern,
        pattern_input.symbols,
        pattern_input.pattern_compile_limits,
    )?);

    Ok(PreparedPattern {
        display_pattern,
        normalized_pattern,
        compiled_automaton,
    })
}

impl MatchPlanLayout {
    pub(crate) fn bind_partition_by(
        planner: &dyn PhysicalPlanner,
        mr: &MatchRecognize,
        session: &dyn Session,
        ctx: &PhysicalPlanningContext,
    ) -> Result<Vec<Arc<dyn PhysicalExpr>>> {
        mr.program()
            .partition_by()
            .iter()
            .map(|expr| {
                planner.create_physical_expr(expr, mr.input().schema(), session, ctx)
            })
            .collect()
    }

    pub(crate) fn bind_order_by(
        planner: &dyn PhysicalPlanner,
        mr: &MatchRecognize,
        session: &dyn Session,
        ctx: &PhysicalPlanningContext,
    ) -> Result<Vec<PhysicalSortExpr>> {
        mr.program()
            .order_by()
            .iter()
            .map(|sort| {
                Ok(PhysicalSortExpr {
                    expr: planner.create_physical_expr(
                        &sort.expr,
                        mr.input().schema(),
                        session,
                        ctx,
                    )?,
                    options: SortOptions {
                        descending: !sort.asc,
                        nulls_first: sort.nulls_first,
                    },
                })
            })
            .collect()
    }

    /// Derive physical properties from a checked program and its child plan.
    pub(crate) fn try_new(
        input: Arc<dyn ExecutionPlan>,
        partition_by: Vec<Arc<dyn PhysicalExpr>>,
        order_by: Option<LexOrdering>,
        program: &ExecutableMatchProgram,
    ) -> Result<Self> {
        Self::try_new_with_bypass(input, partition_by, order_by, program, true)
    }

    pub(super) fn try_new_with_bypass(
        input: Arc<dyn ExecutionPlan>,
        partition_by: Vec<Arc<dyn PhysicalExpr>>,
        order_by: Option<LexOrdering>,
        program: &ExecutableMatchProgram,
        bypass_never_ordering: bool,
    ) -> Result<Self> {
        // Rebinding ordered classification can add neighbor reads to a Never
        // program. Preserve prior restrictions and recheck the current program
        // before deriving any cached ordering or distribution properties.
        let bypass_never_ordering = bypass_never_ordering
            && program_bypasses_ordering_for_never(
                program,
                &partition_by,
                order_by.as_ref(),
            );
        let grouped = input
            .downcast_ref::<datafusion_hash_grouped_order::HashGroupedOrderExec>()
            .filter(|group| {
                super::compatible_group(group, &partition_by, order_by.as_ref())
            });
        let grouped_input = grouped.is_some();
        let unordered_groups = grouped.is_some_and(|group| {
            group.config().emit_order
                == datafusion_hash_grouped_order::GroupEmitOrder::Unordered
        });
        let ordered_partition_by_indices =
            ordered_partition_by_indices(&partition_by, &input)?;
        // Virtual empty rows retain declared PARTITION BY columns (and, for
        // ONE ROW / retained-expression layouts, their input leaves) whenever
        // they pass through output, even before `EnforceSorting` establishes
        // `ordered_partition_by_indices`. Binding declared keys keeps
        // `compute_output_partitioning()` accurate during `EnforceDistribution`
        // so downstream `KeyPartitioned` operators do not insert redundant
        // `RepartitionExec` + `SortExec` pairs above the matcher.
        let binding_keys = match grouped {
            Some(group) => group.output_group_keys(),
            None => partition_by.as_slice(),
        };
        let output_bindings = OutputPartitionBindings::try_new(
            input.schema().as_ref(),
            program.output_plan(),
            binding_keys.iter().cloned(),
        )?;
        let virtual_partition_passthrough =
            virtual_partition_passthrough(program, &output_bindings);
        let skips_past_last_row = matches!(
            program.after_match_skip(),
            crate::execution::matching::ResolvedAfterMatchSkip::PastLastRow
        );
        let has_zero_navigation_offsets = !program
            .output_plan()
            .stream()
            .emits_navigation_buffer_rows();
        // Keys describe this physical stream, before navigation rows are removed.
        let preserves_input_uniqueness = skips_past_last_row
            && virtual_partition_passthrough.is_none()
            && has_zero_navigation_offsets;
        let properties = PropertiesBuilder::try_new(PhysicalPropertiesInput {
            input: &input,
            schema: program.output_schema(),
            partition_by: &partition_by,
            ordered_partition_by_indices: &ordered_partition_by_indices,
            order_by: &order_by,
            output_spec: program.output_spec(),
            zero_output_navigation: has_zero_navigation_offsets,
            // Navigation context can rewind input positions between matches.
            maintains_input_order: !unordered_groups
                && !bypass_never_ordering
                && skips_past_last_row
                && has_zero_navigation_offsets,
            preserves_input_uniqueness,
            interleaves_logical_partitions: program
                .stream_requirements()
                .interleaves_logical_partitions,
            ordered_unmatched: program.emits_ordered_unmatched(),
            rows_per_match: program.rows_per_match(),
            retention: super::PartitionRetention::for_program(program),
            bounded_match: program.compiled_automaton().max_match_rows().is_some(),
            bypass_never_ordering,
            virtual_partition_passthrough,
        })?;
        let maintains_input_order = properties.maintains_input_order();
        let cache = Arc::new(properties.compute()?);

        Ok(Self {
            input,
            grouped_input,
            bypass_never_ordering,
            partition_by,
            order_by,
            cache,
            maintains_input_order,
            ordered_partition_by_indices,
            output_bindings,
        })
    }

    pub(super) fn rebuild_with_input(
        &self,
        input: Arc<dyn ExecutionPlan>,
        program: &ExecutableMatchProgram,
    ) -> Result<Self> {
        Self::try_new_with_bypass(
            input,
            self.partition_by.clone(),
            self.order_by.clone(),
            program,
            self.bypass_never_ordering,
        )
    }

    pub(super) fn rebuild_with_bypass(
        &self,
        bypass_never_ordering: bool,
        program: &ExecutableMatchProgram,
    ) -> Result<Self> {
        Self::try_new_with_bypass(
            Arc::clone(&self.input),
            self.partition_by.clone(),
            self.order_by.clone(),
            program,
            bypass_never_ordering,
        )
    }
}

/// Whether `program` + keys allow bypassing input ordering and partitioning
/// because the pattern is statically impossible (`NormalizedPattern::Never`),
/// emits zero unmatched rows, has no matcher-side fallible predicates, and uses
/// only plain infallible column keys.
pub(super) fn program_bypasses_ordering_for_never(
    program: &ExecutableMatchProgram,
    partition_by: &[Arc<dyn PhysicalExpr>],
    order_by: Option<&LexOrdering>,
) -> bool {
    use crate::core::{EmptyMatchesMode, RowsPerMatch};
    use datafusion_physical_expr::expressions::Column;

    !matches!(
        program.rows_per_match(),
        RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
    ) && program.is_infallible_never()
        && partition_by
            .iter()
            .all(|expr| expr.downcast_ref::<Column>().is_some())
        && order_by.is_none_or(|ordering| {
            ordering
                .iter()
                .all(|sort| sort.expr.downcast_ref::<Column>().is_some())
        })
}

/// Identify visible virtual rows and the output slots that retain partition values.
pub(super) fn virtual_partition_passthrough(
    program: &ExecutableMatchProgram,
    output_bindings: &OutputPartitionBindings,
) -> Option<PartitionPassthrough> {
    (program.compiled_automaton().min_match_rows() == 0
        && program.output_plan().stream().emits_terminal_empty_match())
    .then(|| output_bindings.visible())
}