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.

//! Deferred history preparation and lifetime tests.

use super::*;
use datafusion::arrow::array::Int32Array;
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryConsumer, MemoryPool};

fn make_batch(start: i32, count: i32) -> RecordBatch {
    let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
    RecordBatch::try_new(
        schema,
        vec![Arc::new(Int32Array::from(
            (start..start + count).collect::<Vec<_>>(),
        ))],
    )
    .unwrap()
}

fn get_values(collection: &BatchCollection) -> Vec<i32> {
    (0..collection.num_batches())
        .flat_map(|index| {
            collection
                .batch(index)
                .column(0)
                .as_any()
                .downcast_ref::<Int32Array>()
                .unwrap()
                .values()
                .to_vec()
        })
        .collect()
}

fn source_plan(
    collection: &BatchCollection,
    columns: &[usize],
) -> Result<DeferredSchemaColumnPlan> {
    DeferredSchemaColumnPlan::bind(
        Arc::new(collection.schema().project(columns)?),
        columns
            .iter()
            .copied()
            .map(super::super::compiler::HistorySource::Input),
    )
}

fn start_gather(
    plan: &DeferredSchemaColumnPlan,
    indices: Vec<usize>,
    head: usize,
    memory: &MemoryReservation,
) -> Result<HistoryPreparation> {
    HistoryPreparation::try_new(plan, indices, Vec::new(), head, memory.new_empty())
}

fn gather(
    collection: &BatchCollection,
    columns: &[usize],
    indices: Vec<usize>,
    head: usize,
) -> Result<(RecordBatch, MemoryReservation, usize)> {
    let memory = crate::execution::common::memory::new_unbounded_state_memory();
    let plan = source_plan(collection, columns)?;
    let mut gather = start_gather(&plan, indices, head, &memory)?;
    let mut work = 0;
    let mut completed = |units| {
        work += units;
        Ok(())
    };
    for _ in 0..4096 {
        if let Some(prepared) = gather.advance(&plan, collection, &mut completed)? {
            return Ok((prepared.batch, prepared.memory, work));
        }
    }
    panic!("history gather exceeded test_case work bound");
}

fn injected_work_failure(target_report: usize) -> impl FnMut(usize) -> Result<()> {
    let mut reports = 0;
    move |units| {
        assert!(units <= COARSE_WORK_BATCH_SIZE);
        reports += 1;
        if reports == target_report {
            Err(DataFusionError::Execution(
                "injected collection work failure".into(),
            ))
        } else {
            Ok(())
        }
    }
}

#[test]
fn deferred_gather_selects_columns_rows_and_zero_column_shape() {
    let schema = Arc::new(Schema::new_with_metadata(
        vec![
            Field::new("unused_left", DataType::Int32, false),
            Field::new("unused_right", DataType::Int32, false),
            Field::new("needed", DataType::Int32, false),
        ],
        [("source".to_string(), "history".to_string())],
    ));
    let batches = [0, 100]
        .into_iter()
        .map(|offset| {
            RecordBatch::try_new(
                Arc::clone(&schema),
                vec![
                    Arc::new(Int32Array::from(vec![1 + offset, 2 + offset, 3 + offset])),
                    Arc::new(Int32Array::from(vec![4 + offset, 5 + offset, 6 + offset])),
                    Arc::new(Int32Array::from(vec![7 + offset, 8 + offset, 9 + offset])),
                ],
            )
            .unwrap()
        })
        .collect();
    let collection = BatchCollection::try_new(batches, schema).unwrap();
    for (indices, columns, expected) in [
        (vec![0, 2, 3, 5], vec![2], vec![7, 9, 107, 109]),
        (vec![0, 2, 3, 5], vec![], vec![]),
        (vec![], vec![2], vec![]),
    ] {
        let rows = indices.len();
        let (batch, _lease, _) = gather(&collection, &columns, indices, 0).unwrap();
        assert_eq!(
            (batch.num_rows(), batch.num_columns()),
            (rows, columns.len())
        );
        assert_eq!(
            batch.schema_ref().metadata(),
            collection.schema().metadata()
        );
        if !columns.is_empty() {
            assert_eq!(batch.schema().field(0).name(), "needed");
            assert_eq!(
                batch
                    .column(0)
                    .as_any()
                    .downcast_ref::<Int32Array>()
                    .unwrap()
                    .values(),
                expected.as_slice()
            );
        }
    }
}

