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.

use super::*;
use crate::core::MatchSummaryField;
use datafusion::arrow::array::{Decimal128Array, Int32Array, Int64Array};
use datafusion::arrow::datatypes::Field;
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryConsumer, MemoryPool};

fn binding(op: Op, input: DataType, output: DataType) -> ExecutableDirectCountSummary {
    ExecutableDirectCountSummary::new_reduction(
        MatchSummaryField::new(
            0,
            Arc::new(Field::new("v", output.clone(), op != Op::Count)),
        ),
        None,
        ExecutableReduction {
            op,
            input_type: input,
            output_type: output,
            input_column: 0,
            managed_aggregate: None,
        },
    )
}

fn run(op: Op, source: ArrayRef, ty: DataType, chunks: &[usize]) -> Result<ScalarValue> {
    let summary = binding(op, source.data_type().clone(), ty.clone());
    let spec = summary.reduction().unwrap();
    let memory = crate::execution::common::memory::new_unbounded_state_memory();
    let mut column = ReductionColumn::new(spec, &memory)?;
    let mut first = 0;
    for &n in chunks {
        column.update(&summary, &source, first, n, &memory)?;
        first += n;
    }
    assert_eq!(source.len(), first);
    column.reserve(spec)?;
    Ok(match (&column.result, ty) {
        (PrimitiveResult::Int32(c), _) => ScalarValue::Int32(c.carry),
        (PrimitiveResult::Int64(c), _) => ScalarValue::Int64(c.carry),
        (PrimitiveResult::Float64(c), _) => ScalarValue::Float64(c.carry),
        (PrimitiveResult::Decimal128(c), DataType::Decimal128(p, s)) => {
            ScalarValue::Decimal128(c.carry, p, s)
        }
        _ => unreachable!(),
    })
}

#[test]
fn selected_reduction_wraps_and_preserves_typed_empty_values() -> Result<()> {
    let a: ArrayRef = Arc::new(Int64Array::from(vec![Some(i64::MAX), None, Some(1)]));
    assert_eq!(
        run(Op::Sum, a.clone(), DataType::Int64, &[1, 2])?,
        ScalarValue::Int64(Some(i64::MIN))
    );
    let i32s: ArrayRef = Arc::new(Int32Array::from(vec![i32::MAX, i32::MAX]));
    assert_eq!(
        run(Op::Sum, i32s, DataType::Int64, &[2])?,
        ScalarValue::Int64(Some(2 * i64::from(i32::MAX)))
    );
    let v = 10_i128.pow(38) - 1;
    let decimals: ArrayRef =
        Arc::new(Decimal128Array::from(vec![v, v]).with_precision_and_scale(38, -2)?);
    assert_eq!(
        run(Op::Sum, decimals, DataType::Decimal128(38, -2), &[2])?,
        ScalarValue::Decimal128(Some(v.wrapping_add(v)), 38, -2)
    );
    let none = a.slice(1, 1);
    assert_eq!(
        run(Op::Count, none.clone(), DataType::Int64, &[1])?,
        ScalarValue::Int64(Some(0))
    );
    assert_eq!(
        run(Op::Min, none.clone(), DataType::Int64, &[1])?,
        ScalarValue::Int64(None)
    );
    assert_eq!(
        run(Op::Avg, none, DataType::Float64, &[1])?,
        ScalarValue::Float64(None)
    );
    let source: ArrayRef = Arc::new(
        Decimal128Array::from(vec![Some(1011), None, Some(1012)])
            .with_precision_and_scale(10, 2)?,
    );
    assert_eq!(
        run(Op::Avg, source, DataType::Decimal128(14, 6), &[2, 1])?,
        ScalarValue::Decimal128(Some(10115000), 14, 6)
    );
    Ok(())
}

