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.

//! Match-aware replay and candidate processing for a selected input head.

use super::physical_segmentation_helper::{
    drain_until_input_or_end, gated_test_stream, primitive_values, repeated,
    symbol_batch, symbol_schema,
};
use crate::config::MatchRecognizeConfig;
use crate::core::{
    EmptyMatchesMode, MatchMetadataColumn, MatchRecognizeOutputSpec, NormalizedPattern,
    RepetitionQuantifier, RowsPerMatch, SymbolId,
};
use crate::execution::common::scheduling::SliceControl;
use crate::execution::matching::build_test_executable;
use crate::execution::matching::{
    ExecutableMatchProgram, OutputPartitionBindings, PatternMatcher,
    ResolvedAfterMatchSkip,
};
use crate::execution::metrics::PatternMetrics;
use crate::execution::storage::buffer::PartitionedBuffer;
use crate::execution::stream::MatchInput;
use crate::execution::stream::{matcher_stream, stateful_stream::AwareEngine};
use crate::nfa::CompiledAutomaton;
use datafusion::arrow::array::{BooleanArray, UInt32Array};
use datafusion::arrow::datatypes::{Int64Type, SchemaRef, UInt32Type};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion_common::Result;
use datafusion_execution::TaskContext;
use datafusion_execution::memory_pool::MemoryConsumer;
use datafusion_execution::memory_pool::{GreedyMemoryPool, MemoryPool};
use datafusion_execution::runtime_env::RuntimeEnvBuilder;
use datafusion_hash_grouped_order::{GroupedBatch, GroupedBatchStream, PartitionRange};
use datafusion_physical_expr::expressions::Column;
use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
use datafusion_physical_plan::SendableRecordBatchStream;
use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
use futures::channel::mpsc::{UnboundedReceiver, unbounded};
use futures::{Stream, StreamExt};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::{Context, Poll};

const MIN_MATCH_ROWS: usize = 10;
const FLUSH_THRESHOLD: usize = 4;

struct GatedGroupedStream {
    schema: SchemaRef,
    rx: UnboundedReceiver<Result<GroupedBatch>>,
    waits: Arc<AtomicUsize>,
}

impl Stream for GatedGroupedStream {
    type Item = Result<GroupedBatch>;

    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        let next = self.rx.poll_next_unpin(cx);
        if next.is_pending() {
            self.waits.fetch_add(1, Ordering::Relaxed);
        }
        next
    }
}

impl GroupedBatchStream for GatedGroupedStream {
    fn schema(&self) -> SchemaRef {
        Arc::clone(&self.schema)
    }
}

fn build_program(
    schema: &SchemaRef,
    id_col: usize,
) -> Result<(Arc<ExecutableMatchProgram>, PatternMatcher)> {
    let pattern = NormalizedPattern::Ast(repeated(
        "A",
        RepetitionQuantifier::Exactly(u32::try_from(MIN_MATCH_ROWS).unwrap()),
    ));
    let names = vec!["A".to_string()];
    let automaton = Arc::new(CompiledAutomaton::compile(&pattern, &names)?);
    assert_eq!(automaton.min_match_rows(), MIN_MATCH_ROWS);
    let classifier_id = SymbolId::try_new(1, automaton.num_symbols()).unwrap();
    let output_spec = MatchRecognizeOutputSpec::new(
        vec![id_col],
        vec![MatchMetadataColumn::MatchNumber],
        vec!["A".into()],
    );
    let program = Arc::new(build_test_executable(
        Arc::clone(schema),
        pattern,
        Arc::clone(&automaton),
        |input| {
            input.replace_output(output_spec, Arc::from([classifier_id]));
            input.set_rows_per_match(RowsPerMatch::AllRows(EmptyMatchesMode::Show));
            input.after_match_skip = ResolvedAfterMatchSkip::PastLastRow;
            input.max_define_lookahead_rows = crate::core::NavigationOffset::ZERO;
            input.has_deferred_history_operations = false;
        },
    )?);
    let matcher = PatternMatcher::from_executable(
        program.as_ref(),
        &MatchRecognizeConfig::default(),
    );
    Ok((program, matcher))
}

fn make_task_context() -> (Arc<dyn MemoryPool>, Arc<TaskContext>) {
    let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
    let runtime = Arc::new(
        RuntimeEnvBuilder::new()
            .with_memory_pool(Arc::clone(&pool))
            .build()
            .unwrap(),
    );
    (pool, Arc::new(TaskContext::default().with_runtime(runtime)))
}

