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.

//! Shared helper utilities for navigation window UDF evaluators.
//!
//! These routines validate classifier-mask inputs and perform array extraction
//! used by PREV/NEXT/FIRST/LAST evaluators.

use datafusion::arrow::array::{Array, ArrayRef, BooleanArray, UInt64Array, make_array};
use datafusion::arrow::compute::take as arrow_take;
use datafusion_common::{Result, ScalarValue, arrow_datafusion_err, exec_datafusion_err};

use crate::execution::storage::{contains_run_end_encoded, retype_gather_data};

use crate::functions::navigation_common::nullable_navigation_data_type;
pub(super) use datafusion_hash_grouped_order::gather::contains_dictionary;

/// Materialize the declared navigation type regardless of this partition's NULLs.
pub(super) fn nullable_navigation_array(array: &ArrayRef) -> Result<ArrayRef> {
    if !contains_run_end_encoded(array.data_type()) {
        return Ok(std::sync::Arc::clone(array));
    }
    Ok(make_array(retype_gather_data(
        array.to_data(),
        &nullable_navigation_data_type(array.data_type()),
        false,
    )?))
}

pub(super) fn get_classifier_mask(values: &[ArrayRef]) -> Result<&BooleanArray> {
    // The classifier mask is the last argument when present.
    // The caller ensures it is only invoked when the mask exists.
    values
        .last()
        .and_then(|a| a.as_any().downcast_ref::<BooleanArray>())
        .ok_or_else(|| {
            exec_datafusion_err!("classifier mask column must be a BooleanArray")
        })
}

pub(super) fn gather_array_by_indices(
    data_arr: &ArrayRef,
    indices: Vec<Option<usize>>,
) -> Result<ArrayRef> {
    let idx_array = UInt64Array::from_iter(
        indices
            .into_iter()
            .map(|index| index.map(|value| value as u64)),
    );
    let data_arr = nullable_navigation_array(data_arr)?;
    arrow_take(data_arr.as_ref(), &idx_array, None).map_err(|e| arrow_datafusion_err!(e))
}