#[test]
fn selected_float_reduction_matches_grouped_raw_bits_across_spans() -> Result<()> {
    use datafusion::functions_aggregate::{
        average::avg_udaf,
        min_max::{max_udaf, min_udaf},
        sum::sum_udaf,
    };
    let p = f64::from_bits(0x7ff8_0000_0000_0123);
    let n = f64::from_bits(0xfff8_0000_0000_0333);
    for values in [
        vec![Some(1.0e16), Some(1.), Some(-1.0e16), Some(1.)],
        vec![Some(-0.), None, Some(0.), Some(-0.)],
        vec![
            Some(f64::INFINITY),
            Some(f64::NEG_INFINITY),
            Some(p),
            Some(n),
        ],
        vec![
            Some(n),
            None,
            Some(p),
            Some(f64::from_bits(0x7ff0_0000_0000_0007)),
        ],
    ] {
        let src: ArrayRef = Arc::new(Float64Array::from(values));
        let field = Arc::new(Field::new("v", DataType::Float64, true));
        for (op, udf) in [
            (Op::Sum, sum_udaf()),
            (Op::Avg, avg_udaf()),
            (Op::Min, min_udaf()),
            (Op::Max, max_udaf()),
        ] {
            let mut acc = udf.create_groups_accumulator(AccumulatorArgs {
                return_field: Arc::clone(&field),
                schema: &Schema::empty(),
                ignore_nulls: false,
                order_bys: &[],
                is_reversed: false,
                name: "test",
                is_distinct: false,
                exprs: &[],
                expr_fields: std::slice::from_ref(&field),
            })?;
            acc.update_batch(std::slice::from_ref(&src), &[0; 4], None, 1)?;
            let expected = acc
                .evaluate(EmitTo::All)?
                .as_primitive::<Float64Type>()
                .value(0);
            let ScalarValue::Float64(Some(got)) =
                run(op, src.clone(), DataType::Float64, &[1, 2, 1])?
            else {
                panic!("missing Float64 result");
            };
            assert_eq!(got.to_bits(), expected.to_bits(), "{op:?}");
        }
    }
    Ok(())
}

#[test]
fn selected_reduction_denial_preserves_retry_and_register_output() -> Result<()> {
    let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(4096));
    let memory = MemoryConsumer::new("summaries").register(&pool);
    let summary = binding(Op::Avg, DataType::Float64, DataType::Float64);
    let spec = summary.reduction().unwrap();
    let mut column = ReductionColumn::new(spec, &memory)?;
    let block = memory.new_empty();
    block.try_grow(4096)?;
    let src: ArrayRef = Arc::new(Float64Array::from(vec![
        1.0,
        f64::from_bits(0x7ff8_0000_0000_0012),
        f64::from_bits(0xfff8_0000_0000_0067),
    ]));
    assert!(column.update(&summary, &src, 0, 3, &memory).is_err());
    assert_eq!(column.non_null, 0);
    drop(block);
    let finite: ArrayRef = Arc::new(Float64Array::from(vec![8.0, 4.0]));
    column.update(&summary, &finite, 0, 2, &memory)?;
    let block = memory.new_empty();
    block.try_grow(4096)?;
    assert!(column.reserve(spec).is_err());
    drop(block);
    column.reserve(spec)?;
    let PrimitiveResult::Float64(c) = &column.result else {
        unreachable!()
    };
    assert_eq!(c.carry, Some(6.0));
    column.append_reserved(Op::Avg);
    column.set(spec, WinningValue::Float64(Some(-0.0)))?;
    assert!(column.set(spec, WinningValue::Int64(Some(3))).is_err());
    column.reserve(spec)?;
    let PrimitiveResult::Float64(c) = &column.result else {
        unreachable!()
    };
    assert_eq!(c.carry.unwrap().to_bits(), (-0.0_f64).to_bits());
    column.append_reserved(Op::Avg);
    column.reserve(spec)?;
    let PrimitiveResult::Float64(c) = &column.result else {
        unreachable!()
    };
    assert!(c.carry.is_none());
    drop(column);
    assert_eq!(pool.reserved(), 0);
    Ok(())
}

