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.

//! Keep Halo groups local when the parent observes only per-match aggregates.

use std::{cmp::Ordering, fmt, sync::Arc};

use crate::core::{EmptyMatchesMode, MatchMetadataColumn, RowsPerMatch};
use crate::planning::logical::MatchRecognize;
use datafusion::arrow::datatypes::{DataType, Field};
use datafusion::common::{DFSchema, DFSchemaRef, Result, tree_node::TreeNode};
use datafusion::logical_expr::{
    Expr, Extension, LogicalPlan, UserDefinedLogicalNodeCore, col,
    logical_plan::{Aggregate, Projection},
};

use crate::execution::physical::halo::HALO_CHUNK_ID;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(super) struct PhysicalMatchOutput {
    pub(super) matcher: MatchRecognize,
    schema: DFSchemaRef,
}

impl PhysicalMatchOutput {
    fn try_new(matcher: MatchRecognize) -> Result<Self> {
        let mut fields = matcher
            .schema()
            .iter()
            .map(|(q, f)| (q.cloned(), Arc::clone(f)))
            .collect::<Vec<_>>();
        fields.push((
            None,
            Arc::new(Field::new(HALO_CHUNK_ID, DataType::UInt64, true)),
        ));
        let schema = Arc::new(DFSchema::new_with_metadata(
            fields,
            matcher.schema().metadata().clone(),
        )?);
        Ok(Self { matcher, schema })
    }
}

impl PartialOrd for PhysicalMatchOutput {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        if self == other {
            Some(Ordering::Equal)
        } else {
            None
        }
    }
}

impl UserDefinedLogicalNodeCore for PhysicalMatchOutput {
    fn name(&self) -> &str {
        "MatchRecognizeGroupRows"
    }

    fn inputs(&self) -> Vec<&LogicalPlan> {
        vec![self.matcher.input()]
    }

    fn schema(&self) -> &DFSchemaRef {
        &self.schema
    }

    fn expressions(&self) -> Vec<Expr> {
        self.matcher.expressions()
    }

    fn fmt_for_explain(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.name())
    }

    fn with_exprs_and_inputs(
        &self,
        exprs: Vec<Expr>,
        inputs: Vec<LogicalPlan>,
    ) -> Result<Self> {
        Self::try_new(self.matcher.with_exprs_and_inputs(exprs, inputs)?)
    }
}

fn projection_preserves_key(p: &Projection, key: &Expr) -> bool {
    !key.exists(|node| {
        Ok(match node {
            Expr::Column(c) => {
                let Some(index) = p.schema.maybe_index_of_column(c) else {
                    return Ok(true);
                };
                let Expr::Column(inner) = &p.expr[index] else {
                    return Ok(true);
                };
                if inner == c {
                    false
                } else {
                    let Some(in_index) = p.input.schema().maybe_index_of_column(inner)
                    else {
                        return Ok(true);
                    };
                    p.input.schema().maybe_index_of_column(c) != Some(in_index)
                }
            }
            Expr::OuterReferenceColumn(..)
            | Expr::ScalarSubquery(_)
            | Expr::SetComparison(_)
            | Expr::Exists(_)
            | Expr::InSubquery(_) => true,
            _ => false,
        })
    })
    .expect("expression inspection is infallible")
}

/// MATCH_NUMBER must be a grouping key only. A projected number, an aggregate
/// of it, or an ordering expression using it still requires the dense ordinal.
pub(super) fn project(projection: &Projection) -> Result<Option<LogicalPlan>> {
    let LogicalPlan::Aggregate(group) = projection.input.as_ref() else {
        return Ok(None);
    };
    let number = MatchMetadataColumn::MatchNumber.as_ref();
    let reads_number = |expr: &Expr| {
        expr.exists(|node| {
            Ok(match node {
                Expr::Column(c) => c.name == number,
                Expr::OuterReferenceColumn(..)
                | Expr::ScalarSubquery(_)
                | Expr::SetComparison(_)
                | Expr::Exists(_)
                | Expr::InSubquery(_) => true,
                _ => false,
            })
        })
        .expect("expression inspection is infallible")
    };
    let Some((match_number, keys)) = group.group_expr.split_last() else {
        return Ok(None);
    };
    if group.aggr_expr.is_empty()
        || match_number != &col(number)
        || projection.expr.iter().any(reads_number)
        || group.aggr_expr.iter().any(reads_number)
    {
        return Ok(None);
    }
    // Common-subexpression projections may sit between the aggregate and the
    // matcher. The ordinal and partition keys can only pass through them
    // unmodified under their original identities.
    let mut projections = Vec::new();
    let mut input = group.input.as_ref();
    while let LogicalPlan::Projection(p) = input {
        let Some(index) = p.schema.index_of_column_by_name(None, number) else {
            return Ok(None);
        };
        if p.expr[index] != col(number)
            || p.expr
                .iter()
                .enumerate()
                .any(|(i, e)| i != index && reads_number(e))
            || !keys.iter().all(|key| projection_preserves_key(p, key))
        {
            return Ok(None);
        }
        projections.push(p);
        input = p.input.as_ref();
    }
    let LogicalPlan::Extension(extension) = input else {
        return Ok(None);
    };
    let Some(mr) = extension.node.as_any().downcast_ref::<MatchRecognize>() else {
        return Ok(None);
    };
    let Some(source) = mr.bound_source() else {
        return Ok(None);
    };
    if source.canonical_spec().as_spec().source_rows_per_match != RowsPerMatch::OneRow
        || mr.program().rows_per_match() != &RowsPerMatch::AllRows(EmptyMatchesMode::Show)
        || keys != mr.program().partition_by()
        || mr
            .program()
            .pattern()
            .structural_info()
            .max_match_rows()
            .is_none()
    {
        return Ok(None);
    }
    if group.schema.has_column_with_unqualified_name(HALO_CHUNK_ID)
        || mr.schema().has_column_with_unqualified_name(HALO_CHUNK_ID)
        || projections
            .iter()
            .any(|p| p.schema.has_column_with_unqualified_name(HALO_CHUNK_ID))
    {
        return Ok(None);
    }
    let mut rows = LogicalPlan::Extension(Extension {
        node: Arc::new(PhysicalMatchOutput::try_new(mr.clone())?),
    });
    for p in projections.into_iter().rev() {
        let mut expr = p.expr.clone();
        expr.push(col(HALO_CHUNK_ID));
        rows = LogicalPlan::Projection(Projection::try_new(expr, Arc::new(rows))?);
    }
    let mut groups = group.group_expr.clone();
    groups.push(col(HALO_CHUNK_ID));
    let mut outer = projection.clone();
    outer.input = Arc::new(LogicalPlan::Aggregate(Aggregate::try_new(
        Arc::new(rows),
        groups,
        group.aggr_expr.clone(),
    )?));
    Ok(Some(LogicalPlan::Projection(outer)))
}