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.

//! Exact online Welford state for VAR and STDDEV.
//!
//! Preserve DataFusion's update association order so NaN payloads, signed zero,
//! and rounding match its built-in accumulators. SQL NULL inputs are skipped
//! before the update kernel runs. Bivariate statistics and regression retain
//! their upstream DataFusion Accumulator implementations.

use crate::core::vm::{StatisticalPopulation, VarianceProjection};

/// Online `(mean, M2, count)` state used by VAR and STDDEV.
///
/// The field order is also the intended packed register order.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
#[repr(C)]
pub(super) struct VarianceState {
    pub(super) mean: f64,
    pub(super) m2: f64,
    pub(super) count: u64,
}

impl VarianceState {
    #[inline(always)]
    pub(super) fn from_registers(registers: &[u64], slot: usize) -> Self {
        Self {
            mean: f64::from_bits(registers[slot]),
            m2: f64::from_bits(registers[slot + 1]),
            count: registers[slot + 2],
        }
    }

    /// Applies one non-NULL input using DataFusion's Welford update order.
    #[inline(always)]
    pub(super) fn update(&mut self, value: f64) {
        let new_count = self.count + 1;
        let delta1 = value - self.mean;
        let new_mean = delta1 / new_count as f64 + self.mean;
        let delta2 = value - new_mean;
        let new_m2 = self.m2 + delta1 * delta2;

        self.count = new_count;
        self.mean = new_mean;
        self.m2 = new_m2;
    }

    #[inline]
    pub(super) fn project(self, projection: VarianceProjection) -> Option<f64> {
        let (population, stddev) = match projection {
            VarianceProjection::Variance(population) => (population, false),
            VarianceProjection::Stddev(population) => (population, true),
        };
        let value = self.variance(population);
        if stddev { value.map(f64::sqrt) } else { value }
    }

    #[inline]
    fn variance(self, population: StatisticalPopulation) -> Option<f64> {
        let divisor = match population {
            StatisticalPopulation::Population => self.count,
            StatisticalPopulation::Sample if self.count > 0 => self.count - 1,
            StatisticalPopulation::Sample => self.count,
        };

        match self.count {
            0 => None,
            1 if population == StatisticalPopulation::Population => Some(0.0),
            1 => None,
            _ => Some(self.m2 / divisor as f64),
        }
    }
}

#[cfg(test)]
pub(crate) fn datafusion_statistical_accumulator(
    udaf: &datafusion::logical_expr::AggregateUDF,
) -> Box<dyn datafusion::physical_plan::Accumulator> {
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion::logical_expr::function::AccumulatorArgs;
    use datafusion::physical_expr::expressions::col;
    use std::sync::Arc;

    let field = Arc::new(Field::new("value", DataType::Float64, true));
    let schema = Schema::new(vec![Arc::clone(&field)]);
    let expr = col("value", &schema).unwrap();
    let exprs = [expr];
    let expr_fields = [Arc::clone(&field)];
    udaf.accumulator(AccumulatorArgs {
        return_field: field,
        schema: &schema,
        ignore_nulls: false,
        order_bys: &[],
        is_reversed: false,
        name: udaf.name(),
        is_distinct: false,
        exprs: &exprs,
        expr_fields: &expr_fields,
    })
    .unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;
    use datafusion::arrow::array::{ArrayRef, Float64Array};
    use datafusion::common::ScalarValue;
    use datafusion::functions_aggregate::stddev::{stddev_pop_udaf, stddev_udaf};
    use datafusion::functions_aggregate::variance::{var_pop_udaf, var_samp_udaf};
    use std::sync::Arc;

    fn unary_array(value: Option<f64>) -> ArrayRef {
        Arc::new(Float64Array::from(vec![value]))
    }

    fn scalar_float(value: ScalarValue) -> Option<f64> {
        match value {
            ScalarValue::Float64(value) => value,
            other => panic!("expected Float64, got {other:?}"),
        }
    }

    fn scalar_u64(value: ScalarValue) -> Option<u64> {
        match value {
            ScalarValue::UInt64(value) => value,
            other => panic!("expected UInt64, got {other:?}"),
        }
    }

    fn assert_float_bits_eq(actual: Option<f64>, expected: Option<f64>) {
        match (actual, expected) {
            (Some(actual), Some(expected)) => assert_eq!(
                actual.to_bits(),
                expected.to_bits(),
                "actual={actual:?}, expected={expected:?}"
            ),
            (actual, expected) => assert_eq!(actual, expected),
        }
    }

    #[test]
    fn variance_and_stddev_match_datafusion_at_every_prefix() {
        let inputs = [
            None,
            Some(10_000_000_000_000_000.0),
            Some(10_000_000_000_000_002.0),
            Some(10_000_000_000_000_004.0),
            Some(-0.0),
            Some(0.0),
        ];
        for inputs in [
            inputs.to_vec(),
            vec![Some(f64::NAN)],
            vec![Some(f64::INFINITY), Some(f64::INFINITY)],
            vec![Some(f64::NEG_INFINITY), Some(f64::INFINITY)],
        ] {
            let mut state = VarianceState::default();
            let mut var_sample = datafusion_statistical_accumulator(&var_samp_udaf());
            let mut var_population = datafusion_statistical_accumulator(&var_pop_udaf());
            let mut stddev_sample = datafusion_statistical_accumulator(&stddev_udaf());
            let mut stddev_population =
                datafusion_statistical_accumulator(&stddev_pop_udaf());

            for input in std::iter::once(None).chain(inputs.into_iter().map(Some)) {
                if let Some(input) = input {
                    let values = [unary_array(input)];
                    var_sample.update_batch(&values).unwrap();
                    var_population.update_batch(&values).unwrap();
                    stddev_sample.update_batch(&values).unwrap();
                    stddev_population.update_batch(&values).unwrap();
                    if let Some(value) = input {
                        state.update(value);
                    }
                }

                for (projection, expected) in [
                    (
                        VarianceProjection::Variance(StatisticalPopulation::Sample),
                        scalar_float(var_sample.evaluate().unwrap()),
                    ),
                    (
                        VarianceProjection::Variance(StatisticalPopulation::Population),
                        scalar_float(var_population.evaluate().unwrap()),
                    ),
                    (
                        VarianceProjection::Stddev(StatisticalPopulation::Sample),
                        scalar_float(stddev_sample.evaluate().unwrap()),
                    ),
                    (
                        VarianceProjection::Stddev(StatisticalPopulation::Population),
                        scalar_float(stddev_population.evaluate().unwrap()),
                    ),
                ] {
                    assert_float_bits_eq(state.project(projection), expected);
                }

                let datafusion_state = var_sample.state().unwrap();
                assert_eq!(scalar_u64(datafusion_state[0].clone()), Some(state.count));
                assert_float_bits_eq(
                    scalar_float(datafusion_state[1].clone()),
                    Some(state.mean),
                );
                assert_float_bits_eq(
                    scalar_float(datafusion_state[2].clone()),
                    Some(state.m2),
                );
            }
        }
    }
}