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.

use std::ops::Range;
use std::sync::Arc;

use datafusion::arrow::array::{Array, ArrayRef};
use datafusion::arrow::datatypes::DataType;
use datafusion::common::{Result, ScalarValue};
use datafusion::logical_expr::PartitionEvaluator;

use crate::functions::navigation_common::NavigationKind;

use super::helpers::{
    contains_dictionary, gather_array_by_indices, get_classifier_mask,
    nullable_navigation_array,
};
use super::mask_cache::{map_nth_last_matches, nth_first_match_index};

#[derive(Debug)]
pub(crate) struct MatchRecognizeEdgeEvaluator {
    pub(super) mask_provided: bool,
    pub(super) offset: usize,
    pub(super) kind: NavigationKind,
    bounded_execution: bool,
    /// Cached partition FIRST result, including a selected NULL. Finalizing
    /// during evaluation keeps it stable when bounded execution prunes input,
    /// including when later buffers start after the selected row.
    pub(super) finalized_result: Option<ScalarValue>,
}

impl MatchRecognizeEdgeEvaluator {
    pub(crate) fn new(
        mask_provided: bool,
        offset: usize,
        kind: NavigationKind,
        value_type: &DataType,
    ) -> Self {
        debug_assert!(kind.is_edge());
        Self {
            mask_provided,
            offset,
            kind,
            bounded_execution: !contains_dictionary(value_type),
            finalized_result: None,
        }
    }
}

impl PartitionEvaluator for MatchRecognizeEdgeEvaluator {
    fn evaluate_all(&mut self, values: &[ArrayRef], num_rows: usize) -> Result<ArrayRef> {
        let data_arr = values.first().ok_or_else(|| {
            datafusion::common::exec_datafusion_err!(
                "navigation window requires a value array"
            )
        })?;
        let data_arr = &nullable_navigation_array(data_arr)?;

        if !self.mask_provided {
            debug_assert_eq!(self.offset, 0);
            return match self.kind {
                NavigationKind::First => {
                    let first_val = if !data_arr.is_empty() {
                        ScalarValue::try_from_array(data_arr.as_ref(), 0)?
                    } else {
                        ScalarValue::try_from(data_arr.data_type())?
                    };
                    first_val.to_array_of_size(num_rows)
                }
                NavigationKind::Last => Ok(Arc::clone(data_arr)),
                NavigationKind::Prev | NavigationKind::Next => unreachable!(),
            };
        }

        let mask_arr = get_classifier_mask(values)?;

        let gather_indices: Vec<Option<usize>> = match self.kind {
            NavigationKind::First => {
                let nth_seen_idx = nth_first_match_index(mask_arr, self.offset);
                (0..num_rows)
                    .map(|idx| nth_seen_idx.filter(|&target_idx| idx >= target_idx))
                    .collect()
            }
            NavigationKind::Last => {
                map_nth_last_matches(mask_arr, num_rows, self.offset, |anchor| anchor)?
            }
            NavigationKind::Prev | NavigationKind::Next => unreachable!(),
        };

        gather_array_by_indices(data_arr, gather_indices)
    }

    fn evaluate(
        &mut self,
        values: &[ArrayRef],
        range: &Range<usize>,
    ) -> Result<ScalarValue> {
        if self.mask_provided {
            return datafusion::common::internal_err!(
                "masked navigation requires whole-partition evaluate_all"
            );
        }
        let data_arr = values.first().ok_or_else(|| {
            datafusion::common::exec_datafusion_err!(
                "navigation window requires a value array"
            )
        })?;
        let data_arr = &nullable_navigation_array(data_arr)?;
        // DataFusion ranges are relative to the retained input buffer.
        let idx = range.start;
        if idx >= data_arr.len() {
            return ScalarValue::try_from(data_arr.data_type());
        }
        if let Some(ref result) = self.finalized_result {
            return Ok(result.clone());
        }

        debug_assert_eq!(self.offset, 0);
        match self.kind {
            NavigationKind::First => {
                let result = ScalarValue::try_from_array(data_arr.as_ref(), 0)?;
                // NULL is a final value once a real unmasked row exists.
                self.finalized_result = Some(result.clone());
                Ok(result)
            }
            NavigationKind::Last => ScalarValue::try_from_array(data_arr.as_ref(), idx),
            NavigationKind::Prev | NavigationKind::Next => unreachable!(),
        }
    }

    fn supports_bounded_execution(&self) -> bool {
        // When a classifier mask or positive logical offset is present, we need
        // the entire partition to track matched positions across rows.
        // Dictionary scalars must use array evaluation to avoid key overflow.
        !self.mask_provided && self.offset == 0 && self.bounded_execution
    }

