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.

//! Scratch buffers grouped by traversal, symbols, aggregates, and partitions.

use super::*;
use crate::execution::common::memory::{reserved_vec, try_reserve_accounted};
use crate::execution::identity::PartitionKeyBinding;
use datafusion_common::Result;
use datafusion_execution::memory_pool::MemoryReservation;

/// Buffers used for symbol boolean evaluation and ID collection.
#[derive(Debug)]
pub(crate) struct SymbolEvaluationContext {
    /// Row-level necessary AND checks for variables with residual evaluation.
    pub(crate) pre_checks: Vec<bool>,
    /// OR short-circuit results: if true, skip aggregate evaluation (row-level part of OR passed).
    pub(crate) or_passes: Vec<bool>,
    /// Ordered transition worklist with failed static prechecks omitted.
    pub(crate) matched_ids: Vec<SymbolId>,
    /// Generation stamps used to deduplicate physical and eager symbol
    /// encounters in O(1) without linear `Vec::contains` scans.
    pub(crate) matched_seen: Vec<u32>,
    /// Current generation marker for `matched_seen`.
    pub(crate) matched_seen_gen: u32,
    // Charges follow retained capacity across row and partition resets.
    pub(crate) memory: MemoryReservation,
}

impl SymbolEvaluationContext {
    pub(crate) fn new(n_symbols: usize, memory: MemoryReservation) -> Result<Self> {
        let mut context = Self {
            pre_checks: reserved_vec(n_symbols, &memory, "symbol prechecks")?,
            or_passes: reserved_vec(n_symbols, &memory, "symbol OR results")?,
            matched_ids: reserved_vec(8, &memory, "matched symbol IDs")?,
            matched_seen: reserved_vec(n_symbols, &memory, "symbol generations")?,
            matched_seen_gen: 1,
            memory,
        };
        context.ensure_capacity(n_symbols)?;
        Ok(context)
    }

    pub(super) fn ensure_capacity(&mut self, n_symbols: usize) -> Result<()> {
        let additional = n_symbols.saturating_sub(self.pre_checks.len());
        try_reserve_accounted(
            &mut self.pre_checks,
            &self.memory,
            additional,
            "symbol prechecks",
        )?;
        self.pre_checks
            .resize(self.pre_checks.len().max(n_symbols), true);
        let additional = n_symbols.saturating_sub(self.or_passes.len());
        try_reserve_accounted(
            &mut self.or_passes,
            &self.memory,
            additional,
            "symbol OR results",
        )?;
        self.or_passes
            .resize(self.or_passes.len().max(n_symbols), false);
        let additional = n_symbols.saturating_sub(self.matched_seen.len());
        try_reserve_accounted(
            &mut self.matched_seen,
            &self.memory,
            additional,
            "symbol generations",
        )?;
        self.matched_seen
            .resize(self.matched_seen.len().max(n_symbols), 0);
        Ok(())
    }

    pub(super) fn reset(&mut self) {
        self.pre_checks.fill(true);
        self.or_passes.fill(false);
        self.matched_ids.clear();
    }

    pub(super) fn reset_partition_generation(&mut self) {
        self.matched_seen.fill(0);
        self.matched_seen_gen = 1;
    }

    #[inline]
    pub(crate) fn next_seen_generation(
        &mut self,
        completed: &mut impl FnMut(usize) -> Result<()>,
    ) -> Result<u32> {
        try_advance_generation(
            &mut self.matched_seen_gen,
            &mut self.matched_seen,
            completed,
        )
    }
}

/// Advance a stamp generation, publishing wraparound only after every stamp
/// is cleared. Cancellation leaves the old generation intact so clearing can retry.
#[inline]
pub(crate) fn try_advance_generation(
    generation: &mut u32,
    stamps: &mut [u32],
    completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<u32> {
    let next = generation.wrapping_add(1);
    if next != 0 {
        *generation = next;
        return Ok(next);
    }
    for stamp in stamps {
        *stamp = 0;
        completed(1)?;
    }
    *generation = 1;
    Ok(1)
}

/// Physical execution and immutable program identity, retained across recycling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ExecutionBinding {
    pub(crate) execution_partition_id: ExecutionPartitionId,
    pub(crate) program_id: MatchProgramId,
}

/// One scheduler-issued logical partition and its physical-head or canonical key binding.
#[derive(Debug, Clone)]
pub(crate) struct LogicalPartitionBinding {
    pub(crate) partition_id: MatchPartitionId,
    pub(crate) key: PartitionKeyBinding,
}