pub(super) fn gather_with_default(
    data_arr: &ArrayRef,
    indices: Vec<Option<usize>>,
    default_value: &ScalarValue,
) -> Result<ArrayRef> {
    // Handle an empty source and all-missing targets before invoking take.
    if indices.iter().all(Option::is_none) {
        return nullable_navigation_array(
            &default_value.to_array_of_size(indices.len())?,
        );
    }
    if default_value.is_null() || indices.iter().all(Option::is_some) {
        return gather_array_by_indices(data_arr, indices);
    }
    let mask_array =
        BooleanArray::from_iter(indices.iter().map(|idx| Some(idx.is_none())));
    // Missing targets are overwritten by zip. At least one real target exists,
    // so the source cannot be empty and row zero is a valid dummy.
    let indices = indices
        .into_iter()
        .map(|idx| Some(idx.unwrap_or(0)))
        .collect();
    let gathered = gather_array_by_indices(data_arr, indices)?;
    let default_arr =
        nullable_navigation_array(&default_value.to_array_of_size(gathered.len())?)?;
    datafusion::arrow::compute::kernels::zip::zip(&mask_array, &default_arr, &gathered)
        .map_err(|e| arrow_datafusion_err!(e))
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use datafusion::arrow::array::{Array, ArrayRef, StructArray};
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion::arrow::record_batch::RecordBatch;
    use datafusion_common::ScalarValue;

    use super::{contains_dictionary, gather_array_by_indices, gather_with_default};
    use crate::functions::navigation_common::{
        NavigationKind, navigation_return_field, resolve_navigation_default,
        test_support::{assert_run_values, custom_run_array},
    };

    #[test]
    fn navigation_results_match_declared_run_field() -> datafusion_common::Result<()> {
        let data = custom_run_array(false);
        let input = Arc::new(Field::new("input", data.data_type().clone(), false));
        let field = navigation_return_field(NavigationKind::First, &[input], "result");
        let schema = Arc::new(Schema::new(vec![field]));
        let default =
            resolve_navigation_default(&ScalarValue::Null, schema.field(0).data_type())?;
        let mut partitions = Vec::new();
        for indices in [vec![None, Some(0)], vec![Some(1), Some(0)]] {
            for result in [
                gather_array_by_indices(&data, indices.clone())?,
                gather_with_default(&data, indices, &default)?,
            ] {
                assert_eq!(result.data_type(), custom_run_array(true).data_type());
                RecordBatch::try_new(Arc::clone(&schema), vec![Arc::clone(&result)])?;
                partitions.push(result);
            }
        }
        let arrays: Vec<_> = partitions.iter().map(|array| array.as_ref()).collect();
        let combined = datafusion::arrow::compute::concat(&arrays)?;
        RecordBatch::try_new(schema, vec![combined])?;
        Ok(())
    }

    #[test]
    fn required_run_values_allow_missing_targets_and_defaults() {
        let data = custom_run_array(false);
        for indices in [vec![None, Some(0)], vec![None, None]] {
            let result = gather_array_by_indices(&data, indices.clone()).unwrap();
            assert_eq!(result.data_type(), custom_run_array(true).data_type());
            let expected: Vec<_> =
                indices.iter().map(|index| index.map(|_| 10)).collect();
            assert_run_values(&result, &expected);

            for default in [Some(7), None] {
                let scalar = resolve_navigation_default(
                    &ScalarValue::Int32(default),
                    data.data_type(),
                )
                .unwrap();
                let result =
                    gather_with_default(&data, indices.clone(), &scalar).unwrap();
                let expected: Vec<_> = indices
                    .iter()
                    .map(|index| index.map_or(default, |_| Some(10)))
                    .collect();
                assert_run_values(&result, &expected);
                assert_eq!(result.data_type(), custom_run_array(true).data_type());
            }
        }
        // An all-default result must not attempt to read dummy index zero.
        for default in [Some(7), None] {
            let scalar = resolve_navigation_default(
                &ScalarValue::Int32(default),
                data.data_type(),
            )
            .unwrap();
            let result =
                gather_with_default(&data.slice(0, 0), vec![None; 2], &scalar).unwrap();
            assert_run_values(&result, &[default; 2]);
        }
    }

    #[test]
    fn nested_required_run_values_allow_missing_targets() {
        let encoded = custom_run_array(false);
        let data: ArrayRef = Arc::new(StructArray::new(
            vec![Arc::new(Field::new(
                "nested",
                encoded.data_type().clone(),
                true,
            ))]
            .into(),
            vec![encoded],
            None,
        ));
        let result = gather_array_by_indices(&data, vec![None, Some(0)]).unwrap();
        let result = result.as_any().downcast_ref::<StructArray>().unwrap();
        assert!(result.is_null(0));
        assert_run_values(result.column(0), &[None, Some(10)]);
        assert_eq!(
            result.column(0).data_type(),
            custom_run_array(true).data_type()
        );
    }

    #[test]
    fn non_null_container_default_can_have_a_null_run_child() {
        let encoded = custom_run_array(false);
        let data: ArrayRef = Arc::new(StructArray::new(
            vec![Arc::new(Field::new(
                "nested",
                encoded.data_type().clone(),
                true,
            ))]
            .into(),
            vec![encoded],
            None,
        ));
        let null_child = resolve_navigation_default(
            &ScalarValue::Null,
            custom_run_array(true).data_type(),
        )
        .unwrap()
        .to_array()
        .unwrap();
        let default = StructArray::new(
            vec![Arc::new(Field::new(
                "nested",
                null_child.data_type().clone(),
                true,
            ))]
            .into(),
            vec![null_child],
            None,
        );
        let default = resolve_navigation_default(
            &ScalarValue::try_from_array(&default, 0).unwrap(),
            data.data_type(),
        )
        .unwrap();
        assert!(!default.is_null());
        let result = gather_with_default(&data, vec![None, Some(0)], &default).unwrap();
        let result = result.as_any().downcast_ref::<StructArray>().unwrap();
        assert!(result.is_valid(0));
        assert_run_values(result.column(0), &[None, Some(10)]);
        assert_eq!(
            result.column(0).data_type(),
            custom_run_array(true).data_type()
        );
    }

    #[test]
    fn dictionary_detection_includes_nested_types() {
        let dictionary =
            DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8));
        let field = Arc::new(Field::new("nested", dictionary.clone(), true));
        for data_type in [
            dictionary,
            DataType::List(Arc::clone(&field)),
            DataType::Struct(vec![Arc::clone(&field)].into()),
            DataType::RunEndEncoded(
                Arc::new(Field::new("ends", DataType::Int32, false)),
                field,
            ),
        ] {
            assert!(contains_dictionary(&data_type));
        }
        assert!(!contains_dictionary(custom_run_array(false).data_type()));
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn gather_keeps_indices_above_u32_max() {
        use datafusion::arrow::array::{Int32Array, Int64Array, RunArray};
        use datafusion::arrow::datatypes::Int64Type;

        // Run-end encoding gives a wide logical index with two physical values.
        let first_run_end = i64::from(u32::MAX) + 1;
        let run_ends = Int64Array::from(vec![first_run_end, first_run_end + 1]);
        let values = Int32Array::from(vec![10, 20]);
        let encoded = RunArray::<Int64Type>::try_new(&run_ends, &values).unwrap();
        let data: ArrayRef = Arc::new(encoded);
        let index = u32::MAX as usize + 1;
        assert!(index < data.len());

        let gathered = gather_array_by_indices(&data, vec![Some(index)]).unwrap();
        let gathered = gathered
            .as_any()
            .downcast_ref::<RunArray<Int64Type>>()
            .unwrap();
        assert_eq!(gathered.len(), 1);
        let values = gathered
            .values()
            .as_any()
            .downcast_ref::<Int32Array>()
            .unwrap();
        assert_eq!(values.value(0), 20);
    }
}