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.

//! SQL `MATCH_RECOGNIZE` for Apache DataFusion.
//!
//! This is the main application crate. [`new_match_recognize_context`] installs
//! the functions, planners, and optimizer rules required by the extension and
//! returns a new DataFusion context. [`MatchRecognizeConfig`] controls compile
//! and runtime limits when an application needs values other than the defaults.
//!
//! # Install the extension
//!
//! Applications must depend on the matching official Apache DataFusion `55`
//! release line from crates.io. See [Add the extension to an application] for
//! the dependency declaration.
//!
//! ```rust,no_run
//! use datafusion::execution::SessionStateBuilder;
//! use datafusion_match_recognize::new_match_recognize_context;
//!
//! # fn build() -> datafusion::error::Result<()> {
//! let builder = SessionStateBuilder::new().with_default_features();
//! let ctx = new_match_recognize_context(builder)?;
//! # let _ = ctx;
//! # Ok(())
//! # }
//! ```
//!
//! Register tables and run queries on the returned context. The installer
//! preserves the builder's configuration and extensions, replaces its query
//! planner, and appends the required optimizer rules. See
//! [`new_match_recognize_context`] for the registration order, replaced function
//! registrations, duplicate-installation behavior, and possible errors. An
//! already-created `SessionContext` is not modified in place.
//!
//! # Cargo features
//!
//! - `sql` (default) installs the adapter that turns `MATCH_RECOGNIZE` SQL into
//!   a DataFusion logical plan. Without it, applications build plans directly
//!   through [`planning`] or supply them through another integration.
//! - `substrait` exposes this package's Substrait import and export helpers in
//!   the `substrait` module.
//!
//! The [`advanced`] module exposes unstable component-by-component registration
//! for hosts that cannot use the normal installer. Applications that build
//! patterns directly in Rust use [`planning`] rather than those hooks.
//!
//! # Guides and reference
//!
//! - [Run the example and its assertions]
//! - [Add the extension to an application]
//! - [Build a row pattern step by step]
//! - [Check SQL support]
//! - [Review configuration and feature combinations]
//! - [Evaluate a production workload]
//!
//! These web links follow the current `main` branch. When using a pinned
//! revision, read the corresponding files and Rustdoc from that checkout.
//!
//! [Run the example and its assertions]: https://github.com/datafusion-contrib/datafusion-match-recognize/blob/main/docs/getting_started.md
//! [Add the extension to an application]: https://github.com/datafusion-contrib/datafusion-match-recognize/blob/main/docs/integration.md
//! [Build a row pattern step by step]: https://github.com/datafusion-contrib/datafusion-match-recognize/blob/main/docs/sql/README.md
//! [Check SQL support]: https://github.com/datafusion-contrib/datafusion-match-recognize/blob/main/docs/sql/reference.md
//! [Review configuration and feature combinations]: https://github.com/datafusion-contrib/datafusion-match-recognize/blob/main/match-recognize/README.md
//! [Evaluate a production workload]: https://github.com/datafusion-contrib/datafusion-match-recognize/blob/main/docs/production_evaluation.md

use std::sync::Arc;

use datafusion::execution::{SessionState, SessionStateBuilder};
use datafusion::prelude::SessionContext;

/// Session settings used by physical planning and execution.
pub mod config;
pub mod planning;
#[cfg(feature = "substrait")]
pub mod substrait;

pub(crate) mod compat;
pub(crate) mod core;
pub(crate) mod execution;
pub(crate) mod functions;
pub(crate) mod nfa;
pub(crate) mod nfa_executor;
mod optimizer;
#[cfg(feature = "sql")]
pub(crate) mod sql;

pub use config::MatchRecognizeConfig;

use execution::physical::{
    MatchRecognizeQueryPlanner,
    match_recognize_extension_planner as new_match_recognize_extension_planner,
};
use optimizer::{MatchRecognizePhysicalOptimizer, MatchRecognizeProjectionPushdown};
#[cfg(feature = "sql")]
use sql::MatchRecognizePlanner;

