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.

//! Creates a partition-local output stream from a prepared matcher program.

use std::num::NonZeroUsize;
use std::sync::Arc;

use datafusion::common::Result;
use datafusion::execution::TaskContext;
use datafusion::physical_expr_common::sort_expr::PhysicalSortExpr;
use datafusion::physical_plan::SendableRecordBatchStream;
use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;

use crate::config::MatchRecognizeConfig;
use crate::core::{EmptyMatchesMode, RowsPerMatch};
use crate::execution::common::scheduling::SliceControl;
use crate::execution::matching::ExecutableMatchProgram;
use crate::execution::metrics::PatternMetrics;
use crate::execution::physical::PartitionRetention;
use crate::execution::stream::stateful_stream::match_aware_stream;
use crate::execution::stream::{MatchInput, drain_empty_stream};
use datafusion::physical_expr::expressions::Column;

/// Partition-local inputs kept outside the immutable executable program.
pub(crate) struct ExecutePatternInput {
    pub(crate) input: MatchInput,
    pub(crate) program: Arc<ExecutableMatchProgram>,
    pub(crate) partition_by_sort_keys: Vec<PhysicalSortExpr>,
    pub(crate) retention: PartitionRetention,
    /// Number of leading rows in each physical halo partition that own
    /// candidate starts.
    pub(crate) candidate_start_core_rows: Option<NonZeroUsize>,
    /// Optional producer-local output batch target.
    pub(crate) output_batch_size: Option<NonZeroUsize>,
    pub(crate) flush_threshold: usize,
    pub(crate) config: MatchRecognizeConfig,
    pub(crate) metrics_set: ExecutionPlanMetricsSet,
    pub(crate) task_context: Arc<TaskContext>,
    pub(crate) partition: usize,
}

impl ExecutePatternInput {
    pub(crate) fn base_match_number(&self) -> Result<u64> {
        if !self.partition_by_sort_keys.is_empty() {
            return Ok(1);
        }
        // Keep the existing per-physical-partition stride for unkeyed matches.
        u64::try_from(self.partition)
            .ok()
            .and_then(|index| index.checked_mul(1_000_000_000_000))
            .and_then(|offset| offset.checked_add(1))
            .ok_or_else(|| {
                datafusion::common::DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE physical partition exceeds match-number range"
                        .into(),
                )
            })
    }
}

/// Start pattern matching on one DataFusion input partition.
///
/// `input` combines the shared executable program with this partition's input
/// stream, ordering, task context, metrics, and settings. Construction here
/// creates only mutable runtime state and the output stream. Physical planning
/// has already checked schema, symbol, aggregate, and VM bindings.
pub(crate) fn execute_pattern(
    input: ExecutePatternInput,
) -> Result<SendableRecordBatchStream> {
    let duration = input.config.limits.active_slice_duration()?;
    let control = SliceControl::default();
    {
        let program = input.program.as_ref();
        let can_drain_empty = input.candidate_start_core_rows.is_none()
            && !matches!(
                program.rows_per_match(),
                RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
            )
            && program.is_infallible_never()
            && input
                .partition_by_sort_keys
                .iter()
                .all(|key| key.expr.downcast_ref::<Column>().is_some());
        if can_drain_empty {
            let _ = input.base_match_number()?;
            let mut governor = crate::execution::common::work::WorkGovernor::default();
            governor.bind_cancellation_policy(
                crate::config::CancellationPolicy::try_from_configured(
                    input.config.limits.cancellation_poll_interval,
                    input.config.limits.execution_deadline_millis,
                )?,
            )?;
            let metrics = PatternMetrics::new(&input.metrics_set, input.partition);
            let input_schema = input.input.schema();
            return Ok(drain_empty_stream(
                input.input,
                input_schema,
                Arc::clone(program.output_schema()),
                metrics,
                control,
                governor,
            )
            .scheduled(duration));
        }
    }
    Ok(match_aware_stream(input, control)?.scheduled(duration))
}