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.

mod checked_and_halo;
mod compact_cycle;
mod direct_and_batch;

use super::*;
use crate::core::{
    MatchSummaryField, NormalizedPattern, Pattern, RepetitionQuantifier, Symbol, SymbolId,
};
use crate::execution::matching::ExecutableDirectCountSummary;
use crate::execution::matching::path::Sym;
use datafusion::arrow::array::{
    Array, ArrayRef, BooleanArray, Int32Array, Int64Array, UInt32Array,
};
use datafusion::arrow::datatypes::{DataType, Field};
use datafusion::scalar::ScalarValue;

mod typed_reductions {
    include!("../reduction/tests.rs");
}

const MILLION_ROW_NEIGHBORS: [usize; 3] = [999_999, 1_000_000, 1_000_001];

fn single_column_input(field: Field, values: ArrayRef) -> (SchemaRef, BatchCollection) {
    let schema = Arc::new(Schema::new(vec![field]));
    let batch = RecordBatch::try_new(Arc::clone(&schema), vec![values]).unwrap();
    let batches = BatchCollection::try_new(vec![batch], Arc::clone(&schema)).unwrap();
    (schema, batches)
}

fn path_step(row: u64, sym: Sym) -> PathStep {
    PathStep {
        row: AbsoluteRow::new(row),
        sym,
        excluded: false,
    }
}

fn output_column<'a, T: Array + 'static>(batch: &'a RecordBatch, name: &str) -> &'a T {
    batch
        .column_by_name(name)
        .unwrap()
        .as_any()
        .downcast_ref()
        .unwrap()
}

fn direct_count_output(
    schema: &SchemaRef,
    automaton: &CompiledAutomaton,
    passthrough: Vec<usize>,
    counts: Vec<Option<SymbolId>>,
) -> Arc<ExecutableOutputPlan> {
    let fields = (0..counts.len())
        .map(|output_id| {
            MatchSummaryField::new(
                output_id,
                Arc::new(Field::new("count", DataType::Int64, false)),
            )
        })
        .collect::<Vec<_>>();
    ExecutableOutputPlan::try_direct_counts(
        schema.as_ref(),
        MatchRecognizeOutputSpec::new(passthrough, vec![], vec![]),
        Arc::from([]),
        fields
            .into_iter()
            .zip(counts)
            .map(|(field, symbol_id)| ExecutableDirectCountSummary::new(field, symbol_id))
            .collect(),
        automaton,
    )
    .unwrap()
}

struct NamedAccumulatorHarness {
    schema: SchemaRef,
    batches: BatchCollection,
    compiled: Arc<CompiledAutomaton>,
    rows_per_match: RowsPerMatch,
}

impl NamedAccumulatorHarness {
    fn new(
        value_name: &str,
        values: ArrayRef,
        symbols: BooleanArray,
        empty_matches: EmptyMatchesMode,
    ) -> Self {
        let schema = Arc::new(Schema::new(vec![
            Field::new(value_name, values.data_type().clone(), false),
            Field::new(crate::core::symbol_col_name("A"), DataType::Boolean, false),
        ]));
        let batch =
            RecordBatch::try_new(Arc::clone(&schema), vec![values, Arc::new(symbols)])
                .unwrap();
        let batches = BatchCollection::try_new(vec![batch], Arc::clone(&schema)).unwrap();
        let pattern = NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into())));
        let compiled =
            Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()]).unwrap());
        let rows_per_match = RowsPerMatch::AllRows(empty_matches);
        Self {
            schema,
            batches,
            compiled,
            rows_per_match,
        }
    }

    fn accumulator(
        &self,
        flush_threshold: usize,
        spec: MatchRecognizeOutputSpec,
        classifier_bitset_symbol_ids: &[SymbolId],
    ) -> MatchAccumulator {
        let output = ExecutableOutputPlan::try_rows(
            self.schema.as_ref(),
            spec,
            Arc::from(classifier_bitset_symbol_ids),
            self.rows_per_match.clone(),
            self.compiled.as_ref(),
        )
        .unwrap();
        MatchAccumulator::try_new_unbounded(
            Arc::clone(&self.compiled),
            flush_threshold,
            output,
        )
        .unwrap()
    }

    fn emission_context<'a>(
        &'a self,
        partition: Range<usize>,
        global_offset: usize,
        pending_output: &'a mut PendingOutput,
    ) -> MatchEmissionContext<'a> {
        MatchEmissionContext {
            partition,
            global_offset,
            batches: &self.batches,
            pending_output,
            history: None,
        }
    }
}

