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.

//! Prove intervals of candidate starts impossible, then give the ordinary
//! driver the surviving starts and the entire readable input.

use super::*;
use crate::execution::classification::PackedAnchors;
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::matching::anchors::{
    AnchorBackoff, AnchorCutoff, AnchorJumps, AnchorProbe,
};
use datafusion::arrow::array::AsArray;
use datafusion::arrow::datatypes::UInt64Type;

type Head = (MatchPartitionId, CollectionHeadGeneration);

#[derive(Default)]
pub(in super::super) struct AnchorWindows {
    cutoff_backoff: AnchorBackoff,
    probe_backoff: AnchorBackoff,
    key: Option<(Head, usize, usize, bool)>,
    cutoff: Option<AnchorCutoff>,
    range_end: usize,
    batch: Option<PackedBatch>,
    candidate_end: usize,
}

struct PackedBatch {
    index: usize,
    base: usize,
    end: usize,
    sample: Option<(AnchorProbe, usize)>,
    jumps: AnchorJumps,
}

impl MatchAwareCandidates<'_, '_> {
    pub(super) fn drive_anchor_windows(
        &mut self,
        plan: &PackedAnchors,
        head: Head,
    ) -> Result<ComputeStep> {
        let key = (
            head,
            self.setup.provider_origin,
            self.read_end_row,
            self.setup.final_flush,
        );
        let original_end = self.end_row;
        let mut windows = std::mem::take(&mut self.matcher.services.anchors);
        let result = if windows.key != Some(key)
            && (!self.candidate_is_idle() || self.has_active_start())
        {
            // A growing head may already own a candidate which needs the newly
            // readable rows (including precedence or a pending NEXT measure).
            self.drive_window()
        } else {
            if windows.key != Some(key) {
                let rows = original_end.saturating_sub(self.row_idx);
                windows.key = Some(key);
                windows.cutoff = windows.cutoff_backoff.cutoff(rows).then(|| {
                    AnchorCutoff::new(
                        self.row_idx..original_end,
                        self.read_end_row,
                        self.setup.final_flush,
                        &plan.clauses,
                        plan.start_mask,
                    )
                });
                windows.range_end = original_end;
                windows.batch = None;
                windows.candidate_end = self.row_idx;
            }
            self.drive_packed_windows(plan, &mut windows, original_end)
        };
        self.matcher.services.anchors = windows;
        self.end_row = original_end;
        result
    }

    fn drive_packed_windows(
        &mut self,
        plan: &PackedAnchors,
        windows: &mut AnchorWindows,
        original_end: usize,
    ) -> Result<ComputeStep> {
        let input = self.setup.input_buffer;
        let origin = self.scan_ctx.partition.global_row_offset;
        if let Some(cutoff) = &mut windows.cutoff {
            loop {
                let governor = &mut self.scan_ctx.scan_state.governor;
                let range = cutoff.step(
                    &plan.clauses,
                    |row, work| {
                        let (index, offset) =
                            input.locate_with_work(row - origin, work)?;
                        let words = input
                            .batch(index)
                            .column(plan.column)
                            .as_primitive::<UInt64Type>()
                            .values();
                        Ok((row - offset, words.as_ref()))
                    },
                    &mut |n| governor.record_completed(n, || self.matcher.is_aborted()),
                )?;
                if let Some(range) = range {
                    let rows = original_end - self.row_idx;
                    windows
                        .cutoff_backoff
                        .finish_cutoff(rows, rows - range.len());
                    self.row_idx = self.row_idx.max(range.start);
                    windows.range_end = range.end;
                    windows.cutoff = None;
                    break;
                }
                if self.take_yield_if_due_hot() {
                    return self.yield_progress(ComputeStep::Yield);
                }
            }
        }
        if !plan.bounded_jump {
            windows.candidate_end = windows.range_end;
        }
        loop {
            if self.row_idx < windows.candidate_end {
                self.end_row = windows.candidate_end;
                let step = self.drive_window()?;
                if step != ComputeStep::Complete || self.row_idx < windows.candidate_end {
                    return Ok(step);
                }
            }
            if self.row_idx >= windows.range_end {
                self.end_row = original_end;
                self.row_idx = self.row_idx.max(original_end);
                return self.finish_window();
            }

            if windows.batch.as_ref().is_none_or(|b| self.row_idx >= b.end) {
                let governor = &mut self.scan_ctx.scan_state.governor;
                let (index, offset) = input
                    .locate_with_work(self.row_idx - origin, &mut |n| {
                        governor.record_completed(n, || self.matcher.is_aborted())
                    })?;
                let base = self.row_idx - offset;
                let end = (base + input.batch(index).num_rows()).min(self.read_end_row);
                let len = end - self.row_idx;
                let first_large = self.row_idx
                    == self.scan_ctx.partition.absolute_partition_start
                    && original_end - self.row_idx >= 65536;
                let probe = windows.probe_backoff.probe(len, first_large);
                windows.batch = Some(PackedBatch {
                    index,
                    base,
                    end,
                    sample: probe.then(|| (AnchorProbe::default(), self.row_idx)),
                    jumps: AnchorJumps::default(),
                });
            }
            let batch = windows.batch.as_mut().unwrap();
            let words = input
                .batch(batch.index)
                .column(plan.column)
                .as_primitive::<UInt64Type>()
                .values();
            if let Some((sample, position)) = &mut batch.sample {
                let start = *position - batch.base;
                sample.sample(
                    &words[start..start + COARSE_WORK_BATCH_SIZE],
                    &plan.clauses,
                    plan.start_mask,
                );
                self.scan_ctx
                    .scan_state
                    .governor
                    .record_completed(COARSE_WORK_BATCH_SIZE, || {
                        self.matcher.is_aborted()
                    })?;
                if *position == self.row_idx {
                    *position += (batch.end - self.row_idx) / 2;
                } else {
                    let anchor = sample.select(&plan.clauses, plan.start_mask);
                    windows.probe_backoff.finish_probe(anchor.is_some());
                    batch.jumps = AnchorJumps::new(anchor);
                    batch.sample = None;
                }
                if self.take_yield_if_due_hot() {
                    return self.yield_progress(ComputeStep::Yield);
                }
                continue;
            }
            let (next, scanned) = batch.jumps.step(
                &words[..batch.end - batch.base],
                batch.base,
                self.row_idx,
                windows.range_end,
                self.setup.final_flush && batch.end == self.read_end_row,
            );
            if let Some(range) = next {
                self.row_idx = range.start;
                windows.candidate_end = range.end;
            }
            if scanned == 0 {
                continue;
            }
            self.scan_ctx
                .scan_state
                .governor
                .record_completed(scanned, || self.matcher.is_aborted())?;
            if self.take_yield_if_due_hot() {
                return self.yield_progress(ComputeStep::Yield);
            }
        }
    }
}