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.

use std::any::Any;
use std::fmt;
use std::sync::{
    Arc,
    atomic::{AtomicUsize, Ordering},
};
use std::time::Duration;

use datafusion::common::human_readable_duration;
use datafusion::physical_plan::metrics::{
    BaselineMetrics, Count, CustomMetricValue, ExecutionPlanMetricsSet, MetricBuilder,
    MetricCategory, MetricValue,
};

/// Maximum poll duration in nanoseconds. DataFusion's ordinary Time adds values
/// across partitions, so this metric supplies its own merge operation.
#[derive(Debug, Default)]
struct PollTimeMax(AtomicUsize);

impl PollTimeMax {
    fn record(&self, nanos: usize) {
        if nanos > self.as_usize() {
            self.0.fetch_max(nanos, Ordering::Relaxed);
        }
    }
}

impl fmt::Display for PollTimeMax {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.as_usize() {
            0 => f.write_str("NOT RECORDED"),
            nanos => f.write_str(&human_readable_duration(nanos as u64)),
        }
    }
}

impl CustomMetricValue for PollTimeMax {
    fn new_empty(&self) -> Arc<dyn CustomMetricValue> {
        Arc::new(Self::default())
    }

    fn aggregate(&self, other: Arc<dyn CustomMetricValue>) {
        self.record(other.as_usize());
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_usize(&self) -> usize {
        self.0.load(Ordering::Relaxed)
    }

    fn is_eq(&self, other: &Arc<dyn CustomMetricValue>) -> bool {
        other.as_any().is::<Self>() && self.as_usize() == other.as_usize()
    }
}

/// Metrics recorded at a matcher execution boundary in one physical partition.
#[derive(Clone, Debug)]
pub struct PatternMetrics {
    pub baseline_metrics: BaselineMetrics,
    #[cfg(test)]
    pub(crate) partition_preparations: Count,
    #[cfg(test)]
    pub(crate) candidate_starts: Count,
    #[cfg(test)]
    pub(crate) accepted_edges: Count,
    poll_time_max: Arc<PollTimeMax>,
    pub route_scan_specialized: Count,
    pub route_scan_generic: Count,
    /// Candidates that executed at least one proved single-lane transition.
    pub route_scan_direct_linear: Count,
    /// Collection drives that read DEFINE or register inputs from bound Arrow columns.
    pub route_scan_bound_input: Count,
    /// Candidates resolved entirely inside the continuous batch loop.
    pub route_scan_continuous: Count,
    pub route_evaluator_static: Count,
    pub route_evaluator_direct_expr: Count,
    pub route_evaluator_accumulator: Count,
    pub route_evaluator_deferred: Count,
    pub route_evaluator_fallback: Count,
    pub route_tier_compact: Count,
    pub route_tier_standard: Count,
    pub route_tier_accumulator: Count,
    pub route_path_compact: Count,
    pub route_path_ordinary: Count,
    pub static_absence_pruned_partitions: Count,
    pub input_batches: Count,
    pub input_rows: Count,
    pub matches_emitted: Count,
    pub output_materializations: Count,
    pub output_compact_matches: Count,
    /// Native fields published in a bounded, fully admitted winner row.
    /// Selected measure values decoded from an immutable elected register frame.
    pub output_winning_register_values: Count,
    pub deferred_requests: Count,
}

impl PatternMetrics {
    /// Register only the common/static partition metrics.
    ///
    /// Stateful row-loop counters stay as unregistered `Count::default()` so
    /// purely static execution does not advertise stateful metrics in
    /// `ExecutionPlanMetricsSet`.
    pub fn new(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
        Self::build(metrics, partition, false)
    }

    /// Register both common and stateful row-loop metrics for match-aware execution.
    pub fn new_stateful(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
        Self::build(metrics, partition, true)
    }