#[test]
fn selected_float_single_nan_or_infinity_needs_no_group_scratch() -> Result<()> {
    let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1));
    let memory = MemoryConsumer::new("float carry").register(&pool);
    for first in [
        f64::INFINITY,
        f64::NEG_INFINITY,
        f64::from_bits(0xfff0_0000_0000_0012),
    ] {
        let values: ArrayRef = Arc::new(Float64Array::from_iter_values(
            std::iter::once(first).chain(std::iter::repeat_n(1.0, 1024)),
        ));
        let field = Arc::new(Field::new("v", DataType::Float64, true));
        let udf = datafusion::functions_aggregate::sum::sum_udaf();
        let mut reference = udf.create_groups_accumulator(AccumulatorArgs {
            return_field: field.clone(),
            schema: &Schema::empty(),
            ignore_nulls: false,
            order_bys: &[],
            is_reversed: false,
            name: "reference",
            is_distinct: false,
            exprs: &[],
            expr_fields: std::slice::from_ref(&field),
        })?;
        reference.update_batch(
            std::slice::from_ref(&values),
            &vec![0; values.len()],
            None,
            1,
        )?;
        let expected = reference
            .evaluate(EmitTo::All)?
            .as_primitive::<Float64Type>()
            .value(0);
        let summary = binding(Op::Sum, DataType::Float64, DataType::Float64);
        let spec = summary.reduction().unwrap();
        let mut column = ReductionColumn::new(spec, &memory)?;
        for start in (0..values.len()).step_by(COARSE_WORK_BATCH_SIZE) {
            column.update(
                &summary,
                &values,
                start,
                (values.len() - start).min(COARSE_WORK_BATCH_SIZE),
                &memory,
            )?;
        }
        let PrimitiveResult::Float64(value) = &column.result else {
            unreachable!()
        };
        assert_eq!(value.carry.unwrap().to_bits(), expected.to_bits());
        assert_eq!(pool.reserved(), 0);
    }
    Ok(())
}

#[test]
fn selected_widened_float64_and_int64_reductions_match_arrow_cast() -> Result<()> {
    use datafusion::arrow::array::Float32Array;
    use datafusion::arrow::compute::cast;

    let sources: Vec<ArrayRef> = vec![
        Arc::new(
            Decimal128Array::from(vec![Some(1250), None, Some(-375), Some(10000)])
                .with_precision_and_scale(15, 2)?,
        ),
        Arc::new(
            Decimal128Array::from(vec![Some(12), None, Some(-5), Some(3)])
                .with_precision_and_scale(10, -2)?,
        ),
        Arc::new(Float32Array::from(vec![
            Some(-0.0_f32),
            None,
            Some(1.5),
            Some(-2.25),
        ])),
        Arc::new(Int32Array::from(vec![Some(10), None, Some(-4), Some(20)])),
        Arc::new(Int64Array::from(vec![Some(100), None, Some(-50), Some(25)])),
    ];
    for source in sources {
        let casted = cast(&source, &DataType::Float64)?;
        for op in [Op::Avg, Op::Sum, Op::Min, Op::Max] {
            let expected = run(op, Arc::clone(&casted), DataType::Float64, &[2, 2])?;
            let actual = run(op, Arc::clone(&source), DataType::Float64, &[1, 3])?;
            assert_eq!(actual, expected, "{op:?} on {:?}", source.data_type());
        }
        assert_eq!(
            run(Op::Count, Arc::clone(&source), DataType::Int64, &[2, 2])?,
            ScalarValue::Int64(Some(3))
        );
    }
    // Int32 widened to Int64 for MIN/MAX.
    let i32s: ArrayRef = Arc::new(Int32Array::from(vec![Some(-7), None, Some(42)]));
    assert_eq!(
        run(Op::Min, Arc::clone(&i32s), DataType::Int64, &[1, 2])?,
        ScalarValue::Int64(Some(-7))
    );
    assert_eq!(
        run(Op::Max, i32s, DataType::Int64, &[2, 1])?,
        ScalarValue::Int64(Some(42))
    );
    Ok(())
}