// Two symbols share one prepared Boolean column, as native CSE can arrange.
// The real Lane scanner chooses the supplied cycle, with A excluded.
fn compact_cycle_harness(
    rows: usize,
    origin: usize,
) -> (
    NamedAccumulatorHarness,
    crate::execution::matching::SelectedLane,
) {
    compact_cycle_harness_with_cycle(rows, origin, &["A", "B"])
}

fn compact_cycle_harness_with_cycle(
    rows: usize,
    origin: usize,
    cycle: &[&str],
) -> (
    NamedAccumulatorHarness,
    crate::execution::matching::SelectedLane,
) {
    use crate::execution::matching::{
        ResolvedAfterMatchSkip, ResolvedBoolColumn, SymbolColumn, static_test_program,
    };
    let mut test_case = NamedAccumulatorHarness::new(
        "id",
        Arc::new(Int64Array::from_iter_values(0..rows as i64)),
        BooleanArray::from(vec![true; rows]),
        EmptyMatchesMode::Show,
    );
    let pattern = NormalizedPattern::Ast(Pattern::Repetition(
        Box::new(Pattern::Concat(
            cycle
                .iter()
                .map(|&name| {
                    let symbol = Symbol::Named(name.into());
                    if name == "A" {
                        Pattern::Exclude(symbol)
                    } else {
                        Pattern::Symbol(symbol)
                    }
                })
                .collect(),
        )),
        RepetitionQuantifier::OneOrMore,
    ));
    test_case.compiled = Arc::new(
        CompiledAutomaton::compile(&pattern, &["A".into(), "B".into()]).unwrap(),
    );
    let output = ExecutableOutputPlan::try_rows(
        test_case.schema.as_ref(),
        MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
        Arc::from([]),
        test_case.rows_per_match.clone(),
        &test_case.compiled,
    )
    .unwrap();
    let program = static_test_program(
        Arc::clone(&test_case.schema),
        pattern,
        Arc::clone(&test_case.compiled),
        (1..=2)
            .map(|id| SymbolColumn {
                id: SymbolId::try_new(id, 3).unwrap(),
                column: ResolvedBoolColumn::new_validated(1),
            })
            .collect(),
        ResolvedAfterMatchSkip::PastLastRow,
        output,
        crate::planning::SymbolRelationships::default(),
    )
    .unwrap();
    let scan =
        crate::execution::matching::scan_test_lane(&program, &test_case.batches, origin);
    (test_case, scan)
}

/// Drive the shared compact transaction without exposing private rows.
fn prepare_compact_test(
    acc: &mut MatchAccumulator,
    id: u64,
    selected: &crate::execution::matching::row_loop::lane_scan::CompactSelection<'_>,
    mut emission: MatchEmissionContext<'_>,
    read: &mut reduction::ReadRegister<'_>,
) -> Result<PreparedMatchEmission> {
    let mut progress =
        acc.begin_compact_match(id, selected, &emission, &mut |_| Ok(()))?;
    loop {
        if let Some(done) = acc.prepare_compact_match_chunk_with_registers(
            &mut progress,
            selected,
            emission.reborrow(),
            read,
            &mut |_| Ok(()),
        )? {
            return Ok(done);
        }
    }
}