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 crate::execution::storage::buffer::GroupedRanges;
use std::sync::{Arc, OnceLock};

use datafusion::arrow::array::make_comparator;
use datafusion::arrow::datatypes::SchemaRef;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{DataFusionError, Result, internal_err};
use datafusion::execution::memory_pool::MemoryReservation;

/// Shared partition-key schema metadata and its admitted allocation.
#[derive(Debug)]
pub(crate) struct PartitionKeySchema {
    pub(crate) schema: SchemaRef,
    _memory: MemoryReservation,
}

impl PartitionKeySchema {
    pub(crate) fn new(schema: SchemaRef, memory: MemoryReservation) -> Arc<Self> {
        Arc::new(Self {
            schema,
            _memory: memory,
        })
    }
}

/// The partition expressions evaluated once for one accepted input batch.
/// Its lease includes every shared input buffer reachable from these columns.
#[derive(Debug)]
pub(crate) struct PartitionKeyBatch {
    pub(crate) values: RecordBatch,
    pub(crate) grouped: Option<Box<GroupedRanges>>,
    _schema_owner: Option<Arc<PartitionKeySchema>>,
    _memory: MemoryReservation,
    // Replay keys can outlive history and may alias a sliced input column.
    _shared_backing: Option<Arc<MemoryReservation>>,
}

impl PartitionKeyBatch {
    #[cfg(test)]
    pub(crate) fn new(values: RecordBatch, memory: MemoryReservation) -> Arc<Self> {
        Arc::new(Self {
            values,
            grouped: None,
            _schema_owner: None,
            _memory: memory,
            _shared_backing: None,
        })
    }

    pub(crate) fn closed_grouped(
        grouped: Box<GroupedRanges>,
        memory: MemoryReservation,
    ) -> Arc<Self> {
        static EMPTY_SCHEMA: OnceLock<SchemaRef> = OnceLock::new();
        let schema = Arc::clone(
            EMPTY_SCHEMA
                .get_or_init(|| Arc::new(datafusion::arrow::datatypes::Schema::empty())),
        );
        Arc::new(Self {
            values: RecordBatch::new_empty(schema),
            grouped: Some(grouped),
            _schema_owner: None,
            _memory: memory,
            _shared_backing: None,
        })
    }

    /// Keep the admitted schema alive until the native batch releases it.
    pub(crate) fn new_with_schema(
        values: RecordBatch,
        memory: MemoryReservation,
        schema_owner: Arc<PartitionKeySchema>,
        grouped: Option<Box<GroupedRanges>>,
        shared_backing: Option<Arc<MemoryReservation>>,
    ) -> Arc<Self> {
        debug_assert!(Arc::ptr_eq(&values.schema(), &schema_owner.schema));
        Arc::new(Self {
            values,
            grouped,
            _schema_owner: Some(schema_owner),
            _memory: memory,
            _shared_backing: shared_backing,
        })
    }

    pub(crate) fn rows(&self) -> usize {
        self.grouped
            .as_ref()
            .map_or_else(|| self.values.num_rows(), |groups| groups.rows())
    }
}

/// An exact input view keeps its original key batch as the canonical owner.
#[derive(Debug, Clone)]
pub(crate) struct PartitionKeyRows {
    pub(crate) batch: Arc<PartitionKeyBatch>,
    pub(crate) offset: usize,
    pub(crate) rows: usize,
}

impl PartitionKeyRows {
    pub(crate) fn full(batch: Arc<PartitionKeyBatch>) -> Self {
        Self {
            rows: batch.rows(),
            batch,
            offset: 0,
        }
    }

    pub(crate) fn slice(&self, offset: usize, rows: usize) -> Result<Self> {
        if offset.checked_add(rows).is_none_or(|end| end > self.rows) {
            return internal_err!(
                "MATCH_RECOGNIZE cached partition keys do not cover their input view"
            );
        }
        Ok(Self {
            batch: Arc::clone(&self.batch),
            offset: self.offset + offset,
            rows,
        })
    }

    pub(crate) fn column(&self, index: usize) -> datafusion::arrow::array::ArrayRef {
        let column = self.batch.values.column(index);
        if self.offset == 0 && self.rows == column.len() {
            Arc::clone(column)
        } else {
            column.slice(self.offset, self.rows)
        }
    }

    pub(crate) fn key(&self, row: usize) -> Result<PartitionKey> {
        if row >= self.rows {
            return internal_err!(
                "MATCH_RECOGNIZE partition representative is outside its input view"
            );
        }
        OwnedPartitionKey::try_new(Arc::clone(&self.batch), self.offset + row)
    }
}

