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.

//! Accounted producer-local output coalescing shared by both runtimes.

use std::num::NonZeroUsize;

use datafusion::arrow::array::Array;
use datafusion::arrow::compute::BatchCoalescer;
use datafusion::arrow::datatypes::SchemaRef;
use datafusion::arrow::record_batch::{RecordBatch, RecordBatchOptions};
use datafusion_common::Result;
use datafusion_execution::memory_pool::MemoryReservation;
use datafusion_hash_grouped_order::gather::{
    contains_dictionary, contains_run_end_encoded,
};

/// Admit Arrow's reported retained size before publishing output or reading
/// more input. Native operations allocate before reporting their size, so this
/// does not bound temporary allocations inside an Arrow kernel. Callers end
/// the stream and drop this owner after any error.
pub(crate) struct OutputCoalescer {
    // Release the retained arrays before their memory charge.
    inner: BatchCoalescer,
    memory: MemoryReservation,
}

impl OutputCoalescer {
    pub(crate) fn try_new_optional(
        schema: &SchemaRef,
        target: Option<NonZeroUsize>,
        memory: &MemoryReservation,
    ) -> Result<Option<Self>> {
        // Independently valid dictionaries need not have a representable union.
        // Nested/generic Arrow coalescers may also retain unused dictionary values,
        // so neither target rows nor incoming row counts establish a safe bound.
        // REE values can widen to nullable at Halo edges, and concatenated run
        // ends can exceed their integer type even when each batch fits.
        if schema.fields().iter().any(|f| {
            contains_dictionary(f.data_type()) || contains_run_end_encoded(f.data_type())
        }) {
            return Ok(None);
        }
        target
            .map(|target| Self::try_new(schema.clone(), target, memory.new_empty()))
            .transpose()
    }

    fn try_new(
        schema: SchemaRef,
        target: NonZeroUsize,
        memory: MemoryReservation,
    ) -> Result<Self> {
        let coalescer = Self {
            inner: BatchCoalescer::new(schema, target.get())
                .with_biggest_coalesce_batch_size(Some(target.get() / 2)),
            memory,
        };
        coalescer.account_memory()?;
        Ok(coalescer)
    }

    fn account_memory(&self) -> Result<()> {
        // Arrow includes retained source references, even when there are no
        // buffered rows. Keep that charge until the native owner releases them.
        self.memory.try_resize(self.inner.size())
    }

    pub(crate) fn push_batch(&mut self, batch: RecordBatch) -> Result<()> {
        self.inner.push_batch(batch)?;
        self.account_memory()
    }

    pub(crate) fn next_completed_batch(&mut self) -> Option<RecordBatch> {
        let batch = self.inner.next_completed_batch()?;
        // Native pop only removes queued storage; its retained size cannot grow.
        // The caller now owns the batch, as with PendingOutput::pop_front.
        self.memory.resize(self.inner.size());
        Some(batch)
    }

    pub(crate) fn flush_tail(&mut self) -> Result<Option<RecordBatch>> {
        self.inner.finish_buffered_batch()?;
        self.account_memory()?;
        let Some(batch) = self.next_completed_batch() else {
            return Ok(None);
        };
        let (schema, mut columns, rows) = batch.into_parts();
        // Partial batches otherwise retain the full coalescing target's capacity
        // in each primitive buffer. Release unused space before publication;
        // Arrow leaves shared input buffers untouched.
        for column in &mut columns {
            column.shrink_to_fit();
        }
        Ok(Some(RecordBatch::try_new_with_options(
            schema,
            columns,
            &RecordBatchOptions::new().with_row_count(Some(rows)),
        )?))
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::execution::common::memory::new_unbounded_state_memory;
    use std::sync::Arc;

    use datafusion::arrow::array::{ArrayRef, Int64Array};
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion_common::DataFusionError;
    use datafusion_execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryPool,
    };

    fn batch(values: &[i64]) -> Result<RecordBatch> {
        Ok(RecordBatch::try_from_iter([(
            "value",
            Arc::new(Int64Array::from(values.to_vec())) as ArrayRef,
        )])?)
    }