fn assert_match_one(batches: &[RecordBatch]) {
    let ids: Vec<u32> = primitive_values::<UInt32Type>(batches, 0)
        .into_iter()
        .map(Option::unwrap)
        .collect();
    let match_numbers: Vec<i64> = primitive_values::<Int64Type>(batches, 1)
        .into_iter()
        .map(Option::unwrap)
        .collect();
    assert_eq!(ids, (1..=10).collect::<Vec<_>>());
    assert_eq!(match_numbers, vec![1; MIN_MATCH_ROWS]);
}

#[test]
fn open_candidate_emits_before_eof_when_min_match_rows_exceeds_flush_threshold()
-> Result<()> {
    let head1_flags = [false, true, true, true, true, true, true, true, true, true];
    let head1_ids: Vec<u32> = (0..10).collect();

    // 1. Unpartitioned stream: head 1 retains a 9-row candidate; a full 4-row
    //    continuation batch (< min_match_rows) must still emit match [1..=10]
    //    immediately before EOF.
    {
        let schema = symbol_schema(&["id"], &["A"]);
        let (program, matcher) = build_program(&schema, 0)?;
        let (pool, task_context) = make_task_context();
        let metrics = PatternMetrics::new_stateful(&ExecutionPlanMetricsSet::new(), 0);
        let buffer = PartitionedBuffer::new(Arc::clone(&schema), vec![], FLUSH_THRESHOLD);
        let (source, waits, mut stream) = gated_test_stream(
            buffer,
            &[],
            matcher,
            program.as_ref(),
            task_context,
            &metrics,
            FLUSH_THRESHOLD,
            SliceControl::default(),
            None,
        )?;

        source
            .unbounded_send(Ok(symbol_batch(
                &schema,
                [UInt32Array::from(head1_ids.clone())],
                [BooleanArray::from(head1_flags.to_vec())],
            )))
            .unwrap();
        let mut before_match = Vec::new();
        drain_until_input_or_end(&mut stream, &waits, false, &mut before_match)?;
        assert!(before_match.is_empty());

        source
            .unbounded_send(Ok(symbol_batch(
                &schema,
                [UInt32Array::from(vec![10, 11, 12, 13])],
                [BooleanArray::from(vec![true; 4])],
            )))
            .unwrap();
        let mut emitted = Vec::new();
        drain_until_input_or_end(&mut stream, &waits, false, &mut emitted)?;
        assert_match_one(&emitted);

        source.close_channel();
        let mut tail = Vec::new();
        drain_until_input_or_end(&mut stream, &waits, true, &mut tail)?;
        assert!(tail.is_empty());
        drop((emitted, tail, stream));
        assert_eq!(pool.reserved(), 0);
    }

    // 2. Partitioned stream: splitting the 4-row continuation into [2, 2]
    //    must emit before EOF identically to a single 4-row continuation batch.
    for continuation in [std::slice::from_ref(&(10..14)), &[10..12, 12..14]] {
        let schema = symbol_schema(&["partition", "id"], &["A"]);
        let sort_keys = vec![PhysicalSortExpr::new_default(Arc::new(Column::new(
            "partition",
            0,
        )))];
        let (program, matcher) = build_program(&schema, 1)?;
        let (pool, task_context) = make_task_context();
        let metrics = PatternMetrics::new_stateful(&ExecutionPlanMetricsSet::new(), 0);
        let buffer = PartitionedBuffer::new(
            Arc::clone(&schema),
            sort_keys.clone(),
            FLUSH_THRESHOLD,
        );
        let (source, waits, mut stream) = gated_test_stream(
            buffer,
            &sort_keys,
            matcher,
            program.as_ref(),
            task_context,
            &metrics,
            FLUSH_THRESHOLD,
            SliceControl::default(),
            None,
        )?;

        source
            .unbounded_send(Ok(symbol_batch(
                &schema,
                [
                    UInt32Array::from(vec![1; head1_ids.len()]),
                    UInt32Array::from(head1_ids.clone()),
                ],
                [BooleanArray::from(head1_flags.to_vec())],
            )))
            .unwrap();
        let mut emitted = Vec::new();
        drain_until_input_or_end(&mut stream, &waits, false, &mut emitted)?;
        assert!(emitted.is_empty());

        for (idx, range) in continuation.iter().enumerate() {
            let ids: Vec<u32> = range.clone().collect();
            let len = ids.len();
            source
                .unbounded_send(Ok(symbol_batch(
                    &schema,
                    [UInt32Array::from(vec![1; len]), UInt32Array::from(ids)],
                    [BooleanArray::from(vec![true; len])],
                )))
                .unwrap();
            drain_until_input_or_end(&mut stream, &waits, false, &mut emitted)?;
            if idx + 1 < continuation.len() {
                assert!(emitted.is_empty());
            }
        }
        assert_match_one(&emitted);

        source.close_channel();
        let mut tail = Vec::new();
        drain_until_input_or_end(&mut stream, &waits, true, &mut tail)?;
        assert!(tail.is_empty());
        drop((emitted, tail, stream));
        assert_eq!(pool.reserved(), 0);
    }

    // 3. Grouped stream: an open continuation batch (`open_start < origin`)
    //    sets `same_key = true` and must still emit as soon as flush_threshold
    //    is reached.
    {
        let schema = symbol_schema(&["partition", "id"], &["A"]);
        let sort_keys = vec![PhysicalSortExpr::new_default(Arc::new(Column::new(
            "partition",
            0,
        )))];
        let (program, matcher) = build_program(&schema, 1)?;
        let (pool, task_context) = make_task_context();
        let metrics = PatternMetrics::new_stateful(&ExecutionPlanMetricsSet::new(), 0);
        let buffer = PartitionedBuffer::new(
            Arc::clone(&schema),
            sort_keys.clone(),
            FLUSH_THRESHOLD,
        );
        let bindings = OutputPartitionBindings::try_new(
            &schema,
            program.output_plan(),
            sort_keys.iter().map(|key| Arc::clone(&key.expr)),
        )?;
        let memory = MemoryConsumer::new("grouped-streaming-regression")
            .register(&task_context.runtime_env().memory_pool);
        let slice = SliceControl::default();
        let input_batch_size = task_context.session_config().batch_size();
        let engine = AwareEngine::try_new(
            buffer,
            matcher,
            program.as_ref(),
            task_context,
            0,
            metrics.clone(),
            bindings,
            FLUSH_THRESHOLD,
            slice.clone(),
            1,
            None,
            Arc::new(memory),
        )?;
        let (tx, rx) = unbounded();
        let waits = Arc::new(AtomicUsize::new(0));
        let grouped_input = MatchInput::Grouped(Box::pin(GatedGroupedStream {
            schema: Arc::clone(&schema),
            rx,
            waits: Arc::clone(&waits),
        }));
        let mut stream: SendableRecordBatchStream = Box::pin(matcher_stream(
            engine,
            None,
            slice,
            Arc::clone(program.output_schema()),
            metrics.clone(),
            grouped_input,
            input_batch_size,
        ));

        tx.unbounded_send(Ok(GroupedBatch {
            batch: symbol_batch(
                &schema,
                [
                    UInt32Array::from(vec![1; head1_ids.len()]),
                    UInt32Array::from(head1_ids),
                ],
                [BooleanArray::from(head1_flags.to_vec())],
            ),
            partition_ranges: vec![PartitionRange {
                start: 0,
                end: 10,
                is_complete: false,
            }],
        }))
        .unwrap();
        let mut emitted = Vec::new();
        drain_until_input_or_end(&mut stream, &waits, false, &mut emitted)?;
        assert!(emitted.is_empty());

        tx.unbounded_send(Ok(GroupedBatch {
            batch: symbol_batch(
                &schema,
                [
                    UInt32Array::from(vec![1; 4]),
                    UInt32Array::from(vec![10, 11, 12, 13]),
                ],
                [BooleanArray::from(vec![true; 4])],
            ),
            partition_ranges: vec![PartitionRange {
                start: 0,
                end: 4,
                is_complete: false,
            }],
        }))
        .unwrap();
        drain_until_input_or_end(&mut stream, &waits, false, &mut emitted)?;
        assert_match_one(&emitted);

        // Close the grouped partition cleanly before EOF.
        tx.unbounded_send(Ok(GroupedBatch {
            batch: symbol_batch(
                &schema,
                [UInt32Array::from(vec![1]), UInt32Array::from(vec![14])],
                [BooleanArray::from(vec![false])],
            ),
            partition_ranges: vec![PartitionRange {
                start: 0,
                end: 1,
                is_complete: true,
            }],
        }))
        .unwrap();
        tx.close_channel();
        let mut tail = Vec::new();
        drain_until_input_or_end(&mut stream, &waits, true, &mut tail)?;
        assert!(tail.is_empty());
        drop((emitted, tail, stream));
        assert_eq!(pool.reserved(), 0);
    }

    Ok(())
}