datafusion-match-recognize 0.55.0

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.

//! Scans a partition slice and appends completed matches to the output.
//!
//! [`ScanContext`] keeps the current start row, skip position, and in-progress
//! NFA scan. When work yields, those values are saved before returning
//! `Yield` or `Wait`; the bound scan continues
//! the same partition without reevaluating rows.

use super::PatternMatcher;
use super::row_loop::compiled_program::ExecutablePatternVariant;
use super::row_loop::continuation::{ActiveVariant, NextMatchCursor};
use super::row_loop::lane_scan::direct_payload::DirectRouteCounters;
use super::row_loop::lane_scan::{self, LaneScanProgram};
use super::row_loop::scan::RowLoopSession;
use super::row_loop::state::{AcceptingCandidate, ScanContext};
use super::symbol_columns::MultiBatchBoolColumns;
use crate::core::{AbsoluteRow, PhysicalEndExclusive, PhysicalRowCount};
use crate::execution::common::coordinates::{
    absolute_row_from_usize, absolute_row_to_usize,
};
use crate::execution::common::progress::ComputeStep;
use crate::execution::identity::{CollectionHeadGeneration, MatchPartitionId};
use crate::execution::storage::PendingOutput;
use crate::execution::storage::accumulator::{MatchAccumulator, MatchEmissionContext};
use crate::execution::storage::collection::BatchCollection;
use datafusion::common::{DataFusionError, Result, internal_err};
use std::sync::Arc;

struct CollectionSetup<'a> {
    provider_origin: usize,
    absolute_read_end: usize,
    provider: MultiBatchBoolColumns,
    total_rows: usize,
    variant: ActiveVariant,
    input_buffer: &'a BatchCollection,
    final_flush: bool,
    history_buffer:
        Option<&'a crate::execution::storage::history_buffer::SharedHistoryBuffer>,
}

/// The unpublished start handed from the closed direct driver to LaneRunner.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum SkipDirect {
    #[default]
    None,
    AtRow(usize),
    /// A long static scan already proved this candidate has no winner.
    StaticFailure(usize),
}

struct MatchAwareCandidates<'a, 'matcher> {
    matcher: &'matcher mut PatternMatcher,
    setup: CollectionSetup<'a>,
    anchor_head: Option<(MatchPartitionId, CollectionHeadGeneration)>,
    lane: lane_scan::LaneCollection,
    starts: super::symbol_columns::CandidateStarts,
    end_row: usize,
    read_end_row: usize,
    out: &'matcher mut MatchAccumulator,
    pending_output: &'matcher mut PendingOutput,
    pending_output_at_start: usize,
    stop_on_output: bool,
    metrics: &'matcher crate::execution::metrics::PatternMetrics,
    yield_policy: crate::config::YieldPolicy,
    row_idx: usize,
    min_match_rows: usize,
    max_match_rows: Option<usize>,
    anchored_at_end: bool,
    candidate_cleanup_finalized: bool,
    inline_only: bool,
    skip_direct: SkipDirect,
    batched_base_routes: Option<&'matcher mut DirectRouteCounters>,
    scan_ctx: &'matcher mut ScanContext,
}

/// Arguments for one collection slice.
pub(crate) struct ProcessRowsInput<'a> {
    pub(crate) stop_on_output: bool,
    pub(crate) batches: &'a BatchCollection,
    pub(crate) bool_columns: &'a Arc<super::symbol_columns::MultiBatchBoolColumnsBacking>,
    pub(crate) start_row: usize,
    pub(crate) end_row: usize,
    /// Optional end-exclusive boundary for opening new candidates. Rows up to
    /// `end_row` remain readable so an already-open candidate can finish.
    pub(crate) candidate_end_row: Option<usize>,
    pub(crate) out: &'a mut MatchAccumulator,
    pub(crate) pending_output: &'a mut PendingOutput,
    pub(crate) history_buffer:
        Option<&'a crate::execution::storage::history_buffer::SharedHistoryBuffer>,
    pub(crate) metrics: &'a crate::execution::metrics::PatternMetrics,
    pub(crate) yield_policy: crate::config::YieldPolicy,
    pub(crate) partition_id: MatchPartitionId,
    pub(crate) head_generation: CollectionHeadGeneration,
    pub(crate) final_flush: bool,
    pub(crate) global_offset: usize,
    pub(crate) skip_direct: SkipDirect,
    pub(crate) batched_base_routes: Option<&'a mut DirectRouteCounters>,
}

impl PatternMatcher {
    /// Process a partition slice and emit matches into `out`.
    /// The second result says whether the slice used only inline work before
    /// completing, so the caller can sample its completed-partition clock check.
    pub(crate) fn process_rows_collection(
        &mut self,
        scan: &mut ScanContext,
        mut input: ProcessRowsInput<'_>,
    ) -> Result<(ComputeStep, bool)> {
        let read_end_row = input.end_row;
        if let Some(candidate_end_row) = input.candidate_end_row {
            input.end_row = candidate_end_row;
        }
        let start_row = input.start_row;
        let end_row = input.end_row;
        let total_rows_in_collection = input.batches.num_rows();
        if start_row > end_row
            || end_row > read_end_row
            || read_end_row > total_rows_in_collection
        {
            return internal_err!(
                "invalid MATCH_RECOGNIZE collection range: start={start_row}, end={end_row}, read_end={read_end_row}, physical_rows={total_rows_in_collection}"
            );
        }

        self.run_windowed_collection(scan, &mut input, read_end_row)
    }
}

mod anchors;
pub(super) use anchors::AnchorWindows;
mod boundary;
mod candidates;
mod direct;
pub(crate) use direct::{ClosedDirectDriver, ClosedSegmentOutcome};
mod selected_output;
pub(crate) use selected_output::{SelectedOutputBuffer, SelectedOutputTransaction};
mod setup;