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.

//! Checked physical expression predicates over compact current and shifted leaves.

use super::int64_compare::Int64Compare;
use super::shifted;
use super::{NavigationInput, Neighbor};
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::storage::history_buffer::SharedHistoryBuffer;
use datafusion::arrow::array::{ArrayRef, AsArray};
use datafusion::arrow::datatypes::{DataType, SchemaRef};
use datafusion::arrow::record_batch::{RecordBatch, RecordBatchOptions};
use datafusion::common::{Result, ScalarValue, internal_err};
use datafusion::execution::memory_pool::MemoryReservation;
use datafusion::physical_plan::PhysicalExpr;
use std::ops::Range;
use std::sync::Arc;

/// A checked predicate over a compact RecordBatch of current and shifted leaves.
#[derive(Debug, Clone)]
pub(crate) struct OffsetExpression {
    predicate: Arc<dyn PhysicalExpr>,
    pub(super) inputs: Vec<Neighbor>,
    pub(super) schema: SchemaRef,
    pub(super) int64_compare: Option<Int64Compare>,
}

/// Materialize and admit a partition-edge literal in one cooperative chunk.
pub(crate) fn fill_offset_default(
    value: &ScalarValue,
    rows: usize,
    memory: &MemoryReservation,
) -> Result<ArrayRef> {
    debug_assert!(rows <= COARSE_WORK_BATCH_SIZE);
    let array = value.to_array_of_size(rows)?;
    memory.try_grow(array.get_array_memory_size())?;
    Ok(array)
}

impl OffsetExpression {
    pub(crate) fn mark_referenced_input_columns(&self, needed: &mut [bool]) {
        for neighbor in &self.inputs {
            if let Some(slot) = needed.get_mut(neighbor.column) {
                *slot = true;
            }
        }
    }

    pub(crate) fn try_new(
        predicate: Arc<dyn PhysicalExpr>,
        inputs: Vec<Neighbor>,
        schema: SchemaRef,
    ) -> Option<Self> {
        if inputs.len() != schema.fields().len()
            || predicate.data_type(&schema).ok()? != DataType::Boolean
        {
            return None;
        }
        // Keep the supported leaf and intermediate types checked at binding.
        fn is_supported_type(ty: &DataType) -> bool {
            matches!(ty, DataType::Null | DataType::Boolean)
                || ty.primitive_width().is_some()
        }
        let is_text_type = |ty: &DataType| {
            matches!(
                ty,
                DataType::Utf8 | DataType::Utf8View | DataType::LargeUtf8
            )
        };
        let text_leaves = inputs.iter().any(|n| n.default.is_some())
            && schema.fields().iter().any(|f| is_text_type(f.data_type()));
        let is_supported_leaf_type =
            |ty: &DataType| is_supported_type(ty) || (text_leaves && is_text_type(ty));
        if !schema
            .fields()
            .iter()
            .all(|f| is_supported_leaf_type(f.data_type()))
        {
            return None;
        }
        let mut pending = vec![&predicate];
        while let Some(node) = pending.pop() {
            let ty = node.data_type(&schema).ok()?;
            if !(is_supported_type(&ty)
                || (node.children().is_empty() && is_supported_leaf_type(&ty)))
            {
                return None;
            }
            pending.extend(node.children());
        }
        let has_shift = inputs.iter().any(|n| n.shift != 0);
        let int64_compare = Int64Compare::bind_arithmetic(predicate.as_ref(), &schema)
            .or_else(|| {
                (!has_shift)
                    .then(|| Int64Compare::bind_offset(predicate.as_ref(), &schema))
                    .flatten()
            });
        Some(Self {
            predicate,
            inputs,
            schema,
            int64_compare,
        })
    }

    /// Assemble one bounded expression batch. A leaf that needs retained history
    /// or a materialized default can use the existing segmented evaluator.
    #[inline]
    pub(super) fn batch_inputs(
        &self,
        input: NavigationInput<'_>,
        batch_start: usize,
        batch: &RecordBatch,
        start: usize,
        len: usize,
    ) -> Result<Option<RecordBatch>> {
        let mut arrays = Vec::with_capacity(self.inputs.len());
        for neighbor in &self.inputs {
            let Some(array) = shifted::try_shifted_input(
                neighbor,
                input,
                batch_start,
                batch,
                start,
                len,
            )?
            else {
                return Ok(None);
            };
            arrays.push(array);
        }
        Ok(Some(RecordBatch::try_new_with_options(
            Arc::clone(&self.schema),
            arrays,
            &RecordBatchOptions::new().with_row_count(Some(len)),
        )?))
    }

    pub(super) fn classify(
        &self,
        history: &SharedHistoryBuffer,
        partition: &Range<usize>,
        mut row: usize,
        mut out: &mut [u64],
        bit: u64,
        memory: &MemoryReservation,
    ) -> Result<()> {
        while !out.is_empty() {
            let mut len = out.len().min(COARSE_WORK_BATCH_SIZE);
            let mut spans = Vec::with_capacity(self.inputs.len());
            for neighbor in &self.inputs {
                let (span, count) = neighbor.span(history, partition, row, len)?;
                len = count;
                spans.push(span);
            }
            let mut fill = None;
            let arrays = spans
                .into_iter()
                .enumerate()
                .map(|(i, span)| {
                    Ok(match span {
                        Some((array, offset)) => array.slice(offset, len),
                        None => match &self.inputs[i].default {
                            Some(value) => fill_offset_default(
                                value,
                                len,
                                fill.get_or_insert_with(|| memory.new_empty()),
                            )?,
                            None => datafusion::arrow::array::new_null_array(
                                self.schema.field(i).data_type(),
                                len,
                            ),
                        },
                    })
                })
                .collect::<Result<_>>()?;
            let inputs = RecordBatch::try_new_with_options(
                self.schema.clone(),
                arrays,
                &RecordBatchOptions::new().with_row_count(Some(len)),
            )?;
            self.apply(&inputs, &mut out[..len], bit)?;
            out = &mut out[len..];
            row += len;
        }
        Ok(())
    }

    #[inline]
    pub(super) fn apply(
        &self,
        inputs: &RecordBatch,
        out: &mut [u64],
        bit: u64,
    ) -> Result<()> {
        // Kernel temporaries stay within the existing bounded expression chunk;
        // the result is consumed here, while callers account retained arrays.
        let result = self.predicate.evaluate(inputs)?.into_array(out.len())?;
        let Some(booleans) = result.as_boolean_opt() else {
            return internal_err!(
                "offset expression evaluated to non-boolean type {}",
                result.data_type()
            );
        };
        for (mask, verdict) in out.iter_mut().zip(booleans) {
            if verdict == Some(true) {
                *mask |= bit;
            }
        }
        Ok(())
    }
}