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.

use super::*;
use datafusion::arrow::array::Int64Array;

pub(super) enum AssemblyInput {
    Gathered,
    Sliced,
    WithPreparedColumns(PreparedColumns),
}

pub(super) enum BatchAssembly {
    Complete(RecordBatch),
    CopyInput(Option<PreparedColumns>),
}

/// Owns the final column allocation and its finished arrays. If slice admission
/// fails, this retains the generated columns across the copying gather.
pub(super) struct PreparedColumns {
    pub(super) columns: Vec<ArrayRef>,
    classifier_memory: Option<MemoryReservation>,
    memory: MemoryReservation,
    sliced_input: Option<(usize, usize)>,
}

impl PreparedColumns {
    pub(super) fn reserve_array_bytes(&mut self, bytes: usize) -> Result<()> {
        match self.memory.try_grow(bytes) {
            Err(DataFusionError::ResourcesExhausted(_))
                if self.sliced_input.is_some() =>
            {
                let (columns, bytes_to_release) = self
                    .sliced_input
                    .take()
                    .expect("assembly owns the sliced input prefix");
                // The remaining columns are generated output. Keep them and
                // their charge while releasing the retained input buffers.
                drop(self.columns.drain(..columns));
                self.memory.try_shrink(bytes_to_release)?;
                self.memory.try_grow(bytes)
            }
            result => result,
        }
    }

    fn push_generated(&mut self, array: ArrayRef) -> Result<()> {
        self.reserve_array_bytes(array.get_array_memory_size())?;
        self.columns.push(array);
        Ok(())
    }
}

