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.

//! Reusable, memory-accounted path nodes shared by the static and match-aware frontiers.

use crate::execution::common::memory::try_reserve_accounted;
use datafusion::execution::memory_pool::MemoryReservation;
use std::ops::Deref;

use crate::execution::matching::path::{
    PathNode, PathNodeIndex, PathStep, checked_path_node, is_reserved_path_node,
};
use datafusion::common::{DataFusionError, Result};

pub(crate) const INITIAL_PATH_NODE_CAPACITY: usize = 1024;

/// Frontiers share the initial reservation size, subsequent growth, and path validation.
pub(crate) struct PathNodeArena {
    // Keep the allocation charged until after the vector drops.
    nodes: Vec<PathNode>,
    memory: MemoryReservation,
}

impl PathNodeArena {
    pub(crate) fn new(memory: &MemoryReservation) -> Self {
        Self {
            nodes: Vec::new(),
            memory: memory.new_empty(),
        }
    }

    #[inline]
    pub(crate) fn allocate(
        &mut self,
        step: PathStep,
        prev: Option<PathNodeIndex>,
    ) -> Result<PathNodeIndex> {
        let (index, node) = checked_path_node_append(&self.nodes, step, prev)?;
        if self.nodes.len() == self.nodes.capacity() {
            let additional = if self.nodes.is_empty() {
                INITIAL_PATH_NODE_CAPACITY
            } else {
                1
            };
            try_reserve_accounted(
                &mut self.nodes,
                &self.memory,
                additional,
                "path arena",
            )?;
        }
        self.nodes.push(node);
        Ok(index)
    }

    /// Roll back logical path entries and retain the admitted capacity for reuse.
    pub(crate) fn truncate(&mut self, len: usize) {
        self.nodes.truncate(len);
    }

    #[cfg(test)]
    pub(crate) fn memory(&self) -> &MemoryReservation {
        &self.memory
    }

    #[cfg(test)]
    pub(crate) fn extend_for_test<I>(&mut self, nodes: I)
    where
        I: IntoIterator<Item = PathNode>,
        I::IntoIter: ExactSizeIterator,
    {
        let nodes = nodes.into_iter();
        try_reserve_accounted(
            &mut self.nodes,
            &self.memory,
            nodes.len(),
            "path arena test_case",
        )
        .unwrap();
        self.nodes.extend(nodes);
    }
}

impl Deref for PathNodeArena {
    type Target = [PathNode];

    #[inline]
    fn deref(&self) -> &[PathNode] {
        &self.nodes
    }
}

pub(crate) fn checked_path_node_index(raw_index: usize) -> Result<PathNodeIndex> {
    let index = PathNodeIndex::try_from(raw_index).map_err(|_| {
        DataFusionError::ResourcesExhausted(format!(
            "MATCH_RECOGNIZE path node index {raw_index} exceeds u32"
        ))
    })?;
    if is_reserved_path_node(index) {
        return Err(DataFusionError::ResourcesExhausted(format!(
            "MATCH_RECOGNIZE path node arena exhausted before reserved index {index}"
        )));
    }
    Ok(index)
}

fn checked_child_depth(
    prev_idx: Option<PathNodeIndex>,
    arena: &[PathNode],
) -> Result<u32> {
    let Some(prev_idx) = prev_idx else {
        return Ok(0);
    };
    checked_path_node(arena, prev_idx)?
        .depth
        .checked_add(1)
        .ok_or_else(|| {
            DataFusionError::ResourcesExhausted(
                "MATCH_RECOGNIZE path node depth exceeds u32".to_string(),
            )
        })
}

#[inline]
pub(crate) fn checked_path_node_append(
    arena: &[PathNode],
    step: PathStep,
    prev: Option<PathNodeIndex>,
) -> Result<(PathNodeIndex, PathNode)> {
    let index = checked_path_node_index(arena.len())?;
    let depth = checked_child_depth(prev, arena)?;
    Ok((index, PathNode { step, prev, depth }))
}

