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.

//! Dense schemas for raw transport, ordered row values and one-candidate fallback.

use super::stateful_classification::{BoundInput, protected_columns};
use crate::core::MatchMetadataColumn;
use crate::execution::classification::PredicateValidity;
use crate::execution::classification::StaticClassification;
use crate::execution::matching::ExecutableMatchProgram;
use crate::planning::logical::MatchRecognize;
use datafusion::arrow::datatypes::SchemaRef;
use datafusion::common::{
    DFSchema, Result, ScalarValue, internal_datafusion_err, tree_node::TreeNode,
};
use datafusion::logical_expr::{
    LogicalPlan, UserDefinedLogicalNodeCore, logical_plan::EmptyRelation,
};
use datafusion::physical_expr::{
    PhysicalExpr,
    equivalence::AcrossPartitions,
    expressions::{Column, Literal},
    utils::collect_columns,
};
use datafusion::physical_expr_common::sort_expr::PhysicalSortExpr;
use datafusion::physical_plan::{
    ExecutionPlan, ExecutionPlanProperties, projection::ProjectionExec,
};
use std::{collections::HashSet, sync::Arc};

#[derive(Debug)]
pub(crate) struct VirtualInputMapping {
    /// Raw input fields followed by the post-order classifier and offset results.
    pub(crate) working_schema: SchemaRef,
    /// Also includes private slots supplied only to one-row physical predicates.
    pub(crate) fallback_schema: SchemaRef,
    pub(crate) fallback_literals: Vec<ScalarValue>,
}

pub(in crate::execution) struct CompactInput {
    pub(in crate::execution) input: Arc<dyn ExecutionPlan>,
    pub(in crate::execution) mapping: VirtualInputMapping,
    /// Only an ordinal permutation needs to rebind the checked matcher expressions.
    pub(in crate::execution) rebound: Option<(MatchRecognize, Arc<dyn ExecutionPlan>)>,
}