impl OutputBatchBuilder {
    pub(super) fn finish_batch(
        &mut self,
        data: gather::GatherBatch,
        rows: usize,
        input: AssemblyInput,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<BatchAssembly> {
        let final_columns = self.stream.schema().fields().len();
        let remaining_fields = final_columns - data.batch.num_columns();
        debug_assert_eq!(data.batch.num_rows(), rows);
        let gather::GatherBatch { batch, memory } = data;
        let (_, mut columns, _) = batch.into_parts();
        let sliced = matches!(&input, AssemblyInput::Sliced);
        if let AssemblyInput::WithPreparedColumns(mut output) = input {
            debug_assert_eq!(output.columns.len(), remaining_fields);
            debug_assert!(output.columns.capacity() >= final_columns);
            let input_columns = columns.len();
            output.columns.append(&mut columns);
            output.columns.rotate_right(input_columns);
            let vec_bytes = columns.capacity() * size_of::<ArrayRef>();
            drop(columns);
            memory.shrink(vec_bytes.min(memory.size()));
            return self.seal_batch(output, rows, 1, completed);
        }
        let sliced_bytes = memory
            .size()
            .saturating_sub(columns.capacity() * size_of::<ArrayRef>());
        if let Err(error) = try_reserve_accounted(
            &mut columns,
            &memory,
            remaining_fields,
            "final output columns",
        ) {
            if sliced && matches!(error, DataFusionError::ResourcesExhausted(_)) {
                // No generated columns have changed yet.
                completed(1)?;
                return Ok(BatchAssembly::CopyInput(None));
            }
            return Err(error);
        }
        let sliced_input = sliced.then_some((columns.len(), sliced_bytes));
        let mut output = PreparedColumns {
            columns,
            classifier_memory: None,
            memory,
            sliced_input,
        };
        // Admit each finished array before mutating the next builder.
        for column in self.stream.spec().metadata_columns() {
            let array = match column {
                MatchMetadataColumn::Classifier => {
                    if let Some(builder) = &mut self.class_builder {
                        let array = Arc::new(builder.finish());
                        // Carry the pending charge through a copying gather and
                        // admit any extra retained Arrow capacity.
                        let bytes = array.get_array_memory_size();
                        let retained = self.class_reserved.min(bytes);
                        let release = self.class_reserved - retained;
                        if release != 0 {
                            self.memory.try_shrink(release)?;
                        }
                        output.classifier_memory = Some(self.memory.split(retained));
                        self.class_reserved = 0;
                        self.class_bytes = 0;
                        output.reserve_array_bytes(bytes - retained)?;
                        output.columns.push(array);
                    }
                    continue;
                }
                MatchMetadataColumn::MatchNumber => self
                    .match_num_builder
                    .as_mut()
                    .map(|b| Arc::new(b.finish()) as ArrayRef),
                MatchMetadataColumn::MatchSequenceNumber => self
                    .seq_builder
                    .as_mut()
                    .map(|b| Arc::new(b.finish()) as ArrayRef),
                MatchMetadataColumn::Excluded => self
                    .excluded_builder
                    .as_mut()
                    .map(|b| Arc::new(b.finish()) as ArrayRef),
                MatchMetadataColumn::PathId => {
                    return internal_err!(
                        "__mr_path_id is an internal column and cannot be in final output"
                    );
                }
            };
            if let Some(array) = array {
                output.push_generated(array)?;
            }
        }
        for bits in &mut self.classifier_bits_builders {
            output.push_generated(Arc::new(bits.finish()))?;
        }

        match &mut self.summary_output {
            SummaryOutputStorage::Ordinary => {}
            SummaryOutputStorage::DirectCounts {
                columns: counts, ..
            } => {
                for column in counts {
                    if let Some((array, _)) = &column.prepared_array {
                        output.columns.push(Arc::clone(array));
                        continue;
                    }
                    // Arrow adopts the vector allocation. Only the array header
                    // needs a fresh charge while the value reservation stays live.
                    output.reserve_array_bytes(size_of::<Int64Array>())?;
                    // Counts were checked to fit Int64 during selection.
                    let values = datafusion::arrow::buffer::Buffer::from_vec(
                        std::mem::take(&mut column.values),
                    );
                    let array = Int64Array::new(values.into(), None);
                    output.columns.push(Arc::new(array));
                }
            }
        }
        if sliced && output.sliced_input.is_none() {
            completed(remaining_fields)?;
            return Ok(BatchAssembly::CopyInput(Some(output)));
        }
        self.seal_batch(output, rows, remaining_fields + 1, completed)
    }

    fn seal_batch(
        &mut self,
        output: PreparedColumns,
        rows: usize,
        work: usize,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<BatchAssembly> {
        let batch = RecordBatch::try_new_with_options(
            gather::gathered_schema(self.stream.schema(), &output.columns),
            output.columns,
            &datafusion::arrow::record_batch::RecordBatchOptions::new()
                .with_row_count(Some(rows)),
        )?;
        completed(work)?;

        if let SummaryOutputStorage::DirectCounts {
            columns,
            row_capacity,
            reductions,
            ..
        } = &mut self.summary_output
        {
            for column in columns {
                column.values = Vec::new();
                column.prepared_array = None;
                column.memory.free();
            }
            if let Some(reductions) = reductions {
                for slot in reductions.slots.iter_mut().flatten() {
                    slot.release();
                }
            }
            *row_capacity = 0;
        }
        drop(output.classifier_memory);
        Ok(BatchAssembly::Complete(batch))
    }
}

#[cfg(test)]
mod tests {
    use super::super::tests::test_case;
    use super::*;
    use crate::execution::matching::path::Sym;
    use datafusion_execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryPool,
    };

    #[test]
    fn compact_classifier_exhausts_pool_before_flush() -> Result<()> {
        let (template, _) = test_case(vec![MatchMetadataColumn::Classifier], false);
        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(5000));
        let mut builder = OutputBatchBuilder::try_new(
            Arc::clone(&template.stream),
            16,
            PartitionPassthrough::default(),
            0,
            MemoryConsumer::new("compact classifier").register(&pool),
        )?;
        let name = "A".repeat(1024);
        let classifier = Some(EncodedClassifier {
            symbol: Sym::from_index(1),
            name: &name,
        });
        let append = |builder: &mut OutputBatchBuilder| {
            builder.append_compact_rows(2, 0, classifier, 1, 1, false, &mut |_| Ok(()))
        };
        append(&mut builder)?;
        append(&mut builder)?;
        let reserved = pool.reserved();
        assert!(matches!(
            append(&mut builder),
            Err(DataFusionError::ResourcesExhausted(_))
        ));
        assert_eq!(builder.len(), 4);
        assert_eq!(builder.class_builder.as_ref().unwrap().len(), 4);
        assert_eq!(pool.reserved(), reserved);
        drop(builder);
        assert_eq!(pool.reserved(), 0);
        Ok(())
    }
}