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.

//! Allocation accounting for immutable runtime-compiled automaton owners.

use super::*;
use std::mem::size_of_val;

impl CompactPrefixSuffixInfo {
    /// Heap bytes retained by the fixed prefix and suffix vectors.
    ///
    /// This excludes the inline descriptor. Runtime owners use this count
    /// when cloning a compact shape independently of its compiled automaton.
    ///
    /// # Errors
    ///
    /// Returns a resource error when the vector capacities exceed `usize` bytes.
    pub fn retained_heap_bytes(&self) -> Result<usize> {
        self.prefix
            .capacity()
            .checked_add(self.suffix.capacity())
            .and_then(|count| count.checked_mul(size_of::<(SymbolId, usize)>()))
            .ok_or_else(|| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE retained compact shape size exceeds usize".into(),
                )
            })
    }
}

impl CompiledAutomaton {
    /// Retained owner, graph, names, and structural-table bytes.
    ///
    /// Shared Arc allocations are counted in full for this owner, including
    /// their two reference counters. Callers retaining several aliases to the
    /// same automaton should charge the allocation once. Allocator bookkeeping
    /// is outside this count, following DataFusion's reservation convention.
    ///
    /// # Errors
    ///
    /// Returns a resource error if the sum cannot be represented by `usize`.
    pub fn retained_size_bytes(&self) -> Result<usize> {
        fn overflow() -> DataFusionError {
            DataFusionError::ResourcesExhausted(
                "MATCH_RECOGNIZE retained automaton size exceeds usize".into(),
            )
        }
        fn arc_bytes<T>(values: &[T]) -> Option<usize> {
            size_of_val(values).checked_add(2 * size_of::<usize>())
        }
        let mut total = size_of::<Self>()
            .checked_add(self.nfa.retained_heap_bytes().ok_or_else(overflow)?)
            .and_then(|n| n.checked_add(size_of_val(self.loop_back_edges.as_ref())))
            .and_then(|n| {
                self.id_to_symbol
                    .capacity()
                    .checked_mul(size_of::<Option<String>>())
                    .and_then(|v| n.checked_add(v))
            })
            .ok_or_else(overflow)?;
        for name in self.id_to_symbol.iter().flatten() {
            total = total.checked_add(name.capacity()).ok_or_else(overflow)?;
        }
        if let Some(symbols) = &self.reachable_symbols {
            total = total
                .checked_add(arc_bytes(symbols).ok_or_else(overflow)?)
                .ok_or_else(overflow)?;
        }
        total = total
            .checked_add(
                arc_bytes(&self.unconditional_closure_transition_bitmap)
                    .ok_or_else(overflow)?,
            )
            .and_then(|n| {
                arc_bytes(&self.unconditional_first_accepting_state)
                    .and_then(|v| n.checked_add(v))
            })
            .and_then(|n| {
                n.checked_add(size_of_val(self.unconditional_accepting_rank.as_ref()))
            })
            .ok_or_else(overflow)?;
        if let Some(CompactPathShape::PrefixSuffix(shape)) = &self.compact_path_shape {
            total = total
                .checked_add(shape.retained_heap_bytes()?)
                .ok_or_else(overflow)?;
        }
        if let Some(program) = &self.anchor_program {
            for table in &program.0 {
                total = total
                    .checked_add(size_of_val(table.states.as_ref()))
                    .and_then(|n| n.checked_add(size_of_val(table.dispatch.as_ref())))
                    .ok_or_else(overflow)?;
            }
        }
        Ok(total)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::RepetitionQuantifier;

    fn compile(pattern: Pattern, name: &str) -> CompiledAutomaton {
        CompiledAutomaton::compile(&NormalizedPattern::Ast(pattern), &[name.to_owned()])
            .unwrap()
    }

    #[test]
    fn retained_size_counts_symbol_storage_without_scaling_with_arc_aliases() {
        let short = compile(Pattern::Symbol(Symbol::Named("A".into())), "A");
        let name = "A".repeat(4096);
        let long = Arc::new(compile(Pattern::Symbol(Symbol::Named(name.clone())), &name));
        let bytes = long.retained_size_bytes().unwrap();
        assert_eq!(bytes - short.retained_size_bytes().unwrap(), name.len() - 1);
        let alias = Arc::clone(&long);
        assert_eq!(alias.retained_size_bytes().unwrap(), bytes);
    }

    #[test]
    fn retained_size_grows_with_graph_and_charges_anchor_storage() {
        let symbol = || Pattern::Symbol(Symbol::Named("A".into()));
        let small = compile(symbol(), "A");
        let expanded = compile(
            Pattern::Repetition(Box::new(symbol()), RepetitionQuantifier::Range(1, 128)),
            "A",
        );
        assert!(
            expanded.retained_size_bytes().unwrap()
                > small.retained_size_bytes().unwrap()
        );

        let mut anchored = compile(
            Pattern::Concat(vec![
                Pattern::Symbol(Symbol::Start),
                symbol(),
                Pattern::Symbol(Symbol::End),
            ]),
            "A",
        );
        let bytes = anchored.retained_size_bytes().unwrap();
        let program = anchored
            .anchor_program
            .take()
            .expect("anchor tables were built");
        let anchor_bytes = program
            .0
            .iter()
            .map(|table| {
                table.states.len() * size_of::<AnchorState>()
                    + table.dispatch.len() * size_of::<AutomatonStateId>()
            })
            .sum::<usize>();
        assert!(anchor_bytes > 0);
        assert_eq!(
            bytes - anchored.retained_size_bytes().unwrap(),
            anchor_bytes
        );
    }
}