/// Build a DataFusion context with `MATCH_RECOGNIZE` support for the enabled
/// Cargo features.
///
/// This function consumes `builder` and performs these operations in order:
///
/// 1. Replace any configured query planner with the `MATCH_RECOGNIZE` query
///    planner and append the extension's physical optimizer rule.
/// 2. Build a [`SessionState`].
/// 3. Register the extension's scalar, window, and aggregate functions. An
///    existing function in the same registry with the same name is replaced.
/// 4. With the `sql` feature, prepend the `MATCH_RECOGNIZE` relation planner,
///    giving it priority over relation planners already on the state.
/// 5. Construct a new [`SessionContext`] and append the extension's logical
///    optimizer rule.
///
/// The installer preserves other builder fields. In particular, the supplied
/// session configuration and its extensions are preserved. It does not call
/// `with_default_features`. Applications that
/// want DataFusion's ordinary defaults must add them to the builder before this
/// call. The installer does not modify an existing [`SessionContext`] in place.
///
/// Function registration uses the following names:
///
/// - scalar: `match_number`, `match_sequence_number`, `classifier`, and
///   `excluded`;
/// - window: `first`, `last`, `prev`, and `next`;
/// - aggregate: `__mr_first_agg`, `__mr_last_agg`, `__mr_prev_agg`, and
///   `__mr_next_agg`. Zero-offset match-level `FIRST` and `LAST` continue to
///   use DataFusion's native `first_value` and `last_value` implementations.
///
/// Use the installer once when constructing a session state. Rebuilding from a
/// state that already contains this installation and applying it again replaces
/// the named functions, but adds another logical and physical optimizer rule
/// and, with the `sql` feature, another SQL relation planner.
///
/// Applications with a custom query planner can add
/// [`advanced::physical_extension_planner`] to it and append
/// [`advanced::physical_optimizer_rule`] to their builder. Complete registration
/// with [`advanced::register_state`] and [`advanced::register_optimizer_rules`].
///
/// Default runtime options work without explicitly inserting
/// [`MatchRecognizeConfig`]. Insert it into `SessionConfig` before building the
/// state when the application needs SQL `SET match_recognize.*` commands or
/// custom tuning.
///
/// # Errors
///
/// Returns an error propagated from registration of a scalar, window, or
/// aggregate function or, with the `sql` feature, from registration of the SQL
/// relation planner. No context is returned when registration fails.
pub fn new_match_recognize_context(
    builder: SessionStateBuilder,
) -> datafusion::common::Result<SessionContext> {
    let mut state = advanced::configure_builder(builder).build();
    advanced::register_state(&mut state)?;
    let ctx = SessionContext::new_with_state(state);
    advanced::register_optimizer_rules(&ctx);
    Ok(ctx)
}

/// Unstable hooks for hosts that perform DataFusion registration manually.
///
/// Most applications should use [`new_match_recognize_context`] instead. These
/// functions expose DataFusion registry ordering and are not part of the stable
/// application API.
///
/// A complete manual installation calls [`advanced::configure_builder`] or
/// configures a custom query planner containing the physical extension planner
/// and appends [`advanced::physical_optimizer_rule`] to its builder.
/// It then builds the [`SessionStateBuilder`], calls [`advanced::register_state`]
/// on that state, constructs a [`SessionContext`], and calls
/// [`advanced::register_optimizer_rules`] on the context. Call each hook once.
/// The hooks do not deduplicate optimizer rules or, with the `sql` feature, SQL
/// relation planners.
pub mod advanced {
    use super::*;

