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.

//! Test automatic buffering through the public SQL installer and runtime pool.

#![cfg(feature = "sql")]

use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use datafusion::arrow::array::Int32Array;
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::arrow::util::display::array_value_to_string;
use datafusion::common::tree_node::{Transformed, TreeNode};
use datafusion::datasource::MemTable;
use datafusion::execution::SessionStateBuilder;
use datafusion::execution::memory_pool::{
    GreedyMemoryPool, MemoryPool, MemoryReservation, UnboundedMemoryPool,
};
use datafusion::execution::runtime_env::RuntimeEnvBuilder;
use datafusion::physical_plan::execution_plan::reset_plan_states;
use datafusion::physical_plan::limit::GlobalLimitExec;
use datafusion::physical_plan::{
    ChildrenPropertiesMode, ExecutionPlan, ExecutionPlanProperties,
    ReplaceChildrenOptions, collect, displayable,
};
use datafusion::prelude::{SessionConfig, SessionContext};
use datafusion_match_recognize::{
    MatchRecognizeConfig, advanced, new_match_recognize_context,
};

const MATCHES: &str = "SELECT p, mn, first_seq, last_seq, n FROM ticks
    MATCH_RECOGNIZE (PARTITION BY p ORDER BY seq
      MEASURES MATCH_NUMBER() AS mn, FIRST(seq) AS first_seq,
        LAST(seq) AS last_seq, COUNT(*) AS n
      ONE ROW PER MATCH PATTERN (A+) DEFINE A AS v > 0)";
const EXPECTED: [&str; 3] = ["1 1 1 2 2", "1 2 4 4 1", "2 1 1 3 3"];

// A host pool can account memory without declaring whether its limit is finite.
#[derive(Debug, Default)]
struct UnknownPool(UnboundedMemoryPool);
impl fmt::Display for UnknownPool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "UnknownPool")
    }
}
impl MemoryPool for UnknownPool {
    fn name(&self) -> &str {
        "UnknownPool"
    }
    fn grow(&self, reservation: &MemoryReservation, bytes: usize) {
        self.0.grow(reservation, bytes);
    }
    fn shrink(&self, reservation: &MemoryReservation, bytes: usize) {
        self.0.shrink(reservation, bytes);
    }
    fn try_grow(
        &self,
        reservation: &MemoryReservation,
        bytes: usize,
    ) -> datafusion::common::Result<()> {
        self.0.try_grow(reservation, bytes)
    }
    fn reserved(&self) -> usize {
        self.0.reserved()
    }
}

fn context(pool: Arc<dyn MemoryPool>, partitions: usize) -> SessionContext {
    let mut config = SessionConfig::new()
        .with_target_partitions(partitions)
        .with_batch_size(4);
    // Retain grouped input with two workers rather than the default minimum four.
    config.options_mut().optimizer.subset_repartition_threshold = 1;
    config
        .options_mut()
        .extensions
        .insert(MatchRecognizeConfig::default());
    let runtime = RuntimeEnvBuilder::new()
        .with_memory_pool(pool)
        .build()
        .unwrap();
    let ctx = new_match_recognize_context(
        SessionStateBuilder::new()
            .with_default_features()
            .with_config(config)
            .with_runtime_env(Arc::new(runtime)),
    )
    .unwrap();
    let schema = Arc::new(Schema::new(
        ["p", "seq", "v"].map(|name| Arc::new(Field::new(name, DataType::Int32, false))),
    ));
    let partitions = [
        (1, vec![1, 2, 3, 4], vec![10, 11, 0, 12]),
        (2, vec![1, 2, 3], vec![20, 21, 22]),
    ]
    .into_iter()
    .map(|(key, seq, values)| {
        vec![
            RecordBatch::try_new(
                Arc::clone(&schema),
                vec![
                    Arc::new(Int32Array::from(vec![key; seq.len()])),
                    Arc::new(Int32Array::from(seq)),
                    Arc::new(Int32Array::from(values)),
                ],
            )
            .unwrap(),
        ]
    })
    .collect();
    ctx.register_table(
        "ticks",
        Arc::new(MemTable::try_new(schema, partitions).unwrap()),
    )
    .unwrap();
    ctx
}

async fn plan(ctx: &SessionContext, sql: &str) -> Arc<dyn ExecutionPlan> {
    ctx.sql(sql)
        .await
        .unwrap()
        .create_physical_plan()
        .await
        .unwrap()
}