    fn is_causal(&self) -> bool {
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use datafusion::arrow::array::{BooleanArray, Int32Array};

    #[test]
    fn masked_edges_gather_missing_required_run_values() -> Result<()> {
        use crate::functions::navigation_common::test_support::{
            assert_run_values, custom_run_array,
        };

        for kind in [NavigationKind::First, NavigationKind::Last] {
            for (mask, offset, expected) in [
                (
                    vec![true, true],
                    0,
                    vec![
                        Some(10),
                        Some(if kind == NavigationKind::First {
                            10
                        } else {
                            20
                        }),
                    ],
                ),
                (vec![false, true], 0, vec![None, Some(20)]),
                (vec![false, false], 0, vec![None, None]),
                (vec![false, true], 1, vec![None, None]),
            ] {
                let values =
                    vec![custom_run_array(false), Arc::new(BooleanArray::from(mask))];
                let mut evaluator = MatchRecognizeEdgeEvaluator::new(
                    true,
                    offset,
                    kind,
                    values[0].data_type(),
                );
                assert!(!evaluator.supports_bounded_execution());
                let result = evaluator.evaluate_all(&values, 2)?;
                assert_run_values(&result, &expected);
                assert_eq!(result.data_type(), custom_run_array(true).data_type());
                assert!(evaluator.evaluate(&values, &(0..1)).is_err());
            }
        }
        Ok(())
    }

    #[test]
    fn dictionary_edges_use_whole_partition_evaluation() -> Result<()> {
        use datafusion::arrow::array::{DictionaryArray, Int8Array, StringArray};
        use datafusion::arrow::datatypes::Int8Type;

        let data: ArrayRef = Arc::new(DictionaryArray::<Int8Type>::try_new(
            Int8Array::from(vec![0; 129]),
            Arc::new(StringArray::from(vec!["same"])),
        )?);
        for kind in [NavigationKind::First, NavigationKind::Last] {
            let mut evaluator =
                MatchRecognizeEdgeEvaluator::new(false, 0, kind, data.data_type());
            assert!(!evaluator.supports_bounded_execution());
            let result = evaluator.evaluate_all(&[Arc::clone(&data)], 129)?;
            assert_eq!(result.data_type(), data.data_type());
            assert_eq!(result.len(), 129);
            for row in 0..129 {
                assert_eq!(
                    ScalarValue::try_from_array(&result, row)?,
                    ScalarValue::try_from_array(&data, 0)?
                );
            }
        }
        Ok(())
    }

    #[test]
    fn masked_first_keeps_pre_anchor_null_provisional() -> Result<()> {
        for selected in [Some(20), None] {
            let mut evaluator = MatchRecognizeEdgeEvaluator::new(
                true,
                0,
                NavigationKind::First,
                &DataType::Int32,
            );
            let values: Vec<ArrayRef> = vec![
                Arc::new(Int32Array::from(vec![Some(10), selected, Some(30)])),
                Arc::new(BooleanArray::from(vec![false, true, true])),
            ];
            // Selecting a real value replaces a missing anchor; selecting NULL
            // keeps NULL even after a later non-null row.
            let result = evaluator.evaluate_all(&values, 3)?;
            assert_eq!(
                result.as_any().downcast_ref::<Int32Array>().unwrap(),
                &Int32Array::from(vec![None, selected, selected])
            );
        }
        Ok(())
    }

    #[test]
    fn masked_edge_evaluate_all_tracks_running_anchors() -> Result<()> {
        let values: Vec<ArrayRef> = vec![
            Arc::new(Int32Array::from(vec![Some(10), Some(20), Some(30)])),
            Arc::new(BooleanArray::from(vec![false, true, false])),
        ];
        let mut first = MatchRecognizeEdgeEvaluator::new(
            true,
            0,
            NavigationKind::First,
            &DataType::Int32,
        );
        let first_out = first.evaluate_all(&values, 3)?;
        assert_eq!(
            first_out.as_any().downcast_ref::<Int32Array>().unwrap(),
            &Int32Array::from(vec![None, Some(20), Some(20)])
        );

        let mut last = MatchRecognizeEdgeEvaluator::new(
            true,
            0,
            NavigationKind::Last,
            &DataType::Int32,
        );
        let last_out = last.evaluate_all(&values, 3)?;
        assert_eq!(
            last_out.as_any().downcast_ref::<Int32Array>().unwrap(),
            &Int32Array::from(vec![None, Some(20), Some(20)])
        );
        Ok(())
    }

    #[test]
    fn masked_edge_with_logical_offset_resolves_running_positions() -> Result<()> {
        // Matched indices: 0 (10), 2 (30), 3 (40)
        let values: Vec<ArrayRef> = vec![
            Arc::new(Int32Array::from(vec![10, 20, 30, 40])),
            Arc::new(BooleanArray::from(vec![true, false, true, true])),
        ];
        let mut first_1 = MatchRecognizeEdgeEvaluator::new(
            true,
            1,
            NavigationKind::First,
            &DataType::Int32,
        );
        assert!(!first_1.supports_bounded_execution());
        assert_eq!(
            first_1
                .evaluate_all(&values, 4)?
                .as_any()
                .downcast_ref::<Int32Array>()
                .unwrap(),
            &Int32Array::from(vec![None, None, Some(30), Some(30)])
        );

        let mut last_1 = MatchRecognizeEdgeEvaluator::new(
            true,
            1,
            NavigationKind::Last,
            &DataType::Int32,
        );
        assert!(!last_1.supports_bounded_execution());
        assert_eq!(
            last_1
                .evaluate_all(&values, 4)?
                .as_any()
                .downcast_ref::<Int32Array>()
                .unwrap(),
            &Int32Array::from(vec![None, None, Some(10), Some(30)])
        );

        // Huge logical offset must return all-NULL without OOM.
        let mut huge_last = MatchRecognizeEdgeEvaluator::new(
            true,
            usize::MAX / 2,
            NavigationKind::Last,
            &DataType::Int32,
        );
        assert_eq!(
            huge_last
                .evaluate_all(&values, 4)?
                .as_any()
                .downcast_ref::<Int32Array>()
                .unwrap(),
            &Int32Array::from(vec![None; 4])
        );
        Ok(())
    }
}