/// Context related to partitioning and row offsets.
#[derive(Debug)]
pub(crate) struct PartitionContext {
    pub(crate) execution: Option<ExecutionBinding>,
    pub(crate) logical: Option<LogicalPartitionBinding>,
    /// Global row offset of the current BatchCollection.
    pub(crate) global_row_offset: usize,
    /// The starting row of the current logical partition within the batch collection.
    pub(crate) partition_start_row: usize,
    /// The ending row of the current logical partition within the batch collection.
    pub(crate) partition_end_row: usize,
    /// Absolute start row of the logical partition in the global stream.
    pub(crate) absolute_partition_start: usize,
    /// Next match number to assign for this logical partition.
    pub(crate) next_match_number: u64,
    /// Persists across physical heads and selected-output yields so the final
    /// zero-width attempt runs at most once for the logical partition.
    pub(crate) terminal_empty_attempted: bool,
    /// A soft Lane-capacity miss keeps subsequent starts on General until this
    /// logical partition ends; physical input heads do not reset the decision.
    pub(crate) lane_disabled: bool,
}

impl PartitionContext {
    pub(super) fn new(initial_match_number: u64) -> Self {
        Self {
            execution: None,
            logical: None,
            global_row_offset: 0,
            partition_start_row: 0,
            partition_end_row: 0,
            absolute_partition_start: 0,
            next_match_number: initial_match_number,
            terminal_empty_attempted: false,
            lane_disabled: false,
        }
    }

    pub(crate) fn logical(&self) -> Result<&LogicalPartitionBinding> {
        self.logical.as_ref().ok_or_else(|| {
            datafusion_common::DataFusionError::Internal(
                "MATCH_RECOGNIZE context has no logical partition identity".to_string(),
            )
        })
    }

    /// Clear the logical partition binding before this allocation is reused.
    /// Physical execution and immutable program identity remain bound.
    pub(super) fn reset_for_partition(
        &mut self,
        absolute_start: usize,
        initial_match_number: u64,
    ) {
        self.logical = None;
        self.global_row_offset = 0;
        self.partition_start_row = 0;
        self.partition_end_row = 0;
        self.absolute_partition_start = absolute_start;
        self.next_match_number = initial_match_number;
        self.terminal_empty_attempted = false;
        self.lane_disabled = false;
    }
}

#[cfg(test)]
mod tests {
    use super::SymbolEvaluationContext;
    use crate::execution::matching::row_loop::state::WorkGovernor;

    #[test]
    fn symbol_capacity_requires_admission_and_stays_charged_across_resets() {
        use datafusion_execution::memory_pool::{
            GreedyMemoryPool, MemoryConsumer, MemoryPool,
        };
        use std::sync::Arc;
        let denied: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(0));
        assert!(
            SymbolEvaluationContext::new(
                4,
                MemoryConsumer::new("denied symbols").register(&denied)
            )
            .is_err()
        );
        assert_eq!(denied.reserved(), 0);

        let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(4096));
        let mut symbols = SymbolEvaluationContext::new(
            4,
            MemoryConsumer::new("symbols").register(&pool),
        )
        .unwrap();
        symbols.ensure_capacity(32).unwrap();
        let retained = pool.reserved();
        assert!(retained > 0);
        symbols.reset();
        symbols.reset_partition_generation();
        assert_eq!(pool.reserved(), retained);
        assert!(symbols.ensure_capacity(8192).is_err());
        assert_eq!(pool.reserved(), retained);
        assert_eq!(symbols.pre_checks.len(), 32);
        drop(symbols);
        assert_eq!(pool.reserved(), 0);
    }

    #[test]
    fn seen_generation_wrap_publishes_only_after_retry_clears_every_stamp() {
        let mut symbols = SymbolEvaluationContext::new(
            300,
            crate::execution::common::memory::new_unbounded_state_memory().new_empty(),
        )
        .unwrap();
        symbols.matched_seen_gen = u32::MAX;
        symbols.matched_seen.fill(1);
        let mut governor = WorkGovernor::default();

        let error = symbols
            .next_seen_generation(&mut |units| governor.record_completed(units, || true))
            .expect_err("generation wrap clear must observe cancellation");

        assert!(error.to_string().contains("cancelled"), "{error}");
        assert_eq!(symbols.matched_seen_gen, u32::MAX);
        assert_eq!(governor.work_since_yield_for_test(), 256);
        assert!(symbols.matched_seen[..256].iter().all(|&stamp| stamp == 0));
        assert!(symbols.matched_seen[256..].iter().all(|&stamp| stamp == 1));

        let generation = symbols
            .next_seen_generation(&mut |units| governor.record_completed(units, || false))
            .expect("generation wrap clear should be retryable");

        assert_eq!(generation, 1);
        assert_eq!(symbols.matched_seen_gen, 1);
        assert!(symbols.matched_seen.iter().all(|&stamp| stamp == 0));
        assert_eq!(governor.work_since_yield_for_test(), 556);
    }
}