async fn rows(ctx: &SessionContext, physical: Arc<dyn ExecutionPlan>) -> Vec<String> {
    let batches =
        tokio::time::timeout(Duration::from_secs(15), collect(physical, ctx.task_ctx()))
            .await
            .expect("buffered matching must make progress")
            .unwrap();
    batches
        .iter()
        .flat_map(|batch| {
            (0..batch.num_rows()).map(|row| {
                batch
                    .columns()
                    .iter()
                    .map(|column| array_value_to_string(column.as_ref(), row).unwrap())
                    .collect::<Vec<_>>()
                    .join(" ")
            })
        })
        .collect()
}

fn buffered_bytes(physical: &Arc<dyn ExecutionPlan>) -> usize {
    let own = if physical.name() == "MatchRecognizeBufferExec" {
        physical
            .metrics()
            .and_then(|metrics| metrics.sum_by_name("max_mem_used"))
            .map_or(0, |value| value.as_usize())
    } else {
        0
    };
    own + physical
        .children()
        .iter()
        .map(|child| buffered_bytes(child))
        .sum::<usize>()
}

#[tokio::test]
async fn sql_merge_buffer_preserves_order_and_skips_fetch_sorts_and_plain_queries() {
    let ctx = context(Arc::new(UnboundedMemoryPool::default()), 2);
    for (sql, buffered, expected) in [
        (format!("{MATCHES} ORDER BY p, mn"), true, EXPECTED.to_vec()),
        (
            format!("{MATCHES} ORDER BY p, mn LIMIT 1"),
            false,
            vec![EXPECTED[0]],
        ),
        (
            format!("{MATCHES} ORDER BY n DESC, p, mn"),
            false,
            vec![EXPECTED[2], EXPECTED[0], EXPECTED[1]],
        ),
        (
            "SELECT p, seq FROM ticks ORDER BY p, seq".to_owned(),
            false,
            vec!["1 1", "1 2", "1 3", "1 4", "2 1", "2 2", "2 3"],
        ),
    ] {
        let physical = plan(&ctx, &sql).await;
        let display = displayable(physical.as_ref()).indent(true).to_string();
        assert_eq!(
            display.contains("MatchRecognizeBufferExec"),
            buffered,
            "{sql}\n{display}"
        );
        assert_eq!(rows(&ctx, physical).await, expected, "{sql}");
    }
    let explain = plan(&ctx, &format!("EXPLAIN {MATCHES} ORDER BY p, mn")).await;
    assert!(rows(&ctx, explain).await.join("\n").contains(
        "MatchRecognizeBufferExec: capacity=268435456, memory=headroom-bounded"
    ));

    {
        let sql = format!(
            "{} ORDER BY p, mn",
            MATCHES.replace("v > 0", "COUNT(A.*) <= 2")
        );
        let physical = plan(&ctx, &sql).await;
        assert!(
            displayable(physical.as_ref())
                .indent(true)
                .to_string()
                .contains("MatchRecognizeBufferExec")
        );
        assert_eq!(
            rows(&ctx, physical).await,
            ["1 1 1 2 2", "1 2 3 4 2", "2 1 1 2 2", "2 2 3 3 1"]
        );
    }
}

#[tokio::test]
async fn planned_merge_buffer_checks_the_execution_pool_not_the_planning_pool() {
    let pools: [(Arc<dyn MemoryPool>, bool); 4] = [
        (Arc::new(UnboundedMemoryPool::default()), true),
        // Large finite pool: 32 MiB / 8 = 4 MiB aggregate (2 MiB/partition >= 64 KiB).
        (Arc::new(GreedyMemoryPool::new(32 * 1024 * 1024)), true),
        // Tiny finite pool: 256 KiB / 8 = 32 KiB aggregate (16 KiB/partition < 64 KiB) -> bypass.
        (Arc::new(GreedyMemoryPool::new(256 * 1024)), false),
        (Arc::new(UnknownPool::default()), false),
    ];
    for (pool, should_buffer) in pools {
        // Every plan starts in an unlimited session. Its TaskContext can belong
        // to a different host with a finite or undeclared memory limit.
        let planning = context(Arc::new(UnboundedMemoryPool::default()), 2);
        let physical = plan(&planning, &format!("{MATCHES} ORDER BY p, mn")).await;
        assert!(
            displayable(physical.as_ref())
                .indent(true)
                .to_string()
                .contains("MatchRecognizeBufferExec")
        );
        let executing = context(Arc::clone(&pool), 2);
        assert_eq!(rows(&executing, Arc::clone(&physical)).await, EXPECTED);
        assert_eq!(buffered_bytes(&physical) > 0, should_buffer);
        assert_eq!(pool.reserved(), 0);
    }
}

