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 super::{ManagedAccumulatorEvaluator, ManagedAggregator};
use crate::core::{AggregateId, SymbolId};
use crate::execution::matching::row_loop::provider::ValueProvider;
use crate::planning::AccumulatorInputMode;
use datafusion::arrow::array::{ArrayRef, Int64Array};
use datafusion::arrow::datatypes::DataType;
use datafusion::common::{DataFusionError, Result};
use datafusion::logical_expr::{
    Accumulator, AccumulatorFactoryFunction, Volatility, create_udaf,
};
use datafusion::physical_expr::aggregate::{AggregateExprBuilder, AggregateFunctionExpr};
use datafusion::physical_plan::expressions::Literal;
use datafusion::scalar::ScalarValue;
use std::mem::size_of_val;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

#[derive(Debug, Default)]
struct ProbeAccumulator(i64);

impl Accumulator for ProbeAccumulator {
    fn update_batch(&mut self, _values: &[ArrayRef]) -> Result<()> {
        self.0 += 1;
        Ok(())
    }

    fn evaluate(&mut self) -> Result<ScalarValue> {
        Ok(ScalarValue::Int64(Some(self.0)))
    }

    fn size(&self) -> usize {
        size_of_val(self)
    }

    fn state(&mut self) -> Result<Vec<ScalarValue>> {
        Ok(vec![ScalarValue::Int64(Some(self.0))])
    }

    fn merge_batch(&mut self, _states: &[ArrayRef]) -> Result<()> {
        Ok(())
    }
}

pub(crate) fn factory(calls: Arc<AtomicUsize>, fail: bool) -> Arc<AggregateFunctionExpr> {
    let accumulator: AccumulatorFactoryFunction = Arc::new(move |_| {
        calls.fetch_add(1, Ordering::SeqCst);
        if fail {
            return Err(DataFusionError::Execution("factory failure".into()));
        }
        Ok(Box::<ProbeAccumulator>::default() as Box<dyn Accumulator>)
    });
    let aggregate = create_udaf(
        "probe",
        vec![DataType::Int64],
        Arc::new(DataType::Int64),
        Volatility::Immutable,
        accumulator,
        Arc::new(vec![DataType::Int64]),
    );
    Arc::new(
        AggregateExprBuilder::new(
            Arc::new(aggregate),
            vec![Arc::new(Literal::new(ScalarValue::Int64(Some(1))))],
        )
        .alias("probe")
        .build()
        .unwrap(),
    )
}

fn arguments() -> Vec<Vec<ArrayRef>> {
    let value = Arc::new(Int64Array::from(vec![1])) as ArrayRef;
    vec![vec![Arc::clone(&value)], vec![value]]
}

#[test]
fn lazy_slots_construct_for_default_evaluation_and_reuse() {
    let a = SymbolId::try_new(1, 3).unwrap();
    let b = SymbolId::try_new(2, 3).unwrap();
    let evaluator = ManagedAccumulatorEvaluator {
        aggregators: [Some(a), Some(b), None]
            .into_iter()
            .enumerate()
            .map(|(index, symbol_id)| ManagedAggregator {
                aggregate_id: AggregateId::try_new(index, 3).unwrap(),
                symbol_id,
                update_mode: AccumulatorInputMode::Batch,
                output_type: DataType::Int64,
            })
            .collect(),
    };
    let mut arguments = arguments();
    arguments.push(arguments[0].clone());
    let mut provider = ValueProvider::Prepared(&arguments);
    let constructions = Arc::new(AtomicUsize::new(0));
    let factories = [
        factory(Arc::clone(&constructions), false),
        factory(Arc::clone(&constructions), false),
        factory(Arc::clone(&constructions), false),
    ];
    let mut slots = vec![None, None, None];
    let mut results = Vec::new();
    let mut primitive = Vec::new();

    evaluator
        .update_aggregates(
            &mut provider,
            &mut slots,
            &factories,
            a,
            &mut results,
            &mut primitive,
            &mut |_| Ok(()),
        )
        .unwrap();
    assert_eq!(constructions.load(Ordering::SeqCst), 3);
    assert_eq!(
        results,
        [
            ScalarValue::Int64(Some(1)),
            ScalarValue::Int64(Some(0)),
            ScalarValue::Int64(Some(1))
        ]
    );

    evaluator
        .update_aggregates(
            &mut provider,
            &mut slots,
            &factories,
            a,
            &mut results,
            &mut primitive,
            &mut |_| Ok(()),
        )
        .unwrap();
    assert_eq!(constructions.load(Ordering::SeqCst), 3);
    assert_eq!(
        results,
        [
            ScalarValue::Int64(Some(2)),
            ScalarValue::Int64(Some(0)),
            ScalarValue::Int64(Some(2))
        ]
    );
}

#[test]
fn failed_lazy_factory_leaves_slot_empty_for_retry() {
    let symbol = SymbolId::try_new(1, 2).unwrap();
    let evaluator = ManagedAccumulatorEvaluator {
        aggregators: vec![ManagedAggregator {
            aggregate_id: AggregateId::try_new(0, 1).unwrap(),
            symbol_id: Some(symbol),
            update_mode: AccumulatorInputMode::Batch,
            output_type: DataType::Int64,
        }]
        .into(),
    };
    let arguments = arguments();
    let mut provider = ValueProvider::Prepared(&arguments[..1]);
    let constructions = Arc::new(AtomicUsize::new(0));
    let factories = [factory(Arc::clone(&constructions), true)];
    let mut slots = vec![None];

    for _ in 0..2 {
        let error = evaluator
            .update_aggregates(
                &mut provider,
                &mut slots,
                &factories,
                symbol,
                &mut Vec::new(),
                &mut Vec::new(),
                &mut |_| Ok(()),
            )
            .expect_err("factory failure must propagate");
        assert!(error.to_string().contains("factory failure"));
        assert!(slots[0].is_none());
    }
    assert_eq!(constructions.load(Ordering::SeqCst), 2);
}