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.

//! Turns the matcher's internal row stream into the rows requested by SQL.
//!
//! Physical offset navigation windows (`PREV` / `NEXT`) run while their extra
//! buffer rows are still present. After removing those rows, the planner adds
//! other windows (including `FIRST` / `LAST` and aggregates), removes excluded
//! rows, groups each match when it was not finalized natively, and selects the
//! final columns.

use std::ops::Not;
use std::sync::Arc;

use crate::core::{
    EmptyMatchesMode, MAX_VALID_MATCH_SEQUENCE_NUMBER, MIN_VALID_MATCH_SEQUENCE_NUMBER,
    MatchMetadataColumn, NavigationOffsets, RowsPerMatch,
};
use datafusion::common::{DFSchema, Result};
use datafusion::logical_expr::{
    Expr, Extension, LogicalPlan, LogicalPlanBuilder, SortExpr, col, lit,
};

use crate::planning::logical::utils::rows_projection_expr;
use crate::planning::logical::valid_match_row_expr;
use crate::planning::measures;

use super::AssembledNode;

/// Add the plan nodes that produce the requested `ROWS PER MATCH` output from
/// navigation offsets checked during source lowering.
pub(crate) fn finalize_output_with_navigation_offsets(
    assembled: AssembledNode,
    rows_per_match: &RowsPerMatch,
    table_schema: &Arc<DFSchema>,
    navigation_offsets: NavigationOffsets,
    source_partition_by: &[Expr],
    source_order_by: &[SortExpr],
) -> Result<LogicalPlan> {
    let AssembledNode {
        matcher,
        mut measures_exprs,
        mut logical_partition_by,
        has_exclusions,
    } = assembled;
    if rows_per_match == &RowsPerMatch::AllRows(EmptyMatchesMode::Omit)
        && navigation_offsets.is_zero()
        && !has_exclusions
    {
        measures::omit_classified_row_filter(&mut measures_exprs)?;
    }
    let matcher_finalizes_summaries =
        matcher.program().output().finalizes_selected_summaries();
    let plan = LogicalPlan::Extension(Extension {
        node: Arc::new(matcher),
    });
    // Physical offset navigation (`PREV`/`NEXT`) runs first because it needs
    // the extra buffer rows.
    let (plan, measures_exprs) =
        measures::apply_windows_and_rebase_measures(plan, measures_exprs, true)?;

    // Edge navigation (`FIRST`/`LAST`) and aggregate windows must not include
    // buffer rows in their calculations.
    let plan = if let Some(filter_expr) =
        buffer_row_filter_expr(navigation_offsets, rows_per_match)
    {
        LogicalPlanBuilder::from(plan)
            .filter(filter_expr)?
            .build()?
    } else {
        plan
    };

    // Calculate the remaining Window expressions on real output rows only.
    let (plan, measures_exprs) =
        measures::apply_windows_and_rebase_measures(plan, measures_exprs, false)?;

    // Return the matcher's native one-row summary, add the general aggregate
    // finalizer, or keep row-level output and remove excluded rows.
    let (plan, measures_exprs) = match rows_per_match {
        RowsPerMatch::OneRow => {
            if matcher_finalizes_summaries {
                (plan, measures_exprs)
            } else {
                // ONE ROW measures include excluded rows; no exclusion filter is needed.
                let (plan, measures, partition_outputs) =
                    measures::apply_aggregate_and_rebase_measures(
                        plan,
                        measures_exprs,
                        &logical_partition_by,
                    )?;
                logical_partition_by = partition_outputs;
                (plan, measures)
            }
        }
        _ => {
            // Row-level modes need an explicit exclusion filter.
            let plan = if has_exclusions {
                let excluded_col = col(MatchMetadataColumn::Excluded.as_ref());
                let pred = excluded_col.not();
                LogicalPlanBuilder::from(plan).filter(pred)?.build()?
            } else {
                plan
            };
            (plan, measures_exprs)
        }
    };

    // Group with prepared key columns, then restore the original public names
    // without leaking the input table qualifier onto the anonymous output table.
    // ALL ROWS derives visible input-column order from the original expressions.
    let partition_outputs = if matches!(rows_per_match, RowsPerMatch::OneRow) {
        logical_partition_by
            .into_iter()
            .zip(source_partition_by)
            .map(|(output, source)| {
                let (relation, name) = source.qualified_name();
                let target_relation = if relation.is_some()
                    && source_partition_by
                        .iter()
                        .filter(|other| other.qualified_name().1 == name)
                        .count()
                        == 1
                {
                    None
                } else {
                    relation
                };
                if output.qualified_name() == (target_relation.clone(), name.clone()) {
                    output
                } else {
                    output.alias_qualified(target_relation, name)
                }
            })
            .collect::<Vec<_>>()
    } else {
        source_partition_by.to_vec()
    };

    // Select and order the user-visible columns.
    let projection_exprs = rows_projection_expr(
        rows_per_match,
        &plan,
        table_schema,
        &partition_outputs,
        source_order_by,
        &measures_exprs,
    );
    LogicalPlanBuilder::from(plan)
        .project(projection_exprs)?
        .build()
}

