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.

//! Verify and map upstream SQL `LAG`/`LEAD` window operators to physical row shifts.

use crate::planning::logical::MatchRecognize;
use datafusion::arrow::datatypes::DataType;
use datafusion::functions_window::lead_lag::{WindowShift, WindowShiftKind};
use datafusion::logical_expr::{Expr, LogicalPlan, WindowFunctionDefinition};
use datafusion::physical_plan::windows::{
    BoundedWindowAggExec, WindowAggExec, WindowUDFExpr,
};
use datafusion::physical_plan::{ExecutionPlan, PhysicalExpr};
use datafusion_common::ScalarValue;
use datafusion_physical_expr::expressions::{Column, Literal};
use datafusion_physical_expr::projection::ProjectionExpr;
use datafusion_physical_expr::window::{StandardWindowExpr, WindowExpr};
use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
use std::{collections::HashMap, sync::Arc};

/// The physical UDF keeps null treatment private. Match each discarded window
/// output to its canonical logical call, including the direction before any reversal.
fn logical_directions(mr: &MatchRecognize) -> Option<HashMap<String, bool>> {
    let mut node = mr.input();
    while let LogicalPlan::Projection(projection) = node {
        node = projection.input.as_ref();
    }
    let mut directions = HashMap::new();
    while let LogicalPlan::Window(window) = node {
        for (i, expr) in window.window_expr.iter().enumerate() {
            let Expr::WindowFunction(function) = expr.clone().unalias() else {
                return None;
            };
            let WindowFunctionDefinition::WindowUDF(udf) = &function.fun else {
                return None;
            };
            let shift = udf.inner().downcast_ref::<WindowShift>()?;
            if function.params.null_treatment.is_some()
                || function.params.filter.is_some()
                || function.params.distinct
            {
                return None;
            }
            let name = window
                .schema
                .field(window.input.schema().fields().len() + i)
                .name();
            if directions
                .insert(name.clone(), *shift.kind() == WindowShiftKind::Lead)
                .is_some()
            {
                return None;
            }
        }
        node = window.input.as_ref();
    }
    (!directions.is_empty()).then_some(directions)
}

type WindowInput<'a> = (&'a [Arc<dyn WindowExpr>], &'a Arc<dyn ExecutionPlan>);

fn window_input(node: &Arc<dyn ExecutionPlan>) -> Option<WindowInput<'_>> {
    if let Some(exec) = node.downcast_ref::<BoundedWindowAggExec>() {
        Some((exec.window_expr(), exec.input()))
    } else {
        let exec = node.downcast_ref::<WindowAggExec>()?;
        Some((exec.window_expr(), exec.input()))
    }
}

type PhysicalShift = (Column, i64, Option<Arc<ScalarValue>>);

fn window_shift(
    expr: &dyn WindowExpr,
    lead: bool,
    schema: &datafusion::arrow::datatypes::Schema,
) -> Option<PhysicalShift> {
    let standard = expr.as_any().downcast_ref::<StandardWindowExpr>()?;
    let udf = standard
        .get_standard_func_expr()
        .as_any()
        .downcast_ref::<WindowUDFExpr>()?;
    let shift = udf.fun().inner().downcast_ref::<WindowShift>()?;
    if lead != (*shift.kind() == WindowShiftKind::Lead) {
        return None;
    }
    literal_default_shift(udf.args(), expr.field().ok()?.data_type(), lead, schema)
}

