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 `MatchRecognize` logical node from prepared input and processed
//! `DEFINE` conditions.
//!
//! Assembly binds the canonical source and validated match program together.
//! It leaves the final table output to a separate phase, passing along the
//! partition, ordering, measure, and exclusion information that phase needs.

use std::collections::BTreeSet;
use std::str::FromStr;
use std::sync::Arc;

use crate::core::{
    AfterMatchSkip, MatchMetadataColumn, MatchRecognizeOutputSpec, NavigationOffsets,
    Pattern, RowsPerMatch, classifier_bits_col_name,
};
use crate::planning::NamedExpr;
use crate::planning::logical::{
    BoundMatchSource, LogicalMatchOutput, LogicalMatchProgramInput,
    LogicalSelectedMatchSummary, LogicalSymbolInput, MatchRecognize,
};
use datafusion::common::Result;
use datafusion::logical_expr::{Expr, SortExpr};

use super::{AssembledNode, ProcessedDefines, SymbolPlan, SymbolPlanPredicate};

/// Pattern, ordering, navigation, and source information for the matcher node.
pub(crate) struct MatcherNodeSpec {
    pub partition_by: Vec<Expr>,
    pub order_by: Vec<SortExpr>,
    pub after_match_skip: AfterMatchSkip,
    pub pattern: Pattern,
    pub output: MatcherOutputMode,
    pub navigation_offsets: NavigationOffsets,
    pub bound_source: Arc<BoundMatchSource>,
}

/// Output mode consumed directly by logical node assembly.
pub(crate) enum MatcherOutputMode {
    Rows(RowsPerMatch),
    SelectedSummaries(Vec<LogicalSelectedMatchSummary>),
}

/// Information needed after the matcher node has been built.
pub(crate) struct NodeOutputSpec {
    pub measures_exprs: Vec<NamedExpr>,
    pub has_exclusions: bool,
}

struct AssembledCore {
    matcher: MatchRecognize,
    logical_partition_by: Vec<Expr>,
}

fn assemble_match_recognize_core(
    processed: ProcessedDefines,
    matcher: MatcherNodeSpec,
) -> Result<AssembledCore> {
    let MatcherNodeSpec {
        partition_by,
        order_by,
        after_match_skip,
        pattern,
        output,
        navigation_offsets,
        bound_source,
    } = matcher;
    let ProcessedDefines {
        input,
        symbol_plans,
        managed_aggregates,
        static_extractions,
        prepared_exprs,
        symbol_relationships,
    } = processed;

    let symbols = symbol_plans
        .into_iter()
        .map(logical_symbol_input)
        .collect::<Vec<_>>();
    let classifier_bitsets = symbols
        .iter()
        .map(|symbol| symbol.name.clone())
        .collect::<Vec<_>>();
    let classifier_columns = classifier_bitsets
        .iter()
        .map(|symbol| classifier_bits_col_name(symbol))
        .collect::<BTreeSet<_>>();

    let logical_partition_by = partition_by.clone();
    let matcher_partition_by = partition_by;

    let passthrough_indices: Vec<usize> = input
        .schema()
        .fields()
        .iter()
        .enumerate()
        .filter(|(_, field)| {
            let name = field.name();
            if MatchMetadataColumn::from_str(name).is_ok() {
                return false;
            }
            if classifier_columns.contains(name) {
                return false;
            }
            true
        })
        .map(|(i, _)| i)
        .collect();

    let output_spec = MatchRecognizeOutputSpec::with_validated_navigation_offsets(
        passthrough_indices,
        MatchMetadataColumn::public_output().to_vec(),
        classifier_bitsets.clone(),
        navigation_offsets,
    );
    let output = match output {
        MatcherOutputMode::SelectedSummaries(summaries) => {
            let input_spec = output_spec.clone();
            LogicalMatchOutput::selected_summaries(output_spec, input_spec, summaries)
        }
        MatcherOutputMode::Rows(rows_per_match) => {
            LogicalMatchOutput::rows(rows_per_match, output_spec)
        }
    };

    let program = LogicalMatchProgramInput {
        partition_by: matcher_partition_by,
        order_by,
        after_skip: after_match_skip,
        pattern,
        symbols,
        match_aware: crate::planning::define::preparation::into_program_input(
            managed_aggregates,
            static_extractions,
        ),
        output,
        symbol_relationships,
    };
    let matcher = MatchRecognize::try_new_with_source(input, program, bound_source)?
        .with_prepared_exprs(prepared_exprs);

    Ok(AssembledCore {
        matcher,
        logical_partition_by,
    })
}

fn logical_symbol_input(plan: SymbolPlan) -> LogicalSymbolInput {
    match plan.predicate {
        SymbolPlanPredicate::Demanded(expr) => {
            LogicalSymbolInput::demanded(plan.name, expr)
        }
        SymbolPlanPredicate::Static(expr) => LogicalSymbolInput::static_(plan.name, expr),
        SymbolPlanPredicate::MatchAware(predicate) => predicate.into_logical(plan.name),
    }
}

/// Build and validate the matcher node, retaining the facts needed for final
/// output.
pub fn assemble_node_from_logical_parts(
    processed: ProcessedDefines,
    matcher: MatcherNodeSpec,
    output: NodeOutputSpec,
) -> Result<AssembledNode> {
    let core = assemble_match_recognize_core(processed, matcher)?;

    Ok(AssembledNode {
        matcher: core.matcher,
        measures_exprs: output.measures_exprs,
        logical_partition_by: core.logical_partition_by,
        has_exclusions: output.has_exclusions,
    })
}