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.

//! Native matcher-owned summary admission for `ONE ROW PER MATCH` programs.

use datafusion::common::DFSchema;
use datafusion::common::tree_node::{Transformed, TransformedResult, TreeNode};
use datafusion::logical_expr::utils::{find_aggregate_exprs, find_window_exprs};
use datafusion::logical_expr::{Expr, ExprSchemable, col};
use datafusion_optimizer::analyzer::type_coercion::TypeCoercionRewriter;
use std::collections::{HashMap, HashSet};

use crate::core::MatchSummaryField;
use crate::planning::NamedExpr;
use crate::planning::logical::LogicalSelectedMatchSummary;

/// A complete ONE ROW measure program that the matcher can finalize directly.
pub(crate) struct SelectedMatchSummaryPlan {
    pub(crate) summaries: Vec<LogicalSelectedMatchSummary>,
    pub(crate) measures_exprs: Vec<NamedExpr>,
}

/// Select native one-row finalization when every aggregate leaf can use
/// DataFusion's ordinary aggregate contract over a selected-match row stream.
/// Any unsupported complete program retains downstream finalization.
pub(crate) fn plan_selected_match_summaries(
    measures_exprs: &[NamedExpr],
    summary_input_schema: &DFSchema,
    group_exprs: &[Expr],
    direct_only: bool,
) -> Option<SelectedMatchSummaryPlan> {
    // Private aggregate leaves need coercion against their selected-row schema.
    // Direct summaries leave outer scalars for the session-aware analyzer;
    // coercing them here would assign UTC to naive timestamps prematurely.
    let mut coercer = TypeCoercionRewriter::new(summary_input_schema);
    let coerced_measure_exprs = measures_exprs
        .iter()
        .map(|measure| {
            let expr = measure.expr.clone();
            if direct_only {
                expr.transform_down(|node| {
                    if matches!(node, Expr::AggregateFunction(_)) {
                        node.rewrite(&mut coercer)
                    } else {
                        Ok(Transformed::no(node))
                    }
                })
                .data()
                .ok()
            } else {
                expr.rewrite(&mut coercer).data().ok()
            }
        })
        .collect::<Option<Vec<_>>>()?;
    if !find_window_exprs(&coerced_measure_exprs).is_empty() {
        return None;
    }
    let mut summaries = Vec::new();
    let mut shared = HashMap::new();
    let allowed_group_columns = group_exprs
        .iter()
        .filter_map(|expr| match expr {
            Expr::Column(column) => Some(column.clone()),
            _ => None,
        })
        .collect::<HashSet<_>>();
    let rebased_measures = coerced_measure_exprs
        .into_iter()
        .map(|expr| {
            expr.transform_down(|node| {
                let Expr::AggregateFunction(aggregate) = &node else {
                    return Ok(Transformed::no(node));
                };
                let shareable = !node.is_volatile();
                if shareable && let Some(replacement) = shared.get(&node) {
                    return Ok(Transformed::yes(Expr::clone(replacement)));
                }
                let (_, field) = node.to_field(summary_input_schema)?;
                let field = MatchSummaryField::new(summaries.len(), field);
                let replacement = col(field.column_name());
                let summary = LogicalSelectedMatchSummary::new(field, aggregate.clone());
                if direct_only
                    && summary.selected_path_summary().is_none()
                    && summary.selected_reduction(summary_input_schema).is_none()
                {
                    return datafusion::common::plan_err!(
                        "measure requires ordinary aggregation"
                    );
                }
                summaries.push(summary);
                if shareable {
                    shared.insert(node, replacement.clone());
                }
                Ok(Transformed::yes(replacement))
            })
            .data()
            .ok()
        })
        .collect::<Option<Vec<_>>>()?;
    let summary_schema = DFSchema::new_with_metadata(
        summaries
            .iter()
            .map(|summary| (None, summary.field().arrow_field()))
            .collect::<Vec<_>>(),
        HashMap::new(),
    )
    .ok()?;
    let result_schema = summary_input_schema.join(&summary_schema).ok()?;
    let measures_exprs = measures_exprs
        .iter()
        .zip(rebased_measures)
        .map(|(measure, expr)| {
            let only_approved_columns = expr.column_refs().iter().all(|column| {
                allowed_group_columns.contains(*column)
                    || summaries
                        .iter()
                        .any(|summary| summary.field().column_name() == column.name)
            });
            if !find_aggregate_exprs(std::iter::once(&expr)).is_empty()
                || !only_approved_columns
                || expr.to_field(&result_schema).is_err()
            {
                return None;
            }
            Some(NamedExpr {
                expr,
                name: measure.name.clone(),
            })
        })
        .collect::<Option<Vec<_>>>()?;
    Some(SelectedMatchSummaryPlan {
        summaries,
        measures_exprs,
    })
}