pub(super) fn literal_default_shift(
    args: &[Arc<dyn PhysicalExpr>],
    output_type: &DataType,
    lead: bool,
    schema: &datafusion::arrow::datatypes::Schema,
) -> Option<PhysicalShift> {
    let source = args.first()?.downcast_ref::<Column>()?;
    let source_type = schema.fields().get(source.index())?.data_type();
    // DataFusion's `WindowShift` can refine a `DataType::Null` source column to
    // the 3rd argument's type even when that default is a typed NULL literal.
    // Reject any shift whose output type differs from the raw source column.
    if output_type != source_type {
        return None;
    }
    let offset = match args.get(1) {
        None => 1,
        Some(expr) => match expr.downcast_ref::<Literal>()?.value() {
            ScalarValue::Int64(Some(v)) if *v >= 0 => *v,
            ScalarValue::UInt64(Some(v)) => i64::try_from(*v).ok()?,
            _ => return None,
        },
    };
    let default = match args.get(2) {
        Some(arg) if args.len() == 3 => {
            let literal = arg.downcast_ref::<Literal>()?.value();
            if literal.is_null() {
                // WindowShift casts typed NULL defaults too. Keep the SQL window
                // when that cast fails so it still reports DataFusion's error.
                if !literal.data_type().is_null() && source_type != &literal.data_type() {
                    literal.cast_to(source_type).ok()?;
                }
                None
            } else {
                // DataFusion's `WindowShift` casts typed default literals to
                // `source`'s type when `source` is not `DataType::Null`, and
                // refines a `Null` source column to the default's type instead.
                if source_type.is_null()
                    || source_type.is_nested()
                    || matches!(
                        source_type,
                        DataType::Dictionary(..)
                            | DataType::Union(..)
                            | DataType::RunEndEncoded(..)
                    )
                {
                    return None;
                }
                let coerced = if source_type == &literal.data_type() {
                    literal.clone()
                } else {
                    literal.cast_to(source_type).ok()?
                };
                if coerced.is_null()
                    || matches!(&coerced, ScalarValue::Utf8(Some(s)) if s.len() > i32::MAX as usize)
                    || matches!(&coerced, ScalarValue::Binary(Some(b)) if b.len() > i32::MAX as usize)
                {
                    return None;
                }
                Some(Arc::new(coerced))
            }
        }
        None => None,
        _ => return None,
    };
    Some((source.clone(), if lead { offset } else { -offset }, default))
}

pub(in crate::execution) type ShiftMap = HashMap<usize, PhysicalShift>;

pub(in crate::execution) fn checked_windows_on<'a>(
    mut input: &'a Arc<dyn ExecutionPlan>,
    raw: &[ProjectionExpr],
    mr: &MatchRecognize,
    partition: &[Arc<dyn PhysicalExpr>],
    order: &[PhysicalSortExpr],
) -> Option<(&'a Arc<dyn ExecutionPlan>, ShiftMap)> {
    window_input(input)?;
    let mut directions = logical_directions(mr)?;
    // The matcher binds keys against its public prefix. Windows bind against
    // the unprojected input. Compare those expressions in the same coordinate space.
    let rebase = |expr: &Arc<dyn PhysicalExpr>| {
        let column = expr.downcast_ref::<Column>()?;
        Some(Arc::clone(&raw.get(column.index())?.expr))
    };
    let keys = partition.iter().map(rebase).collect::<Option<Vec<_>>>()?;
    // Nested and encoded partition keys can require key-comparison scratch
    // outside a head. Keep the upstream SQL window evaluator for them.
    let base_schema = input.schema();
    if !keys.iter().all(|key| {
        key.data_type(base_schema.as_ref()).is_ok_and(|ty| {
            !ty.is_nested()
                && !matches!(ty, DataType::Dictionary(..) | DataType::RunEndEncoded(..))
        })
    }) {
        return None;
    }
    let sort = order
        .iter()
        .map(|s| {
            Some(PhysicalSortExpr {
                expr: rebase(&s.expr)?,
                options: s.options,
            })
        })
        .collect::<Option<Vec<_>>>()?;
    let mut shifts = HashMap::new();
    while let Some((windows, child)) = window_input(input) {
        let start = child.schema().fields().len();
        let fields = input.schema();
        for (i, window) in windows.iter().enumerate() {
            if window.partition_by() != keys || window.order_by() != sort {
                return None;
            }
            let lead = directions.remove(fields.field(start + i).name())?;
            shifts.insert(
                start + i,
                window_shift(window.as_ref(), lead, &child.schema())?,
            );
        }
        input = child;
    }
    let width = input.schema().fields().len();
    (directions.is_empty() && shifts.values().all(|(source, ..)| source.index() < width))
        .then_some((input, shifts))
}