#[test]
fn history_gather_work_is_independent_of_batches_outside_the_selected_span() {
    // Both inputs require rebasing. More unused batches must add no gather work.
    let [small_work, large_work] = [1, 64].map(|padding| {
        let mut batches = vec![make_batch(-1, 1); padding];
        batches.extend([make_batch(10, 2), make_batch(20, 2)]);
        batches.extend(std::iter::repeat_n(make_batch(-2, 1), padding));
        let schema = batches[0].schema();
        let collection = BatchCollection::try_new(batches, schema).unwrap();
        let indices = vec![padding + 3, padding + 1, padding + 3];
        let (batch, _lease, work) = gather(&collection, &[0], indices, 0).unwrap();
        assert_eq!(
            batch
                .column(0)
                .as_any()
                .downcast_ref::<Int32Array>()
                .unwrap()
                .values(),
            &[21, 11, 21]
        );
        work
    });
    assert_eq!(small_work, large_work);
}

#[test]
fn history_gather_preserves_rows_and_memory_across_resumption() -> Result<()> {
    let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(16 * 1024 * 1024));
    let memory = MemoryConsumer::new("history-gather-test").register(&pool);
    const ROWS: i32 = COARSE_WORK_BATCH_SIZE as i32 + 1;
    let collection = BatchCollection::try_new(
        vec![make_batch(0, 32), make_batch(32, ROWS - 32)],
        make_batch(0, 1).schema(),
    )?;
    let plan = source_plan(&collection, &[0])?;
    let mut preparing =
        start_gather(&plan, (0..ROWS as usize).rev().collect(), 0, &memory)?;
    preparing
        .advance(&plan, &collection, &mut injected_work_failure(2))
        .expect_err("coordinate preparation must propagate cancellation");
    let mut pauses = 0;
    let prepared = loop {
        if let Some(prepared) = preparing.advance(&plan, &collection, &mut |_| Ok(()))? {
            break prepared;
        }
        pauses += 1;
    };
    assert!(pauses > 0);
    let values = prepared
        .batch
        .column(0)
        .as_any()
        .downcast_ref::<Int32Array>()
        .unwrap();
    let expected = (0..ROWS).rev().collect::<Vec<_>>();
    assert_eq!(values.values(), expected.as_slice());
    assert_eq!(pool.reserved(), prepared.memory.size());
    assert_eq!(
        prepared.memory.size(),
        prepared.batch.column(0).get_array_memory_size()
    );
    drop(prepared);
    drop(preparing);
    assert_eq!(pool.reserved(), 0);
    Ok(())
}

#[test]
fn history_gather_pool_denial_releases_owned_scratch() -> Result<()> {
    const LIMIT: usize = 4096;
    let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(LIMIT));
    let memory = MemoryConsumer::new("history-gather-denial").register(&pool);
    let collection =
        BatchCollection::try_new(vec![make_batch(0, 3)], make_batch(0, 1).schema())?;
    let plan = source_plan(&collection, &[0])?;
    let mut preparing = start_gather(&plan, vec![0, 2], 0, &memory)?;
    assert!(
        preparing
            .advance(&plan, &collection, &mut |_| Ok(()))?
            .is_none()
    );
    let blocker = memory.new_empty();
    blocker.try_grow(LIMIT - pool.reserved() - 1)?;
    let error = preparing
        .advance(&plan, &collection, &mut |_| Ok(()))
        .expect_err("interleaved array must be admitted before publication");
    assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
    drop(preparing);
    assert_eq!(pool.reserved(), blocker.size());
    drop(blocker);
    assert_eq!(get_values(&collection), [0, 1, 2]);
    assert_eq!(pool.reserved(), 0);
    Ok(())
}

#[test]
fn metadata_only_history_does_not_locate_source_rows() -> Result<()> {
    let collection =
        BatchCollection::try_new(vec![make_batch(0, 1)], make_batch(0, 1).schema())?;
    // Deliberately invalid coordinates: a zero-column gather needs only the row count.
    let (batch, _lease, work) = gather(&collection, &[], vec![usize::MAX; 3], 0)?;
    assert_eq!(batch.num_rows(), 3);
    assert_eq!(batch.num_columns(), 0);
    assert_eq!(work, 0);
    Ok(())
}

#[test]
fn absolute_history_gather_checks_normal_and_wide_origins() {
    let collection =
        BatchCollection::try_new(vec![make_batch(20, 3)], make_batch(0, 1).schema())
            .unwrap();
    #[cfg(not(target_pointer_width = "64"))]
    let heads = [10];
    #[cfg(target_pointer_width = "64")]
    let heads = [10, u32::MAX as usize + 100];
    for head in heads {
        let (batch, _lease, _) =
            gather(&collection, &[0], vec![head, head + 2], head).unwrap();
        assert_eq!(
            batch
                .column(0)
                .as_any()
                .downcast_ref::<Int32Array>()
                .unwrap()
                .values(),
            &[20, 22]
        );
        for (index, diagnostic) in [
            (head - 1, "precedes collection head"),
            (head + 3, "outside a collection"),
        ] {
            let error = gather(&collection, &[0], vec![index], head).unwrap_err();
            assert!(error.to_string().contains(diagnostic), "{error}");
        }
    }
}