/// Build the predicate that removes extra rows supplied only so `PREV` and
/// `NEXT` can navigate, returning `None` when no filter is needed.
///
/// `PREV` buffer rows have negative sequence numbers, `NEXT` buffer rows have
/// very large sequence numbers, and real matched rows use one-based sequence
/// numbers no greater than `2^62 - 1`.
/// With `WITH UNMATCHED ROWS`, an unmatched row has a `NULL` sequence number
/// and must remain in the output.
///
/// Physical navigation Window nodes (`PREV`/`NEXT`) run before this filter so
/// they can see the buffer. Logical edge (`FIRST`/`LAST`) and aggregate
/// windows run after it so buffer rows cannot change or fail their evaluation.
///
/// `ONE ROW PER MATCH` is the exception. Its `PREV` and `NEXT` aggregates need
/// the buffer and distinguish real rows with their `is_matched` argument.
/// Native `FIRST_VALUE`/`LAST_VALUE` and ordinary aggregates exclude buffer
/// rows through their own filters. Retaining an empty-match marker row still
/// creates the output group even though no value passes those filters.
/// Therefore this function returns `None` in that mode.
///
/// Returns `None` when both navigation offsets are zero. The offsets were
/// checked during source lowering before reaching this phase.
fn buffer_row_filter_expr(
    navigation_offsets: NavigationOffsets,
    rows_per_match: &RowsPerMatch,
) -> Option<Expr> {
    if matches!(rows_per_match, RowsPerMatch::OneRow) {
        return None;
    }

    let seq_col = || col(MatchMetadataColumn::MatchSequenceNumber.as_ref());
    let matched_row_expr = match (
        !navigation_offsets.previous().is_zero(),
        !navigation_offsets.next().is_zero(),
    ) {
        // Without a navigation offset, runtime did not add buffer rows.
        (false, false) => return None,
        (true, true) => valid_match_row_expr(),
        (true, false) => seq_col().gt_eq(lit(MIN_VALID_MATCH_SEQUENCE_NUMBER)),
        (false, true) => seq_col().lt_eq(lit(MAX_VALID_MATCH_SEQUENCE_NUMBER)),
    };

    Some(
        if matches!(
            rows_per_match,
            RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
        ) {
            seq_col().is_null().or(matched_row_expr)
        } else {
            matched_row_expr
        },
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::NavigationOffset;

    #[test]
    fn output_filter_keeps_the_exact_inclusive_sequence_maximum() {
        let next_only =
            NavigationOffsets::new(NavigationOffset::ZERO, NavigationOffset::ONE);
        assert_eq!(
            buffer_row_filter_expr(
                next_only,
                &RowsPerMatch::AllRows(EmptyMatchesMode::Show),
            ),
            Some(col("__mr_match_sequence_number").lt_eq(lit((1_i64 << 62) - 1)))
        );
    }

    #[test]
    fn all_rows_first_and_last_run_after_buffer_row_filter() -> Result<()> {
        use crate::core::{
            AfterMatchSkip, MatchRecognizeDefinition, MatchRecognizeMeasure,
            MatchRecognizeNullOrdering, MatchRecognizeOutputContract,
            MatchRecognizeSortDirection, MatchRecognizeSortExpr, Pattern, Symbol,
        };
        use crate::functions::udwf::{mr_first_udwf, mr_last_udwf, mr_prev_udwf};
        use crate::planning::{
            BoundMatchExpr, BoundMatchSpec, DefaultMatchRecognizePlanningContext,
            MatchNavigation, plan_match_recognize_from_source,
        };
        use datafusion::common::{Column, ScalarValue};
        use datafusion::logical_expr::{Operator, WindowFunctionDefinition};

        let input = LogicalPlanBuilder::values(vec![
            vec![lit(1_i64), lit(0_i64)],
            vec![lit(2_i64), lit(5_i64)],
        ])?
        .project(vec![col("column1").alias("ord"), col("column2").alias("x")])?
        .build()?;
        let ratio = || BoundMatchExpr::Binary {
            left: Box::new(BoundMatchExpr::Literal(ScalarValue::Int64(Some(100)))),
            op: Operator::Divide,
            right: Box::new(BoundMatchExpr::InputColumn(Column::from_name("x"))),
        };
        let spec = BoundMatchSpec {
            partition_by: vec![],
            order_by: vec![MatchRecognizeSortExpr {
                expr: BoundMatchExpr::InputColumn(Column::from_name("ord")),
                direction: MatchRecognizeSortDirection::Asc,
                null_ordering: MatchRecognizeNullOrdering::Last,
            }],
            source_rows_per_match: RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
            after_match_skip: AfterMatchSkip::PastLastRow,
            pattern: Pattern::Symbol(Symbol::Named("A".into())),
            symbols: vec!["A".into()],
            definitions: vec![MatchRecognizeDefinition {
                symbol: "A".into(),
                predicate: BoundMatchExpr::InputExpr(col("x").gt(lit(0_i64))),
            }],
            measures: vec![
                MatchRecognizeMeasure {
                    name: Some("prev_x".into()),
                    expression: BoundMatchExpr::Navigation(MatchNavigation::Prev {
                        expr: Box::new(BoundMatchExpr::InputColumn(Column::from_name(
                            "x",
                        ))),
                        offset: Some(Box::new(BoundMatchExpr::Literal(
                            ScalarValue::Int64(Some(1)),
                        ))),
                        default: Some(Box::new(BoundMatchExpr::Literal(
                            ScalarValue::Int64(Some(-1)),
                        ))),
                    }),
                },
                MatchRecognizeMeasure {
                    name: Some("first_ratio".into()),
                    expression: BoundMatchExpr::Navigation(MatchNavigation::First {
                        expr: Box::new(ratio()),
                        offset: None,
                    }),
                },
                MatchRecognizeMeasure {
                    name: Some("last_ratio".into()),
                    expression: BoundMatchExpr::Navigation(MatchNavigation::Last {
                        expr: Box::new(ratio()),
                        offset: None,
                    }),
                },
            ],
            output: MatchRecognizeOutputContract::Derived,
        };

        let plan = plan_match_recognize_from_source(
            &mut DefaultMatchRecognizePlanningContext::new(),
            input,
            spec,
        )?;
        let window_udwfs = |exprs: &[Expr]| {
            exprs
                .iter()
                .map(|expr| match expr {
                    Expr::Alias(alias) => alias.expr.as_ref(),
                    other => other,
                })
                .filter_map(|expr| match expr {
                    Expr::WindowFunction(wf) => match &wf.fun {
                        WindowFunctionDefinition::WindowUDF(udf) => Some(Arc::clone(udf)),
                        _ => None,
                    },
                    _ => None,
                })
                .collect::<Vec<_>>()
        };

        let LogicalPlan::Projection(projection) = &plan else {
            panic!("expected final projection, got {plan:?}");
        };
        let LogicalPlan::Window(post_filter) = projection.input.as_ref() else {
            panic!("expected post-filter Window for FIRST/LAST, got {plan:?}");
        };
        let LogicalPlan::Filter(buffer_filter) = post_filter.input.as_ref() else {
            panic!("expected buffer-row Filter below post-filter Window, got {plan:?}");
        };
        let LogicalPlan::Window(pre_filter) = buffer_filter.input.as_ref() else {
            panic!("expected pre-filter Window for PREV, got {plan:?}");
        };

        assert_eq!(
            buffer_filter.predicate,
            col(MatchMetadataColumn::MatchSequenceNumber.as_ref())
                .gt_eq(lit(MIN_VALID_MATCH_SEQUENCE_NUMBER))
        );
        let post_udwfs = window_udwfs(&post_filter.window_expr);
        assert_eq!(post_udwfs.len(), 2);
        assert!(post_udwfs.contains(&mr_first_udwf()));
        assert!(post_udwfs.contains(&mr_last_udwf()));
        assert_eq!(window_udwfs(&pre_filter.window_expr), vec![mr_prev_udwf()]);
        Ok(())
    }
}