    /// Build the standard query planner with the host's physical extension
    /// planners followed by the `MATCH_RECOGNIZE` extension planner.
    ///
    /// This is the simplest composition path for hosts whose planner
    /// customization consists of DataFusion [`ExtensionPlanner`]s. Install the
    /// returned planner on a builder, build the state, then call
    /// [`register_state`] and [`register_optimizer_rules`].
    ///
    /// ```rust,no_run
    /// use std::sync::Arc;
    ///
    /// use datafusion::execution::{
    ///     SessionState, SessionStateBuilder, context::SessionContext,
    /// };
    /// use datafusion::physical_planner::ExtensionPlanner;
    /// use datafusion_match_recognize::advanced;
    ///
    /// # fn build(existing_state: SessionState) -> datafusion::error::Result<()> {
    /// let host_planners: Vec<Arc<dyn ExtensionPlanner + Send + Sync>> = vec![];
    /// let query_planner = advanced::query_planner_with_extensions(host_planners);
    /// let builder = SessionStateBuilder::new_from_existing(existing_state)
    ///     .with_query_planner(query_planner)
    ///     .with_physical_optimizer_rule(advanced::physical_optimizer_rule());
    /// let mut state = builder.build();
    /// advanced::register_state(&mut state)?;
    /// let ctx = SessionContext::new_with_state(state);
    /// advanced::register_optimizer_rules(&ctx);
    /// # let _ = ctx;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`ExtensionPlanner`]: datafusion::physical_planner::ExtensionPlanner
    pub fn query_planner_with_extensions(
        extension_planners: Vec<
            Arc<dyn datafusion::physical_planner::ExtensionPlanner + Send + Sync>,
        >,
    ) -> Arc<dyn datafusion::execution::context::QueryPlanner + Send + Sync> {
        Arc::new(MatchRecognizeQueryPlanner::with_extension_planners(
            extension_planners,
        ))
    }

    /// Return the physical extension planner for `MATCH_RECOGNIZE` nodes.
    ///
    /// Add this planner to the host query planner's extension-planner chain,
    /// preserving that custom query planner when building the state. DataFusion
    /// tries extension planners in order and uses the first one that handles a
    /// logical extension node. Append [`physical_optimizer_rule`] to the builder.
    /// After building the state, complete installation with [`register_state`],
    /// construct a [`SessionContext`], and call [`register_optimizer_rules`].
    pub fn physical_extension_planner()
    -> Arc<dyn datafusion::physical_planner::ExtensionPlanner + Send + Sync> {
        new_match_recognize_extension_planner()
    }

    /// Return the physical rule that optimizes matcher input and ordered output.
    ///
    /// Append it with [`SessionStateBuilder::with_physical_optimizer_rule`] when
    /// installing a custom query planner. [`configure_builder`] and the normal
    /// installer already append it. The rule restores eligible cheap constants
    /// after matcher input sorting and buffers eligible ordered output. Buffering
    /// skips known fetch paths and existing buffering boundaries, enforces a
    /// 256 MiB shared aggregate cap (with a per-partition floor) under unlimited
    /// memory pools, scales to a headroom-bounded aggregate fraction
    /// (`min(256 MiB, L / 8)`, pausing speculative lookahead at 75% pool
    /// utilization) under finite pools, and passes through when the per-partition
    /// share falls below 64 KiB or the pool limit is unknown.
    pub fn physical_optimizer_rule()
    -> Arc<dyn datafusion::physical_optimizer::PhysicalOptimizerRule + Send + Sync> {
        Arc::new(MatchRecognizePhysicalOptimizer)
    }

    /// Install the builder-time physical planning components.
    ///
    /// This replaces any query planner already configured on `builder`,
    /// installs the DataFusion 55 compatibility wrappers for `EnsureRequirements`
    /// sort/limit pushdown and leaf-expression projection merging, and appends
    /// [`physical_optimizer_rule`]. Other builder fields are preserved.
    /// Calling this hook repeatedly replaces the query planner and appends
    /// another physical rule each time.
    pub fn configure_builder(builder: SessionStateBuilder) -> SessionStateBuilder {
        let builder =
            compat::leaf_projections::install_leaf_projection_workaround(builder);
        compat::ensure_requirements::install_ensure_requirements_workaround(builder)
            .with_query_planner(Arc::new(MatchRecognizeQueryPlanner::new()))
            .with_physical_optimizer_rule(physical_optimizer_rule())
    }