#[tokio::test]
async fn bounded_merge_buffer_degrades_cleanly_under_heavy_pool_pressure() {
    use datafusion::execution::memory_pool::MemoryConsumer;

    let limit = 32 * 1024 * 1024;
    let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
    let ctx = context(Arc::clone(&pool), 2);
    let physical = plan(&ctx, &format!("{MATCHES} ORDER BY p, mn")).await;
    // Pin > 75% of the pool (leaving ~2 MiB for matcher/sort execution) so the
    // buffer's headroom gate suppresses speculative lookahead without failing.
    let external = MemoryConsumer::new("external_pressure").register(&pool);
    external.try_grow(limit - 2 * 1024 * 1024).unwrap();
    assert_eq!(rows(&ctx, Arc::clone(&physical)).await, EXPECTED);
    drop(external);
    assert_eq!(pool.reserved(), 0);
}

#[tokio::test]
async fn public_rule_preserves_rows_properties_and_guards_when_plans_are_rebuilt() {
    let ctx = context(Arc::new(UnboundedMemoryPool::default()), 2);
    let sql = format!("{MATCHES} ORDER BY p, mn");
    let unbuffered = plan(&ctx, &sql)
        .await
        .transform_up(|physical| {
            if physical.name() == "MatchRecognizeBufferExec" {
                Ok(Transformed::yes(Arc::clone(physical.children()[0])))
            } else {
                Ok(Transformed::no(physical))
            }
        })
        .unwrap()
        .data;
    let rule = advanced::physical_optimizer_rule();
    let options = ctx.state().config_options().clone();
    let plain = plan(&ctx, "SELECT p, seq FROM ticks ORDER BY p, seq").await;
    let unchanged = rule.optimize(Arc::clone(&plain), &options).unwrap();
    assert!(Arc::ptr_eq(&plain, &unchanged));
    let buffered = rule.optimize(Arc::clone(&unbuffered), &options).unwrap();
    let twice = rule.optimize(Arc::clone(&buffered), &options).unwrap();
    assert_eq!(
        displayable(twice.as_ref())
            .indent(true)
            .to_string()
            .matches("MatchRecognizeBufferExec")
            .count(),
        1
    );
    assert_eq!(buffered.schema(), unbuffered.schema());
    assert_eq!(
        buffered.output_partitioning().partition_count(),
        unbuffered.output_partitioning().partition_count()
    );
    assert_eq!(buffered.output_ordering(), unbuffered.output_ordering());
    // Exchanges own consumable channels; each execution needs fresh plan state.
    assert_eq!(
        rows(&ctx, reset_plan_states(Arc::clone(&unbuffered)).unwrap()).await,
        EXPECTED
    );
    assert_eq!(
        rows(&ctx, reset_plan_states(Arc::clone(&buffered)).unwrap()).await,
        EXPECTED
    );

    let rebuilt = buffered
        .transform_up(|physical| {
            if physical.name() == "MatchRecognizeBufferExec" {
                let children = physical.children().into_iter().cloned().collect();
                let replacement = physical.replace_children(
                    children,
                    ReplaceChildrenOptions::new(ChildrenPropertiesMode::Keep),
                )?;
                assert_eq!(replacement.name(), "MatchRecognizeBufferExec");
                Ok(Transformed::yes(replacement))
            } else {
                Ok(Transformed::no(physical))
            }
        })
        .unwrap()
        .data;
    assert_eq!(
        rows(&ctx, reset_plan_states(rebuilt).unwrap()).await,
        EXPECTED
    );

    let limited: Arc<dyn ExecutionPlan> =
        Arc::new(GlobalLimitExec::new(unbuffered, 0, Some(1)));
    let limited = rule.optimize(limited, &options).unwrap();
    assert!(
        !displayable(limited.as_ref())
            .indent(true)
            .to_string()
            .contains("MatchRecognizeBufferExec")
    );
    assert_eq!(
        rows(&ctx, reset_plan_states(limited).unwrap()).await,
        [EXPECTED[0]]
    );

    let sequential = context(Arc::new(UnboundedMemoryPool::default()), 1);
    let physical = plan(&sequential, &sql).await;
    assert!(
        !displayable(physical.as_ref())
            .indent(true)
            .to_string()
            .contains("MatchRecognizeBufferExec")
    );
    assert_eq!(rows(&sequential, physical).await, EXPECTED);
}