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.

//! Bind leaves once; the runtime uses one evaluator for every admitted domain.
use super::*;
use crate::execution::matching::ResolvedInputColumn;

#[derive(Debug, Clone)]
pub(super) enum Source {
    Literal(ScalarValue),
    Column(usize, VmScalarType),
    Managed(usize, BoundStateCell, VmScalarType),
    Navigation(
        BoundNavigation,
        Option<super::super::types::PackedNavigationRead>,
        VmScalarType,
        Option<crate::execution::matching::program::validated_vm::RegisterId>,
    ),
    MatchNumber,
    MatchSequenceNumber,
}
#[derive(Debug, Clone)]
pub(crate) struct RowValueSourceBindings {
    pub(crate) batch_columns: Vec<ResolvedInputColumn>,
}
#[derive(Debug, Clone)]
pub(crate) struct BoundPredicate {
    pub(super) ops: Vec<Op>,
    direct: bool,
    total: bool,
    pub(crate) row_value_bindings: RowValueSourceBindings,
}
impl BoundPredicate {
    pub(crate) fn bind_direct_predicate(
        schema: &Schema,
        layout: &RegisterLayout,
        cells: &[BoundStateCell],
        rows: &ResolvedRowBindings,
        plan: &DirectPredicatePlan,
    ) -> datafusion_common::Result<Self> {
        let packed = layout
            .navigation_layout()
            .map(super::super::types::PackedNavigationLayout::try_new)
            .transpose()?;
        let columns = plan
            .row_columns()
            .iter()
            .map(|name| {
                resolve_unique_column(schema, name, "predicate source")
                    .map(|(col, _)| col)
            })
            .collect::<datafusion_common::Result<Vec<_>>>()?;
        let bind = |source: &VmSourceRef| -> datafusion_common::Result<Source> {
            let column = |column: ResolvedInputColumn,
                          ty: VmType|
             -> datafusion_common::Result<Source> {
                validate_typed_column(schema, column, ty, "predicate source")?;
                Ok(Source::Column(column.index(), ty.scalar))
            };
            Ok(match source {
                VmSourceRef::Literal(v) => Source::Literal(v.clone()),
                VmSourceRef::ManagedSlot { slot_idx, ty } => {
                    let cell = cells
                        .get(*slot_idx as usize)
                        .ok_or_else(|| invalid_binding("managed source index".into()))?;
                    let actual = crate::planning::predicate::vm_type_from_data_type(
                        cell.output_type(),
                        true,
                    )
                    .ok_or_else(|| invalid_binding("managed source type".into()))?;
                    validate_vm_type_compatibility(actual, *ty, "managed source")?;
                    if let BoundStateSource::Navigation(read) = cell.source() {
                        Source::Navigation(
                            read.clone(),
                            packed.as_ref().and_then(|p| p.resolve(read.lookup())),
                            ty.scalar,
                            cell.nonnull_count_slot(),
                        )
                    } else {
                        Source::Managed(*slot_idx as usize, cell.clone(), ty.scalar)
                    }
                }
                VmSourceRef::RowValue { column_ref, ty } => column(
                    *columns
                        .get(*column_ref as usize)
                        .ok_or_else(|| invalid_binding("row source index".into()))?,
                    *ty,
                )?,
                VmSourceRef::StaticScalar { scalar_idx, ty } => {
                    let binding = rows
                        .static_scalar_columns
                        .get(*scalar_idx as usize)
                        .and_then(Option::as_ref)
                        .ok_or_else(|| invalid_binding("static scalar index".into()))?;
                    column(binding.column, *ty)?
                }
                VmSourceRef::StaticPredicate { bool_idx } => {
                    let col = rows
                        .static_predicate_columns
                        .get(*bool_idx as usize)
                        .ok_or_else(|| invalid_binding("static Boolean index".into()))?;
                    let resolved = ResolvedInputColumn::new_validated(col.index());
                    column(resolved, VmType::nullable(VmScalarType::Bool))?
                }
                VmSourceRef::MatchNumber => Source::MatchNumber,
                VmSourceRef::MatchSequenceNumber => Source::MatchSequenceNumber,
            })
        };
        enum Task {
            Visit(u16),
            Emit(Op),
            Guard(bool),
            GuardNotNull,
            FinishGuard,
        }
        let mut pending = vec![Task::Visit(plan.root())];
        let mut guards = vec![];
        let mut ops = vec![];
        while let Some(task) = pending.pop() {
            match task {
                Task::Visit(id) => match &plan.nodes()[id as usize] {
                    PredicateNode::Source(s) => ops.push(Op::Read(bind(s)?)),
                    PredicateNode::Binary {
                        op,
                        out_ty,
                        left,
                        right,
                    } => {
                        let guard = matches!(op, VmBinaryOp::And | VmBinaryOp::Or);
                        if guard {
                            pending.push(Task::FinishGuard);
                        }
                        pending.extend([
                            Task::Emit(Op::Binary(*op, out_ty.scalar)),
                            Task::Visit(*right),
                        ]);
                        if guard {
                            pending.push(Task::Guard(*op == VmBinaryOp::Or));
                        }
                        pending.push(Task::Visit(*left));
                    }
                    PredicateNode::Coalesce { left, right, .. } => {
                        pending.extend([
                            Task::FinishGuard,
                            Task::Visit(*right),
                            Task::Emit(Op::Pop),
                            Task::GuardNotNull,
                            Task::Visit(*left),
                        ]);
                    }
                    node => {
                        let (op, input) = match node {
                            PredicateNode::Unary { op, out_ty, input } => {
                                (Unary::Operator(*op, out_ty.scalar), input)
                            }
                            PredicateNode::Cast { target_ty, input } => {
                                (Unary::Cast(target_ty.scalar), input)
                            }
                            PredicateNode::IsNull { input } => {
                                (Unary::NullTest(true), input)
                            }
                            PredicateNode::IsNotNull { input } => {
                                (Unary::NullTest(false), input)
                            }
                            _ => unreachable!(),
                        };
                        pending.extend([Task::Emit(Op::Unary(op)), Task::Visit(*input)]);
                    }
                },
                Task::Emit(op) => ops.push(op),
                Task::Guard(decisive) => {
                    guards.push(ops.len());
                    ops.push(Op::Guard {
                        decisive,
                        resume: 0,
                    });
                }
                Task::GuardNotNull => {
                    guards.push(ops.len());
                    ops.push(Op::GuardNotNull { resume: 0 });
                }
                Task::FinishGuard => {
                    let resume = ops.len();
                    let index = guards.pop().expect("guard");
                    match &mut ops[index] {
                        Op::Guard { resume: r, .. } | Op::GuardNotNull { resume: r } => {
                            *r = resume;
                        }
                        _ => unreachable!("guard index must point to a guard op"),
                    }
                }
            }
        }
        let register_only = ops.iter().all(|op| match op {
            Op::Read(Source::Column(..) | Source::Navigation(..)) => false,
            Op::Read(Source::Managed(_, cell, _)) => {
                cell.source().is_register_state_local()
            }
            _ => true,
        });
        let direct = ops.iter().all(|op| match op {
            Op::Read(Source::Column(_, ty) | Source::Navigation(_, _, ty, _)) => {
                !ty.is_string()
            }
            Op::Read(Source::Managed(_, cell, ty)) => {
                !ty.is_string()
                    && !matches!(
                        cell.source(),
                        BoundStateSource::AccumulatorOwned
                            | BoundStateSource::RetainedRow { .. }
                    )
            }
            _ => true,
        });
        let total = register_only
            && ops.iter().all(|op| {
                !matches!(
                    op,
                    Op::Read(Source::Managed(_, _, VmScalarType::Decimal128 { .. }))
                        | Op::Unary(
                            Unary::Cast(_)
                                | Unary::Operator(
                                    VmUnaryOp::Neg
                                        | VmUnaryOp::CheckedNeg
                                        | VmUnaryOp::Abs,
                                    _,
                                ),
                        )
                        | Op::Binary(
                            VmBinaryOp::Add
                                | VmBinaryOp::Sub
                                | VmBinaryOp::Mul
                                | VmBinaryOp::AddInterval
                                | VmBinaryOp::SubInterval,
                            _
                        )
                )
            });
        Ok(Self {
            ops,
            direct,
            total,
            row_value_bindings: RowValueSourceBindings {
                batch_columns: columns,
            },
        })
    }