#[cfg(test)]
pub(crate) fn allocate_path_node(
    step: PathStep,
    prev: Option<PathNodeIndex>,
    arena: &mut Vec<PathNode>,
) -> Result<PathNodeIndex> {
    let (index, node) = checked_path_node_append(arena, step, prev)?;
    arena.push(node);
    Ok(index)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::AbsoluteRow;
    use crate::execution::matching::path::{Sym, compact_path_node};

    fn step(row: u64) -> PathStep {
        PathStep {
            row: AbsoluteRow::new(row),
            sym: Sym::User(0),
            excluded: false,
        }
    }

    fn node(depth: u32) -> PathNode {
        PathNode {
            step: step(0),
            prev: None,
            depth,
        }
    }

    #[test]
    fn reserved_path_index_is_rejected() {
        let reserved = usize::try_from(compact_path_node()).unwrap();
        let last_valid = reserved - 1;

        assert_eq!(
            checked_path_node_index(last_valid).unwrap(),
            compact_path_node() - 1
        );

        for invalid in [reserved, usize::MAX] {
            let error = checked_path_node_index(invalid)
                .expect_err("reserved or overflowing path index must be rejected");
            assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
        }
        let read_error = checked_path_node(&[], compact_path_node()).unwrap_err();
        assert!(read_error.to_string().contains("path node index"));
        assert!(read_error.to_string().contains("reserved"));
    }

    #[test]
    fn path_allocation_preserves_roots_children_and_rejects_invalid_predecessors_atomically()
     {
        let mut arena = Vec::new();
        let root = allocate_path_node(step(10), None, &mut arena).unwrap();
        let child = allocate_path_node(step(11), Some(root), &mut arena).unwrap();
        assert_eq!((root, child), (0, 1));
        assert_eq!(
            (arena[0].depth, arena[0].prev, arena[1].depth, arena[1].prev),
            (0, None, 1, Some(0))
        );
        assert_eq!(
            (arena[0].step.row, arena[1].step.row),
            (AbsoluteRow::new(10), AbsoluteRow::new(11))
        );
        for (mut arena, predecessor, exhausted) in
            [(vec![], 0, false), (vec![node(u32::MAX)], 0, true)]
        {
            let before = arena
                .iter()
                .map(|n| (n.step, n.prev, n.depth))
                .collect::<Vec<_>>();
            let error =
                allocate_path_node(step(99), Some(predecessor), &mut arena).unwrap_err();
            assert_eq!(
                matches!(error, DataFusionError::ResourcesExhausted(_)),
                exhausted
            );
            if !exhausted {
                assert!(matches!(error, DataFusionError::Internal(_)));
            }
            assert_eq!(
                arena
                    .iter()
                    .map(|n| (n.step, n.prev, n.depth))
                    .collect::<Vec<_>>(),
                before
            );
        }
    }

    #[test]
    fn path_growth_denial_preserves_existing_nodes() {
        use datafusion::execution::memory_pool::{
            GreedyMemoryPool, MemoryConsumer, MemoryPool,
        };
        use std::sync::Arc;

        let initial_bytes = INITIAL_PATH_NODE_CAPACITY * size_of::<PathNode>();
        let pool: Arc<dyn MemoryPool> =
            Arc::new(GreedyMemoryPool::new(2 * initial_bytes - 1));
        let memory = MemoryConsumer::new("path arena test").register(&pool);
        let mut arena: PathNodeArena = PathNodeArena::new(&memory);
        assert_eq!(pool.reserved(), 0);
        for row in 0..INITIAL_PATH_NODE_CAPACITY {
            let index = arena.allocate(step(row as u64), None).unwrap();
            assert_eq!(index as usize, row);
        }
        assert_eq!(pool.reserved(), initial_bytes);

        let error = arena
            .allocate(step(INITIAL_PATH_NODE_CAPACITY as u64), Some(0))
            .expect_err("the pool cannot admit the doubled path arena");
        assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
        assert_eq!(arena.len(), INITIAL_PATH_NODE_CAPACITY);
        assert_eq!(arena.nodes.capacity(), INITIAL_PATH_NODE_CAPACITY);
        assert!(arena.iter().enumerate().all(|(index, node)| {
            node.step == step(index as u64) && node.prev.is_none() && node.depth == 0
        }));
        assert_eq!(arena.memory().size(), initial_bytes);
        assert_eq!(pool.reserved(), initial_bytes);
        drop(arena);
        assert_eq!(pool.reserved(), 0);
    }
}