pub(in crate::execution) fn compact(
    mr: &MatchRecognize,
    program: &ExecutableMatchProgram,
    bound: &mut BoundInput,
    partition: &[Arc<dyn PhysicalExpr>],
    order: &[PhysicalSortExpr],
) -> Result<Option<CompactInput>> {
    if bound
        .classification
        .as_ref()
        .is_some_and(|c| !c.demanded.is_empty())
    {
        return Ok(None);
    }
    let Some(projection) = bound.input.downcast_ref::<ProjectionExec>() else {
        return Ok(None);
    };
    let schema = projection.schema();
    let output = program.output_plan();
    let mut protected = protected_columns(program, mr, output.spec(), partition, order);
    let managed: HashSet<_> = program
        .aggregate_programs()
        .iter()
        .map(|a| a.column().index())
        .collect();
    let mut derived = HashSet::new();
    if let Some(class) = &bound.classification {
        derived.extend(class.predicates.iter().map(|p| p.output));
        derived.extend(class.lane_column);
    }
    if let Some(offsets) = &bound.offsets {
        derived.extend(offsets.columns.iter().map(|(i, _)| *i));
    }
    if !derived.is_disjoint(&protected) {
        return Ok(None);
    }
    for agg in program.aggregate_programs() {
        protected.extend(
            agg.input_expressions()
                .iter()
                .flat_map(|e| collect_columns(e).into_iter().map(|c| c.index())),
        );
    }
    program
        .vm_program()
        .visit_direct_predicate_columns(|column| {
            protected.insert(column);
        });
    let mut raw = Vec::new();
    let mut computed = Vec::new();
    let mut scratch = Vec::new();
    let mut literals = Vec::new();
    let classifier_flags: HashSet<_> = mr
        .program()
        .symbols()
        .iter()
        .map(|s| crate::core::classifier_bits_col_name(s.name()))
        .collect();
    for (i, expr) in projection.expr().iter().enumerate() {
        if derived.contains(&i) {
            // A Boolean identity can be both a real operand and its own
            // result slot. Keep its value available while classifying the head.
            if expr.expr.downcast_ref::<Column>().is_some() {
                raw.push(i);
            } else {
                computed.push(i);
            }
        } else if !protected.contains(&i)
            && (managed.contains(&i)
                || bound.unused_window_columns.contains(&i)
                || MatchMetadataColumn::all()
                    .iter()
                    .any(|m| m.as_ref() == expr.alias)
                || classifier_flags.contains(&expr.alias))
            // Removing a window may expose a column forwarding a NULL from a
            // lower projection. Its known value is just as exact as a literal.
            && (expr.expr.is::<Literal>() || expr.expr.is::<Column>())
            && let Some(AcrossPartitions::Uniform(Some(value))) = projection
                .input()
                .equivalence_properties()
                .is_expr_constant(&expr.expr)
            && value.is_null()
            && value.data_type() == *schema.field(i).data_type()
        {
            scratch.push(i);
            literals.push(value);
        } else {
            raw.push(i);
        }
    }
    if raw.is_empty() || (computed.is_empty() && scratch.is_empty()) {
        return Ok(None);
    }
    // Avoid upstream constraint-index projection until DataFusion can remap
    // unique keys safely when narrowing a projection through the input tree.
    if projection
        .input()
        .exists(|p| Ok(!p.equivalence_properties().constraints().is_empty()))?
    {
        return Ok(None);
    }
    let input = Arc::new(ProjectionExec::try_new(
        raw.iter()
            .map(|i| projection.expr()[*i].clone())
            .collect::<Vec<_>>(),
        projection.input().clone(),
    )?) as Arc<dyn ExecutionPlan>;
    let mut permutation = raw;
    permutation.extend(computed);
    let working_schema = Arc::new(schema.project(&permutation)?);
    permutation.extend(scratch);
    let fallback_schema = Arc::new(schema.project(&permutation)?);
    let rebound = if permutation.iter().enumerate().any(|(new, &old)| new != old) {
        let original = mr.input().schema();
        let fields = permutation
            .iter()
            .map(|&old| {
                if old < original.fields().len() {
                    (
                        original.qualified_field(old).0.cloned(),
                        original.fields()[old].clone(),
                    )
                } else {
                    (None, schema.fields()[old].clone())
                }
            })
            .collect();
        // Program expressions are rebound by qualified logical name. The child is
        // schema-only; the actual scan always receives the compact projection above.
        let child = LogicalPlan::EmptyRelation(EmptyRelation {
            produce_one_row: false,
            schema: Arc::new(DFSchema::new_with_metadata(
                fields,
                original.metadata().clone(),
            )?),
        });
        let logical = mr.with_exprs_and_inputs(mr.expressions(), vec![child])?;
        if logical.schema() != mr.schema() {
            return Ok(None);
        }
        let mut index = vec![0; permutation.len()];
        for (new, &old) in permutation.iter().enumerate() {
            index[old] = new;
        }
        if let Some(class) = &mut bound.classification {
            for p in &mut class.predicates {
                p.output = index[p.output];
                if let PredicateValidity::Column(i) = &mut p.validity {
                    *i = index[*i];
                }
            }
            class.lane_column = class.lane_column.map(|i| index[i]);
            for rule in &mut bound.rules {
                rule.remap_input(&index);
            }
            class.classifier = Arc::new(
                StaticClassification::for_predicates(std::mem::take(&mut bound.rules))
                    .ok_or_else(|| {
                        internal_datafusion_err!(
                            "failed to rebind ordered classifier columns"
                        )
                    })?,
            );
        }
        if let Some(offsets) = &mut bound.offsets {
            for (i, src) in &mut offsets.columns {
                *i = index[*i];
                src.column = index[src.column];
            }
        }
        let full: Arc<dyn ExecutionPlan> = Arc::new(ProjectionExec::try_new(
            permutation
                .iter()
                .map(|&i| projection.expr()[i].clone())
                .collect::<Vec<_>>(),
            projection.input().clone(),
        )?);
        Some((logical, full))
    } else {
        None
    };
    Ok(Some(CompactInput {
        input,
        mapping: VirtualInputMapping {
            working_schema,
            fallback_schema,
            fallback_literals: literals,
        },
        rebound,
    }))
}