    pub(crate) fn has_total_register_predicate(&self) -> bool {
        self.total
    }
    pub(crate) fn has_direct_readers(&self) -> bool {
        self.direct
    }
    pub(crate) fn direct_loop_work(&self) -> Option<usize> {
        self.direct.then_some(self.ops.len() + 1)
    }
}
fn resolve_unique_column<'a>(
    schema: &'a Schema,
    name: &str,
    context: &str,
) -> datafusion_common::Result<(ResolvedInputColumn, &'a DataType)> {
    let exact_matches = schema
        .fields()
        .iter()
        .enumerate()
        .filter_map(|(index, field)| (field.name() == name).then_some(index))
        .collect::<Vec<_>>();
    let matches = if exact_matches.is_empty() {
        schema
            .fields()
            .iter()
            .enumerate()
            .filter_map(|(index, field)| {
                field.name().eq_ignore_ascii_case(name).then_some(index)
            })
            .collect::<Vec<_>>()
    } else {
        exact_matches
    };

    let index = match matches.as_slice() {
        [index] => *index,
        [] => {
            return Err(invalid_binding(format!(
                "{context} column '{name}' is missing from the input schema"
            )));
        }
        _ => {
            return Err(invalid_binding(format!(
                "{context} column '{name}' is ambiguous in the input schema (matching indices: {matches:?})"
            )));
        }
    };
    Ok((
        ResolvedInputColumn::new_validated(index),
        schema.field(index).data_type(),
    ))
}

pub(crate) fn validate_typed_column(
    schema: &Schema,
    column: ResolvedInputColumn,
    expected: VmType,
    context: &str,
) -> datafusion_common::Result<()> {
    let field = schema.field(column.index());
    let actual = crate::planning::predicate::vm_type_from_data_type(
        field.data_type(),
        field.is_nullable(),
    )
    .ok_or_else(|| {
        invalid_binding(format!(
            "{context} column '{}' has unsupported type {}",
            field.name(),
            field.data_type()
        ))
    })?;
    validate_vm_type_compatibility(
        actual,
        expected,
        &format!("{context} column '{}'", field.name()),
    )
}

fn validate_vm_type_compatibility(
    actual: VmType,
    declared: VmType,
    source: &str,
) -> datafusion_common::Result<()> {
    if actual.scalar != declared.scalar {
        return Err(invalid_binding(format!(
            "{source} has VM type {:?}, but the predicate declares {:?}",
            actual.scalar, declared.scalar
        )));
    }
    // Physical expressions may conservatively widen logical nullability. Readers
    // check NULLs dynamically (Source::Column retains only the scalar type), so
    // both widening and the already-supported narrowing are safe here.
    Ok(())
}

pub(crate) fn invalid_binding(reason: String) -> datafusion_common::DataFusionError {
    datafusion_common::DataFusionError::Internal(format!(
        "MATCH_RECOGNIZE invalid typed predicate binding: {reason}"
    ))
}