/// One canonical logical key retains only its originating key batch.
pub(crate) struct OwnedPartitionKey {
    batch: Option<Arc<PartitionKeyBatch>>,
    row: usize,
}

impl std::fmt::Debug for OwnedPartitionKey {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PartitionKey")
            .field("source", &self.batch.as_ref().map(Arc::as_ptr))
            .field("row", &self.row)
            .field("columns", &self.len())
            .finish()
    }
}

pub(crate) type PartitionKey = Arc<OwnedPartitionKey>;

pub(crate) fn shared_empty_partition_key() -> PartitionKey {
    static EMPTY: OnceLock<PartitionKey> = OnceLock::new();
    Arc::clone(EMPTY.get_or_init(|| {
        Arc::new(OwnedPartitionKey {
            batch: None,
            row: 0,
        })
    }))
}

impl OwnedPartitionKey {
    pub(crate) fn try_new(
        batch: Arc<PartitionKeyBatch>,
        row: usize,
    ) -> Result<PartitionKey> {
        if batch.values.num_columns() == 0 && batch.grouped.is_none() {
            return Ok(shared_empty_partition_key());
        }
        if row >= batch.rows()
            || batch
                .grouped
                .as_ref()
                .is_some_and(|g| !g.has_representative(row))
        {
            return internal_err!(
                "MATCH_RECOGNIZE canonical key row is outside its input batch"
            );
        }
        Ok(Arc::new(Self {
            batch: Some(batch),
            row,
        }))
    }

    pub(crate) fn group_start(&self) -> Option<usize> {
        self.batch
            .as_ref()?
            .grouped
            .as_ref()
            .map(|groups| groups.start_at(self.row))
    }

    pub(crate) fn len(&self) -> usize {
        self.batch
            .as_ref()
            .map_or(0, |batch| batch.values.num_columns())
    }

    #[cfg(test)]
    pub(crate) fn is_empty(&self) -> bool {
        self.batch.is_none()
    }

    pub(crate) fn column(&self, index: usize) -> datafusion::arrow::array::ArrayRef {
        let batch = self.batch.as_ref().expect("a nonempty key has a batch");
        batch
            .values
            .column(index)
            .slice(if batch.grouped.is_some() { 0 } else { self.row }, 1)
    }

    pub(crate) fn same_values(&self, other: &Self) -> Result<bool> {
        if std::ptr::eq(self, other) {
            return Ok(true);
        }
        if self.len() != other.len() {
            return Ok(false);
        }
        for index in 0..self.len() {
            let left = self.column(index);
            let right = other.column(index);
            if !make_comparator(left.as_ref(), right.as_ref(), Default::default())?(0, 0)
                .is_eq()
            {
                return Ok(false);
            }
        }
        Ok(true)
    }

    #[cfg(test)]
    pub(crate) fn scalar_values(&self) -> Result<Vec<datafusion::common::ScalarValue>> {
        (0..self.len())
            .map(|index| {
                datafusion::common::ScalarValue::try_from_array(
                    self.column(index).as_ref(),
                    0,
                )
            })
            .collect()
    }
}

#[cfg(test)]
impl PartialEq for OwnedPartitionKey {
    fn eq(&self, other: &Self) -> bool {
        self.same_values(other)
            .expect("test_case keys have comparable native values")
    }
}

#[cfg(test)]
impl Eq for OwnedPartitionKey {}

#[cfg(test)]
pub(crate) fn owned_partition_key(
    values: Vec<datafusion::common::ScalarValue>,
) -> PartitionKey {
    use datafusion::execution::memory_pool::{
        MemoryConsumer, MemoryPool, UnboundedMemoryPool,
    };
    if values.is_empty() {
        return shared_empty_partition_key();
    }
    let batch = RecordBatch::try_from_iter(
        values
            .into_iter()
            .enumerate()
            .map(|(index, value)| {
                value.to_array().map(|array| (format!("key{index}"), array))
            })
            .collect::<Result<Vec<_>>>()
            .unwrap(),
    )
    .unwrap();
    let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
    let memory = MemoryConsumer::new("partition-key-test_case").register(&pool);
    memory.try_grow(batch.get_array_memory_size()).unwrap();
    OwnedPartitionKey::try_new(PartitionKeyBatch::new(batch, memory), 0).unwrap()
}

pub(crate) fn key_memory_overflow() -> DataFusionError {
    DataFusionError::ResourcesExhausted(
        "MATCH_RECOGNIZE partition-key memory exceeds usize".into(),
    )
}