    #[test]
    fn dictionary_batches_bypass_coalescing_even_inside_containers() -> Result<()> {
        use datafusion::arrow::array::{
            DictionaryArray, StringArray, StructArray, UInt8Array,
        };
        use datafusion::arrow::datatypes::{Field, UInt8Type};
        for nested in [false, true] {
            let batches: Vec<_> = (0..3)
                .map(|source| {
                    let values = StringArray::from_iter_values(
                        (0..100).map(|i| format!("value-{}", source * 100 + i)),
                    );
                    let mut array: ArrayRef = Arc::new(
                        DictionaryArray::<UInt8Type>::try_new(
                            UInt8Array::from_iter_values(0..100),
                            Arc::new(values),
                        )
                        .unwrap(),
                    );
                    if nested {
                        array = Arc::new(StructArray::new(
                            vec![Field::new("d", array.data_type().clone(), false)]
                                .into(),
                            vec![array],
                            None,
                        ));
                    }
                    RecordBatch::try_from_iter([("v", array)]).unwrap()
                })
                .collect();
            let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
            let memory =
                MemoryConsumer::new("dictionary coalescer bypass").register(&pool);
            let coalescer = OutputCoalescer::try_new_optional(
                &batches[0].schema(),
                NonZeroUsize::new(300),
                &memory,
            )?;
            // None selects the stream's existing direct-output path. All 300
            // distinct values remain representable in their original batches.
            assert!(coalescer.is_none());
            assert_eq!(
                batches.iter().map(RecordBatch::num_rows).sum::<usize>(),
                300
            );
            assert_eq!(pool.reserved(), 0);
            for batch in batches {
                batch.column(0).to_data().validate_full()?;
            }
        }
        Ok(())
    }

    #[test]
    fn run_end_encoded_bypasses_coalescing_even_inside_structs() -> Result<()> {
        let ree = DataType::RunEndEncoded(
            Arc::new(Field::new("run_ends", DataType::Int16, false)),
            Arc::new(Field::new("values", DataType::Int64, false)),
        );
        let nested = DataType::Struct(vec![Field::new("ree", ree.clone(), false)].into());
        let memory = new_unbounded_state_memory();
        let target = NonZeroUsize::new(65536);
        for ty in [ree, nested] {
            let schema = Arc::new(Schema::new(vec![Field::new("v", ty, false)]));
            let coalescer = OutputCoalescer::try_new_optional(&schema, target, &memory)?;
            assert!(coalescer.is_none());
        }
        Ok(())
    }

    #[test]
    fn coalesces_values_and_accounts_until_drop() -> Result<()> {
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(4096));
        let first = batch(&[1, 2])?;
        let mut coalescer = OutputCoalescer::try_new(
            first.schema(),
            NonZeroUsize::new(4).unwrap(),
            MemoryConsumer::new("coalescer test").register(&pool),
        )?;
        coalescer.push_batch(first)?;
        assert!(coalescer.next_completed_batch().is_none());
        coalescer.push_batch(batch(&[3, 4])?)?;
        let retained = pool.reserved();
        let full = coalescer.next_completed_batch().unwrap();
        assert!(pool.reserved() < retained);
        let values = |batch: &RecordBatch| {
            batch
                .column(0)
                .as_any()
                .downcast_ref::<Int64Array>()
                .unwrap()
                .values()
                .to_vec()
        };
        assert_eq!(values(&full), [1, 2, 3, 4]);
        coalescer.push_batch(batch(&[5])?)?;
        let tail = coalescer.flush_tail()?.unwrap();
        assert_eq!(values(&tail), [5]);
        assert_eq!(tail.column(0).get_buffer_memory_size(), size_of::<i64>());
        assert!(coalescer.is_empty());
        // The native coalescer still retains its source and reusable allocations.
        assert!(pool.reserved() > 0);
        drop(coalescer);
        assert_eq!(pool.reserved(), 0);
        Ok(())
    }

    #[test]
    fn denied_growth_releases_admitted_memory_on_drop() -> Result<()> {
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(256));
        let input = batch(&[1])?;
        let mut coalescer = OutputCoalescer::try_new(
            input.schema(),
            NonZeroUsize::new(1024).unwrap(),
            MemoryConsumer::new("coalescer test").register(&pool),
        )?;
        assert!(matches!(
            coalescer.push_batch(input),
            Err(DataFusionError::ResourcesExhausted(_))
        ));
        drop(coalescer);
        assert_eq!(pool.reserved(), 0);
        Ok(())
    }
}