    /// Register functions and the optional SQL relation planner on built state.
    ///
    /// Scalar functions are registered first, followed by window functions and
    /// aggregate functions. Existing entries with the same names are replaced.
    /// With the `sql` feature, the relation planner is registered last and is
    /// given priority over existing relation planners. The exact function names
    /// and collision behavior are listed by [`crate::new_match_recognize_context`].
    ///
    /// Calling this hook repeatedly replaces the named function entries rather
    /// than adding duplicates. With the `sql` feature, each call prepends
    /// another relation planner. Relation planners are not deduplicated.
    ///
    /// This operation mutates `state` as it proceeds. If registration returns an
    /// error, registrations completed before that error are not rolled back.
    ///
    /// # Errors
    ///
    /// Returns an error propagated from registration of a scalar, window, or
    /// aggregate function or, with the `sql` feature, from registration of the
    /// SQL relation planner.
    pub fn register_state(state: &mut SessionState) -> datafusion::common::Result<()> {
        functions::register_all(state)?;

        #[cfg(feature = "sql")]
        state.register_relation_planner(Arc::new(MatchRecognizePlanner))?;

        Ok(())
    }

    /// Append the logical optimizer rule to a context.
    ///
    /// Existing logical optimizer rules keep their order and the
    /// `MATCH_RECOGNIZE` rule is added at the end. Calling this hook repeatedly
    /// appends duplicate rules.
    pub fn register_optimizer_rules(ctx: &SessionContext) {
        ctx.add_optimizer_rule(Arc::new(MatchRecognizeProjectionPushdown::new()));
    }
}

/// Workspace-only hooks for Criterion benchmarks and developer tools.
#[cfg(feature = "internal-bench")]
#[doc(hidden)]
pub mod internal_bench {
    pub use crate::nfa::CompiledAutomaton;
    pub use crate::planning::logical::MatchRecognize;
    pub use crate::planning::physical_derivation::compile_match_program;
    pub use crate::planning::routed_program::MatchCompilerOptions;

    pub fn match_recognize_program(
        node: &MatchRecognize,
    ) -> &crate::planning::logical::LogicalMatchProgram {
        node.program()
    }
}

/// Workspace-only hooks for integration tests, reference oracles, and snapshot tooling.
#[cfg(feature = "test-support")]
#[doc(hidden)]
pub mod test_support {
    pub use crate::core::test_support::{EndPolicy, all_matches_with_policy};
    pub use crate::nfa::PatternOptimizer;
    pub use crate::planning::logical::{LogicalMatchProgram, MatchRecognize};
    pub use crate::planning::physical_derivation::compile_match_program;
    pub use crate::planning::predicate::{
        PredicateNode, VmBinaryOp, VmLiteral, VmSourceRef,
    };
    pub use crate::planning::routed_program::{MatchCompilerOptions, RoutedPredicate};
    #[cfg(feature = "sql")]
    pub use crate::sql::adapter::{
        build_parsed_match_clause, render_parsed_match_clause,
    };

    pub fn match_recognize_program(node: &MatchRecognize) -> &LogicalMatchProgram {
        node.program()
    }
}

#[cfg(all(test, feature = "substrait"))]
mod substrait_reexport_tests {
    use std::collections::BTreeSet;

    use crate::substrait::{
        DATAFUSION_EXCLUDED_FEATURE, DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE,
        DATAFUSION_SEMANTIC_ONE_ROW_FEATURE, DATAFUSION_WINDOW_MODIFIERS_FEATURE,
        MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE, MATCH_RECOGNIZE_EXTENSION_FEATURE,
        MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE,
        MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE,
        MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE,
        MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE,
    };

    #[test]
    fn facade_reexports_all_substrait_feature_constants() {
        let features = [
            MATCH_RECOGNIZE_EXTENSION_FEATURE,
            MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE,
            MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE,
            MATCH_RECOGNIZE_RELUCTANT_QUANTIFIERS_FEATURE,
            MATCH_RECOGNIZE_LOGICAL_NAVIGATION_OFFSET_FEATURE,
            MATCH_RECOGNIZE_COMPOUND_NAVIGATION_FEATURE,
            DATAFUSION_MATCH_SEQUENCE_NUMBER_FEATURE,
            DATAFUSION_EXCLUDED_FEATURE,
            DATAFUSION_WINDOW_MODIFIERS_FEATURE,
            DATAFUSION_SEMANTIC_ONE_ROW_FEATURE,
        ];
        assert!(features.iter().all(|feature| !feature.is_empty()));
        assert_eq!(features.into_iter().collect::<BTreeSet<_>>().len(), 10);
    }
}