    fn build(
        metrics: &ExecutionPlanMetricsSet,
        partition: usize,
        register_stateful: bool,
    ) -> Self {
        let count = |name| MetricBuilder::new(metrics).counter(name, partition);
        let stateful_count = |name| {
            if register_stateful {
                count(name)
            } else {
                Count::default()
            }
        };
        Self {
            // Keep the stateful counters first in the metric registration order.
            route_scan_direct_linear: stateful_count("route.scan.direct_linear"),
            route_scan_bound_input: stateful_count("route.scan.bound_input"),
            route_scan_continuous: stateful_count("route.scan.continuous"),
            output_winning_register_values: stateful_count(
                "output.winning_register_values",
            ),
            route_evaluator_direct_expr: stateful_count("route.evaluator.direct_expr"),
            route_evaluator_accumulator: stateful_count("route.evaluator.accumulator"),
            route_evaluator_deferred: stateful_count("route.evaluator.deferred"),
            route_evaluator_fallback: stateful_count("route.evaluator.fallback"),
            route_tier_compact: stateful_count("route.tier.compact"),
            route_tier_standard: stateful_count("route.tier.standard"),
            route_tier_accumulator: stateful_count("route.tier.accumulator"),
            deferred_requests: stateful_count("deferred_requests"),
            poll_time_max: {
                let poll_time_max = Arc::new(PollTimeMax::default());
                MetricBuilder::new(metrics)
                    .with_partition(partition)
                    .with_category(MetricCategory::Timing)
                    .build(MetricValue::Custom {
                        name: "poll_time_max".into(),
                        value: poll_time_max.clone(),
                    });
                poll_time_max
            },
            baseline_metrics: BaselineMetrics::new(metrics, partition),
            #[cfg(test)]
            partition_preparations: Count::default(),
            #[cfg(test)]
            candidate_starts: Count::default(),
            #[cfg(test)]
            accepted_edges: Count::default(),
            route_scan_specialized: count("route.scan.specialized"),
            route_scan_generic: count("route.scan.generic"),
            route_evaluator_static: count("route.evaluator.static"),
            route_path_compact: count("route.path.compact"),
            route_path_ordinary: count("route.path.ordinary"),
            static_absence_pruned_partitions: count("static_absence_pruned_partitions"),
            input_batches: count("input_batches"),
            input_rows: count("input_rows"),
            matches_emitted: count("matches_emitted"),
            output_materializations: count("output.materializations"),
            output_compact_matches: count("output.compact_matches"),
        }
    }

    pub(crate) fn record_poll_time(&self, elapsed: Duration) {
        self.poll_time_max
            .record(usize::try_from(elapsed.as_nanos()).unwrap_or(usize::MAX));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn poll_time_max_aggregates_by_maximum() {
        let metrics = ExecutionPlanMetricsSet::new();
        let first = PatternMetrics::new(&metrics, 0);
        let second = PatternMetrics::new(&metrics, 1);
        first.record_poll_time(Duration::from_millis(3));
        first.record_poll_time(Duration::from_millis(1));
        second.record_poll_time(Duration::from_millis(5));

        let per_partition = metrics.clone_inner();
        let poll_maxima = per_partition
            .iter()
            .filter(|metric| metric.value().name() == "poll_time_max")
            .map(|metric| (metric.partition(), metric.value().as_usize()))
            .collect::<Vec<_>>();
        assert_eq!(poll_maxima, [(Some(0), 3_000_000), (Some(1), 5_000_000)]);

        let aggregated = per_partition.aggregate_by_name();
        let peak = aggregated
            .iter()
            .find(|metric| metric.value().name() == "poll_time_max")
            .unwrap();
        assert_eq!(peak.partition(), None);
        assert_eq!(peak.metric_category(), Some(MetricCategory::Timing));
        assert_eq!(peak.value().as_usize(), 5_000_000);
        assert_eq!(peak.to_string(), "poll_time_max=5.00ms");
    }

    #[test]
    fn stateful_counters_are_registered_only_by_new_stateful() {
        let stateful_only = [
            "route.scan.direct_linear",
            "route.scan.bound_input",
            "route.scan.continuous",
            "output.winning_register_values",
            "route.evaluator.direct_expr",
            "route.evaluator.accumulator",
            "route.evaluator.deferred",
            "route.evaluator.fallback",
            "route.tier.compact",
            "route.tier.standard",
            "route.tier.accumulator",
            "deferred_requests",
        ];

        let static_set = ExecutionPlanMetricsSet::new();
        let _static_metrics = PatternMetrics::new(&static_set, 0);
        let static_names: Vec<_> = static_set
            .clone_inner()
            .iter()
            .map(|m| m.value().name().to_owned())
            .collect();
        for name in stateful_only {
            assert!(
                !static_names.iter().any(|n| n == name),
                "PatternMetrics::new registered stateful metric {name}: {static_names:?}"
            );
        }

        let stateful_set = ExecutionPlanMetricsSet::new();
        let _stateful_metrics = PatternMetrics::new_stateful(&stateful_set, 0);
        let stateful_names: Vec<_> = stateful_set
            .clone_inner()
            .iter()
            .map(|m| m.value().name().to_owned())
            .collect();
        for name in stateful_only {
            assert!(
                stateful_names.iter().any(|n| n == name),
                "PatternMetrics::new_stateful missed stateful metric {name}: {stateful_names:?}"
            );
        }
        assert_eq!(
            stateful_names.len(),
            static_names.len() + stateful_only.len()
        );
    }
}